text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
// TypeScript type definitions // // After modifying project's source code make appropriate changes to this file, // especially when you do one of the following: // - add/remove/rename a class // - add/remove/rename a method // - change method signature // declare namespace zipkin { interface Context<T> { setContext(ctx: T): void; getContext(): T; scoped<V>(callback: () => V): V; letContext<V>(ctx: T, callback: () => V): V; } namespace sampler { class Sampler { constructor(evaluator: (traceId: TraceId) => boolean); shouldSample(traceId: TraceId): option.IOption<boolean>; } class CountingSampler implements Sampler { constructor(sampleRate?: number); shouldSample(traceId: TraceId): option.IOption<boolean>; } const neverSample: (traceId: TraceId) => boolean; const alwaysSample: (traceId: TraceId) => boolean; } class Tracer { constructor(args: { ctxImpl: Context<TraceId>, recorder: Recorder, sampler?: sampler.Sampler, supportsJoin?: boolean, traceId128Bit?: boolean, localServiceName?: string, localEndpoint?: model.Endpoint, log?: Console, defaultTags?: {} }); /** Returns the current trace ID or a sentinel value indicating its absence. */ id: TraceId; scoped<V>(callback: () => V): V; local<V>(name: string, callback: () => V): V; createRootId(isSampled?: option.IOption<boolean>, isDebug?: boolean): TraceId; /** Creates a child of the current trace ID or a new root span. */ createChildId(parentId?: TraceId): TraceId; letId<V>(traceId: TraceId, callback: () => V): V; setId(traceId: TraceId): void; recordAnnotation(annotation: IAnnotation, timestamp?: number): void; recordMessage(message: string): void; recordServiceName(serviceName: string): void; recordRpc(name: string): void; recordClientAddr(inetAddress: InetAddress): void; recordServerAddr(inetAddress: InetAddress): void; recordLocalAddr(inetAddress: InetAddress): void; recordBinary(key: string, value: boolean | string | number): void; writeIdToConsole(message: any): void; } class TraceId { readonly traceId: string; readonly parentSpanId: option.IOption<string>; readonly spanId: string; readonly sampled: option.IOption<boolean>; isDebug(): boolean; isShared(): boolean; constructor(args?: { traceId?: string, parentId?: option.IOption<string>, spanId?: string, sampled?: option.IOption<boolean>, debug?: boolean, shared?: boolean }); toString(): string; } const createNoopTracer: () => Tracer; const randomTraceId: () => string; namespace option { abstract class Option<T> { map<V>(fn: (value: T) => V): IOption<V>; ifPresent(fn: (value: T) => any): void; flatMap<V>(fn: (value: T) => IOption<V>): IOption<V>; getOrElse(fnOrValue: (() => T) | T): T; equals(other: IOption<T>): boolean; toString(): string; } class Some<T> extends Option<T> { constructor(value: T); readonly type: 'Some'; readonly present: true; } interface INone<T> extends Option<T> { readonly type: 'None'; readonly present: false; } type IOption<T> = Some<T> | INone<T>; const None: INone<never>; function isOptional(data: any): boolean; function verifyIsOptional(data: any): void; // Throw error is not a valid option function fromNullable<V>(nullable: V): IOption<V>; } namespace model { class Endpoint { constructor(args: { serviceName?: string, ipv4?: string, port?: number }); setServiceName(serviceName: string): void; setIpv4(ipv4: string): void; setPort(port: number): void; isEmpty(): boolean; } interface Annotation { timestamp: number; value: string; } class Span { readonly traceId: string; readonly parentId?: string; readonly id: string; readonly name?: string; readonly kind?: string; readonly timestamp?: number; readonly duration?: number; readonly localEndpoint?: Endpoint; readonly remoteEndpoint?: Endpoint; readonly annotations: Annotation[]; readonly tags: { [ key: string ]: string }; readonly debug: boolean; readonly shared: boolean; constructor(traceId: TraceId) setName(name: string): void; setKind(kind: string): void; setTimestamp(timestamp: number): void; setDuration(duration: number): void; setLocalEndpoint(endpoint: Endpoint): void; setRemoteEndpoint(endpoint: Endpoint): void; addAnnotation(timestamp: number, value: string): void; putTag(key: string, value: string): void; setDebug(debug: boolean): void; setShared(shared: boolean): void; } } /** Used by the HttpLogger transport to convert spans to JSON */ interface JsonEncoder { encode(span: model.Span): string; } namespace jsonEncoder { const JSON_V1: JsonEncoder; const JSON_V2: JsonEncoder; } interface IAnnotation { readonly annotationType: string; } namespace Annotation { class ClientSend implements IAnnotation { readonly annotationType: string; } class ClientRecv implements IAnnotation { readonly annotationType: string; } class ServerSend implements IAnnotation { readonly annotationType: string; } class ServerRecv implements IAnnotation { readonly annotationType: string; } class ProducerStart implements IAnnotation { readonly annotationType: string; } class ProducerStop implements IAnnotation { readonly annotationType: string; } class ConsumerStart implements IAnnotation { readonly annotationType: string; } class ConsumerStop implements IAnnotation { readonly annotationType: string; } class MessageAddr implements IAnnotation { constructor(args: { serviceName: string, host?: InetAddress, port?: number }); readonly annotationType: string; serviceName: string; host: InetAddress; port: number; } class LocalOperationStart implements IAnnotation { constructor(name: string); readonly annotationType: string; name: string; } class LocalOperationStop implements IAnnotation { readonly annotationType: string; } class Message implements IAnnotation { constructor(message: string); readonly annotationType: string; message: string; } class ServiceName implements IAnnotation { constructor(serviceName: string); readonly annotationType: string; serviceName: string; } class Rpc implements IAnnotation { constructor(name: string); readonly annotationType: string; name: string; } class ClientAddr implements IAnnotation { constructor(args: { host: InetAddress, port: number }); readonly annotationType: string; } class ServerAddr implements IAnnotation { constructor(args: { serviceName: string, host?: InetAddress, port?: number }); readonly annotationType: string; serviceName: string; host: InetAddress; port: number; } class LocalAddr implements IAnnotation { constructor(args?: { host?: InetAddress, port?: number }); readonly annotationType: string; host: InetAddress; port: number; } class BinaryAnnotation implements IAnnotation { constructor(key: string, value: string); readonly annotationType: string; key: string; value: string; } } class InetAddress { constructor(addr: string); static getLocalAddress(): InetAddress; ipv4(): string; toInt(): number; } namespace HttpHeaders { const TraceId: string; const SpanId: string; const ParentSpanId: string; const Sampled: string; const Flags: string; } interface Record { traceId: TraceId; timestamp: number; annotation: IAnnotation; } /** The Tracer sends each annotation to a Recorder implementation */ interface Recorder { record(rec: Record): void; } class BatchRecorder implements Recorder { /** * @constructor * @param {Object} args * @param {Logger} args.logger logs the data to zipkin server * @param {number} args.timeout timeout after which an unfinished span is * flushed to zipkin in **microseconds**. Passing this value has * implications in the reported data of the span so we discourage users * to pass a value for it unless there is a good reason for. */ constructor(args: { logger: Logger, timeout?: number }); record: (rec: Record) => void; flush: () => void; } class ConsoleRecorder implements Recorder { constructor(logger?: (message: string) => void); record: (rec: Record) => void; } class ExplicitContext implements Context<TraceId> { setContext(ctx: TraceId): void; getContext(): TraceId; scoped<V>(callback: () => V): V; letContext<V>(ctx: TraceId, callback: () => V): V; } type RequestZipkinHeaders<T = any, H = any> = T & { headers: H & { ['X-B3-TraceId']: string; ['X-B3-SpanId']: string; ['X-B3-ParentSpanId']?: string; ['X-B3-Sampled']?: '1' | '0'; ['X-B3-Flags']?: '1' | '0'; }; }; namespace Request { function addZipkinHeaders<T, H>(req: T & { headers?: any }, traceId: TraceId): RequestZipkinHeaders<T, H>; } /** The Logger (or transport) is what the Recorder uses to send spans to Zipkin. * @see https://github.com/openzipkin/zipkin-js/#transports Official transport implementations */ interface Logger { logSpan(span: model.Span): void; } namespace Instrumentation { class HttpServer { constructor(args: { tracer: Tracer, port: number, serviceName?: string, host?: string, serverTags?: {[key: string]: string} }); recordRequest( method: string, requestUrl: string, readHeader: <T> (header: string) => option.IOption<T> ): TraceId; recordResponse(traceId: TraceId, statusCode: string, error?: Error): void; } class HttpClient { constructor(args: { tracer: Tracer, serviceName?: string, remoteServiceName?: string }); recordRequest<T>( request: T, url: string, method: string ): T; recordResponse(traceId: TraceId, statusCode: string): void; recordError(traceId: TraceId, error: Error): void; } } } export = zipkin;
the_stack
import { RSA } from './rsa'; import { IllegalArgumentError, IllegalStateError, SecurityError } from '../other/errors'; import { Sha512 } from '../hash/sha512/sha512'; import { Sha1 } from '../hash/sha1/sha1'; import { Sha256 } from '../hash/sha256/sha256'; import { BigNumber } from '../bignum/bignum'; import { getRandomValues } from '../other/get-random-values'; export class RSA_OAEP { private readonly rsa: RSA; private readonly label: Uint8Array | null; private readonly hash: Sha1 | Sha256 | Sha512; constructor(key: Uint8Array[], hash: Sha1 | Sha256 | Sha512, label?: Uint8Array) { this.rsa = new RSA(key); this.hash = hash; if (label !== undefined) { this.label = label.length > 0 ? label : null; } else { this.label = null; } } encrypt(data: Uint8Array, random?: Uint8Array): Uint8Array { const key_size = Math.ceil(this.rsa.key[0].bitLength / 8); const hash_size = this.hash.HASH_SIZE; const data_length = data.byteLength || data.length || 0; const ps_length = key_size - data_length - 2 * hash_size - 2; if (data_length > key_size - 2 * this.hash.HASH_SIZE - 2) throw new IllegalArgumentError('data too large'); const message = new Uint8Array(key_size); const seed = message.subarray(1, hash_size + 1); const data_block = message.subarray(hash_size + 1); data_block.set(data, hash_size + ps_length + 1); data_block.set(this.hash.process(this.label || new Uint8Array(0)).finish().result as Uint8Array, 0); data_block[hash_size + ps_length] = 1; if (random !== undefined) { if (seed.length !== random.length) throw new IllegalArgumentError('random size must equal the hash size'); seed.set(random); } else { getRandomValues(seed); } const data_block_mask = this.RSA_MGF1_generate(seed, data_block.length); for (let i = 0; i < data_block.length; i++) data_block[i] ^= data_block_mask[i]; const seed_mask = this.RSA_MGF1_generate(data_block, seed.length); for (let i = 0; i < seed.length; i++) seed[i] ^= seed_mask[i]; this.rsa.encrypt(new BigNumber(message)); return new Uint8Array(this.rsa.result); } decrypt(data: Uint8Array): Uint8Array { if (!this.rsa.key) throw new IllegalStateError('no key is associated with the instance'); const key_size = Math.ceil(this.rsa.key[0].bitLength / 8); const hash_size = this.hash.HASH_SIZE; const data_length = data.byteLength || data.length || 0; if (data_length !== key_size) throw new IllegalArgumentError('bad data'); this.rsa.decrypt(new BigNumber(data)); const z = this.rsa.result[0]; const seed = this.rsa.result.subarray(1, hash_size + 1); const data_block = this.rsa.result.subarray(hash_size + 1); if (z !== 0) throw new SecurityError('decryption failed'); const seed_mask = this.RSA_MGF1_generate(data_block, seed.length); for (let i = 0; i < seed.length; i++) seed[i] ^= seed_mask[i]; const data_block_mask = this.RSA_MGF1_generate(seed, data_block.length); for (let i = 0; i < data_block.length; i++) data_block[i] ^= data_block_mask[i]; const lhash = this.hash .reset() .process(this.label || new Uint8Array(0)) .finish().result as Uint8Array; for (let i = 0; i < hash_size; i++) { if (lhash[i] !== data_block[i]) throw new SecurityError('decryption failed'); } let ps_end = hash_size; for (; ps_end < data_block.length; ps_end++) { const psz = data_block[ps_end]; if (psz === 1) break; if (psz !== 0) throw new SecurityError('decryption failed'); } if (ps_end === data_block.length) throw new SecurityError('decryption failed'); this.rsa.result = data_block.subarray(ps_end + 1); return new Uint8Array(this.rsa.result); } RSA_MGF1_generate(seed: Uint8Array, length: number = 0): Uint8Array { const hash_size = this.hash.HASH_SIZE; // if ( length > (hash_size * 0x100000000) ) // throw new IllegalArgumentError("mask length too large"); const mask = new Uint8Array(length); const counter = new Uint8Array(4); const chunks = Math.ceil(length / hash_size); for (let i = 0; i < chunks; i++) { (counter[0] = i >>> 24), (counter[1] = (i >>> 16) & 255), (counter[2] = (i >>> 8) & 255), (counter[3] = i & 255); const submask = mask.subarray(i * hash_size); let chunk = this.hash .reset() .process(seed) .process(counter) .finish().result as Uint8Array; if (chunk.length > submask.length) chunk = chunk.subarray(0, submask.length); submask.set(chunk); } return mask; } } export class RSA_PSS { private readonly rsa: RSA; private readonly saltLength: number; private readonly hash: Sha1 | Sha256 | Sha512; constructor(key: Uint8Array[], hash: Sha1 | Sha256 | Sha512, saltLength: number = 4) { this.rsa = new RSA(key); this.hash = hash; this.saltLength = saltLength; if (this.saltLength < 0) throw new TypeError('saltLength should be a non-negative number'); if ( this.rsa.key !== null && Math.ceil((this.rsa.key[0].bitLength - 1) / 8) < this.hash.HASH_SIZE + this.saltLength + 2 ) throw new SyntaxError('saltLength is too large'); } sign(data: Uint8Array, random?: Uint8Array): Uint8Array { const key_bits = this.rsa.key[0].bitLength; const hash_size = this.hash.HASH_SIZE; const message_length = Math.ceil((key_bits - 1) / 8); const salt_length = this.saltLength; const ps_length = message_length - salt_length - hash_size - 2; const message = new Uint8Array(message_length); const h_block = message.subarray(message_length - hash_size - 1, message_length - 1); const d_block = message.subarray(0, message_length - hash_size - 1); const d_salt = d_block.subarray(ps_length + 1); const m_block = new Uint8Array(8 + hash_size + salt_length); const m_hash = m_block.subarray(8, 8 + hash_size); const m_salt = m_block.subarray(8 + hash_size); m_hash.set(this.hash.process(data).finish().result as Uint8Array); if (salt_length > 0) { if (random !== undefined) { if (m_salt.length !== random.length) throw new IllegalArgumentError('random size must equal the salt size'); m_salt.set(random); } else { getRandomValues(m_salt); } } d_block[ps_length] = 1; d_salt.set(m_salt); h_block.set(this.hash .reset() .process(m_block) .finish().result as Uint8Array); const d_block_mask = this.RSA_MGF1_generate(h_block, d_block.length); for (let i = 0; i < d_block.length; i++) d_block[i] ^= d_block_mask[i]; message[message_length - 1] = 0xbc; const zbits = 8 * message_length - key_bits + 1; if (zbits % 8) message[0] &= 0xff >>> zbits; this.rsa.decrypt(new BigNumber(message)); return this.rsa.result; } verify(signature: Uint8Array, data: Uint8Array): void { const key_bits = this.rsa.key[0].bitLength; const hash_size = this.hash.HASH_SIZE; const message_length = Math.ceil((key_bits - 1) / 8); const salt_length = this.saltLength; const ps_length = message_length - salt_length - hash_size - 2; this.rsa.encrypt(new BigNumber(signature)); const message = this.rsa.result; if (message[message_length - 1] !== 0xbc) throw new SecurityError('bad signature'); const h_block = message.subarray(message_length - hash_size - 1, message_length - 1); const d_block = message.subarray(0, message_length - hash_size - 1); const d_salt = d_block.subarray(ps_length + 1); const zbits = 8 * message_length - key_bits + 1; if (zbits % 8 && message[0] >>> (8 - zbits)) throw new SecurityError('bad signature'); const d_block_mask = this.RSA_MGF1_generate(h_block, d_block.length); for (let i = 0; i < d_block.length; i++) d_block[i] ^= d_block_mask[i]; if (zbits % 8) message[0] &= 0xff >>> zbits; for (let i = 0; i < ps_length; i++) { if (d_block[i] !== 0) throw new SecurityError('bad signature'); } if (d_block[ps_length] !== 1) throw new SecurityError('bad signature'); const m_block = new Uint8Array(8 + hash_size + salt_length); const m_hash = m_block.subarray(8, 8 + hash_size); const m_salt = m_block.subarray(8 + hash_size); m_hash.set(this.hash .reset() .process(data) .finish().result as Uint8Array); m_salt.set(d_salt); const h_block_verify = this.hash .reset() .process(m_block) .finish().result as Uint8Array; for (let i = 0; i < hash_size; i++) { if (h_block[i] !== h_block_verify[i]) throw new SecurityError('bad signature'); } } RSA_MGF1_generate(seed: Uint8Array, length: number = 0): Uint8Array { const hash_size = this.hash.HASH_SIZE; // if ( length > (hash_size * 0x100000000) ) // throw new IllegalArgumentError("mask length too large"); const mask = new Uint8Array(length); const counter = new Uint8Array(4); const chunks = Math.ceil(length / hash_size); for (let i = 0; i < chunks; i++) { (counter[0] = i >>> 24), (counter[1] = (i >>> 16) & 255), (counter[2] = (i >>> 8) & 255), (counter[3] = i & 255); const submask = mask.subarray(i * hash_size); let chunk = this.hash .reset() .process(seed) .process(counter) .finish().result as Uint8Array; if (chunk.length > submask.length) chunk = chunk.subarray(0, submask.length); submask.set(chunk); } return mask; } } export class RSA_PKCS1_v1_5 { private readonly rsa: RSA; private readonly hash: Sha1 | Sha256 | Sha512; constructor(key: Uint8Array[], hash: Sha1 | Sha256 | Sha512) { this.rsa = new RSA(key); this.hash = hash; } sign(data: Uint8Array): Uint8Array { if (!this.rsa.key) { throw new IllegalStateError('no key is associated with the instance'); } const prefix = getHashPrefix(this.hash); const hash_size = this.hash.HASH_SIZE; const t_len = prefix.length + hash_size; const k = (this.rsa.key[0].bitLength + 7) >> 3; if (k < t_len + 11) { throw new Error('Message too long'); } const m_hash = new Uint8Array(hash_size); m_hash.set(this.hash.process(data).finish().result as Uint8Array); // EM = 0x00 || 0x01 || PS || 0x00 || T const em = new Uint8Array(k); let i = 0; em[i++] = 0; // 0x00 em[i++] = 1; // 0x01 // PS for (i; i < k - t_len - 1; i++) { em[i] = 0xff; } em[i++] = 0; em.set(prefix, i); // 0x00 // T em.set(m_hash, em.length - hash_size); this.rsa.decrypt(new BigNumber(em)); return this.rsa.result; } verify(signature: Uint8Array, data: Uint8Array): void { const prefix = getHashPrefix(this.hash); const hash_size = this.hash.HASH_SIZE; const t_len = prefix.length + hash_size; const k = (this.rsa.key[0].bitLength + 7) >> 3; if (k < t_len + 11) { throw new SecurityError('Bad signature'); } this.rsa.encrypt(new BigNumber(signature)); const m_hash = new Uint8Array(hash_size); m_hash.set(this.hash.process(data).finish().result as Uint8Array); let res = 1; // EM = 0x00 || 0x01 || PS || 0x00 || T const decryptedSignature = this.rsa.result; let i = 0; res &= decryptedSignature[i++] === 0 ? 1 : 0; // 0x00 res &= decryptedSignature[i++] === 1 ? 1 : 0; // 0x01 // PS for (i; i < k - t_len - 1; i++) { res &= decryptedSignature[i] === 0xff ? 1 : 0; } res &= decryptedSignature[i++] === 0 ? 1 : 0; // 0x00 // T let j = 0; let n = i + prefix.length; // prefix for (i; i < n; i++) { res &= decryptedSignature[i] === prefix[j++] ? 1 : 0; } j = 0; n = i + m_hash.length; // hash for (i; i < n; i++) { res &= decryptedSignature[i] === m_hash[j++] ? 1 : 0; } if (!res) { throw new SecurityError('Bad signature'); } } } const HASH_PREFIXES: { sha1: Uint8Array; sha256: Uint8Array; sha384: Uint8Array; sha512: Uint8Array; [key: string]: Uint8Array; } = { sha1: new Uint8Array([0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14]), sha256: new Uint8Array([ 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20, ]), sha384: new Uint8Array([ 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30, ]), sha512: new Uint8Array([ 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40, ]), }; function getHashPrefix(hash: Sha1 | Sha256 | Sha512): Uint8Array { const prefix = HASH_PREFIXES[hash.NAME]; if (!prefix) { throw new Error("Cannot get hash prefix for hash algorithm '" + hash.NAME + "'"); } return prefix; }
the_stack
import * as chai from 'chai'; import * as chaiAsPromised from 'chai-as-promised'; import * as sinon from 'sinon'; import { isEqual } from 'lodash'; import gql from 'graphql-tag'; import { print } from 'graphql'; import * as fetchMock from 'fetch-mock'; import { createApolloFetch, constructDefaultOptions, } from '../src/apollo-fetch'; import { RequestAndOptions, FetchResult } from '../src/types'; chai.use(chaiAsPromised); const { assert, expect } = chai; const sampleQuery = gql` query SampleQuery { stub { id } } `; const simpleQueryWithNoVars = gql` query people { allPeople(first: 1) { people { name } } } `; const simpleQueryWithVar = gql` query people($personNum: Int!) { allPeople(first: $personNum) { people { name } } } `; const simpleResult = { data: { allPeople: { people: [ { name: 'Luke Skywalker', }, ], }, }, }; const complexQueryWithTwoVars = gql` query people($personNum: Int!, $filmNum: Int!) { allPeople(first: $personNum) { people { name filmConnection(first: $filmNum) { edges { node { id } } } } } } `; const complexResult = { data: { allPeople: { people: [ { name: 'Luke Skywalker', filmConnection: { edges: [ { node: { id: 'ZmlsbXM6MQ==', }, }, ], }, }, ], }, }, }; const swapiUrl = 'http://graphql-swapi.test/'; const unauthorizedUrl = 'http://unauthorized.test/'; const forbiddenUrl = 'http://forbidden.test/'; const serviceUnavailableUrl = 'http://service-unavailable.test/'; const missingUrl = 'http://does-not-exist.test/'; const swapiResolver = (url, opts) => { const { query, variables } = JSON.parse( (opts as RequestInit).body!.toString(), ); if (query === print(simpleQueryWithNoVars)) { return simpleResult; } if ( query === print(simpleQueryWithVar) && isEqual(variables, { personNum: 1 }) ) { return simpleResult; } if ( query === print(complexQueryWithTwoVars) && isEqual(variables, { personNum: 1, filmNum: 1 }) ) { return complexResult; } throw new Error('Invalid Query'); }; describe('apollo-fetch', () => { describe('single request', () => { const postData = { hello: 'world', method: 'POST' }; const data = JSON.stringify({ data: { hello: 'world', uri: '/graphql' } }); const alternateData = JSON.stringify({ data: { hello: 'alternate world', uri: 'alternate' }, }); const unparsableData = 'raw string'; const unauthorizedData = { data: { user: null, }, }; const mockError = { throws: new TypeError('mock me') }; before(() => { fetchMock.post('/graphql', data); fetchMock.post('alternate', alternateData); fetchMock.post('/raw', unparsableData); fetchMock.post('data', postData); fetchMock.post('error', mockError); fetchMock.post('test', data); fetchMock.post(unauthorizedUrl, unauthorizedData); fetchMock.post(swapiUrl, swapiResolver); fetchMock.post(missingUrl, () => { throw new Error('Network error'); }); fetchMock.post(forbiddenUrl, 403); fetchMock.post(serviceUnavailableUrl, 503); }); afterEach(fetchMock.reset); after(fetchMock.restore); it('should not throw with no arguments', () => { assert.doesNotThrow(createApolloFetch); }); it('should call fetch', () => { const fetcher = createApolloFetch(); const result = fetcher({ query: print(sampleQuery) }); return result.then(response => { assert.deepEqual(fetchMock.calls('/graphql').length, 1); assert.deepEqual(response, JSON.parse(data)); }); }); const callAndCheckFetch = (uri, fetcher) => { const result = fetcher({ query: print(sampleQuery) }); return result.then(response => { //correct response assert.deepEqual(response, JSON.parse(data)); assert.deepEqual(fetchMock.lastCall(uri)[0], uri); const options = fetchMock.lastCall(uri)[1]; const body = JSON.parse((<RequestInit>options).body); assert.deepEqual(options.method, 'POST'); assert.deepEqual(options.headers, { Accept: '*/*', 'Content-Type': 'application/json', }); assert.deepEqual(body.query, print(sampleQuery)); }); }; it('should call fetch with correct arguments and result', () => { const uri = 'test'; const fetcher = createApolloFetch({ uri }); return callAndCheckFetch(uri, fetcher); }); it('should make two successful requests', () => { const uri = 'test'; const fetcher = createApolloFetch({ uri }); return callAndCheckFetch(uri, fetcher).then(() => callAndCheckFetch(uri, fetcher), ); }); it('should pass an error onto the Promise', () => { const uri = 'error'; const fetcher = createApolloFetch({ uri, customFetch: fetch }); const result = fetcher({ query: print(sampleQuery) }); return assert.isRejected( result, mockError.throws, mockError.throws.message, ); }); it('should catch on a network error', () => { const fetcher = createApolloFetch({ uri: forbiddenUrl }); const result = fetcher({ query: print(sampleQuery) }); return result.then(expect.fail).catch(error => { assert.deepEqual( error.message, 'Network request failed with status 403 - "Forbidden"', ); assert.isDefined(error.response); assert.isDefined(error.parseError); }); }); it('should return a fail to parse response when fetch returns raw response', () => { const fetcher = createApolloFetch({ uri: '/raw' }); const result = fetcher({ query: print(sampleQuery) }); return result.then(expect.fail).catch(error => { assert.deepEqual( error.message, 'Network request failed to return valid JSON', ); assert.isDefined(error.response); assert.deepEqual(error.response.raw, unparsableData); }); }); it('should pass the parsed response if valid regardless of the status', () => { const fetcher = createApolloFetch({ uri: unauthorizedUrl, customFetch: () => new Promise((resolve, reject) => { const init = { status: 401, statusText: 'Unauthorized', }; const body = JSON.stringify(unauthorizedData); resolve(new Response(body, init)); }), }); return fetcher({ query: print(sampleQuery) }).then(result => { assert.deepEqual(result.data, unauthorizedData.data); }); }); }); describe('middleware', () => { before(() => { fetchMock.post(swapiUrl, swapiResolver); }); afterEach(fetchMock.reset); after(fetchMock.restore); it('should throw an error if middleware is not a function', () => { const malWare: any = {}; const apolloFetch = createApolloFetch({ uri: '/graphql' }); try { apolloFetch.use(malWare); expect.fail(); } catch (error) { assert.equal(error.message, 'Middleware must be a function'); } }); it('should return errors thrown in middlewares', () => { const apolloFetch = createApolloFetch({ uri: swapiUrl }); apolloFetch.use(() => { throw Error('Middleware error'); }); const simpleRequest = { query: print(simpleQueryWithNoVars), variables: {}, debugName: 'People query', }; return assert.isRejected( apolloFetch(simpleRequest), Error, 'Middleware error', ); }); it('can alter the request variables', () => { const testWare1 = TestWare([{ key: 'personNum', val: 1 }]); const swapi = createApolloFetch({ uri: swapiUrl }); swapi.use(testWare1); // this is a stub for the end user client api const simpleRequest = { query: print(simpleQueryWithVar), variables: {}, debugName: 'People query', }; return assert.eventually.deepEqual(swapi(simpleRequest), simpleResult); }); it('can alter the options', () => { const testWare1 = TestWare([], [{ key: 'planet', val: 'mars' }]); const swapi = createApolloFetch({ uri: swapiUrl }); swapi.use(testWare1); // this is a stub for the end user client api const simpleRequest = { query: print(simpleQueryWithNoVars), variables: {}, debugName: 'People query', }; return swapi(simpleRequest).then(() => { assert.equal((fetchMock.lastCall()[1] as any).planet, 'mars'); }); }); it('can alter the request body params', () => { const testWare1 = TestWare( [], [], [{ key: 'newParam', val: '0123456789' }], ); const swapi = createApolloFetch({ uri: 'http://graphql-swapi.test/' }); swapi.use(testWare1); const simpleRequest = { query: print(simpleQueryWithVar), variables: { personNum: 1 }, debugName: 'People query', }; return swapi(simpleRequest).then(() => { return assert.deepEqual( JSON.parse((fetchMock.lastCall()[1] as any).body), { query: 'query people($personNum: Int!) {\n allPeople(first: $personNum) {\n people {\n name\n }\n }\n}\n', variables: { personNum: 1 }, debugName: 'People query', newParam: '0123456789', }, ); }); }); it('handle multiple middlewares', () => { const testWare1 = TestWare([{ key: 'personNum', val: 1 }]); const testWare2 = TestWare([{ key: 'filmNum', val: 1 }]); const swapi = createApolloFetch({ uri: 'http://graphql-swapi.test/' }); swapi.use(testWare1).use(testWare2); // this is a stub for the end user client api const simpleRequest = { query: print(complexQueryWithTwoVars), variables: {}, debugName: 'People query', }; return assert.eventually.deepEqual(swapi(simpleRequest), complexResult); }); it('should chain use() calls', () => { const testWare1 = TestWare([{ key: 'personNum', val: 1 }]); const testWare2 = TestWare([{ key: 'filmNum', val: 1 }]); const swapi = createApolloFetch({ uri: swapiUrl }); swapi.use(testWare1).use(testWare2); const simpleRequest = { query: print(complexQueryWithTwoVars), variables: {}, debugName: 'People query', }; return assert.eventually.deepEqual(swapi(simpleRequest), complexResult); }); }); describe('afterware', () => { before(() => { fetchMock.post(swapiUrl, swapiResolver); fetchMock.post(forbiddenUrl, 403); }); afterEach(fetchMock.reset); after(fetchMock.restore); it('should return errors thrown in afterwares', () => { const apolloFetch = createApolloFetch({ uri: swapiUrl }); apolloFetch.useAfter(() => { throw Error('Afterware error'); }); const simpleRequest = { query: print(simpleQueryWithNoVars), variables: {}, debugName: 'People query', }; return assert.isRejected( apolloFetch(simpleRequest), Error, 'Afterware error', ); }); it('should throw an error if afterware is not a function', () => { const malWare = {} as any; const apolloFetch = createApolloFetch({ uri: '/graphql' }); try { apolloFetch.useAfter(malWare); expect.fail(); } catch (error) { assert.equal(error.message, 'Afterware must be a function'); } }); it('can modify response to add data when response is not parsable', () => { const parsedData = { data: { mock: 'stub', }, }; const afterware = ({ response }, next) => { assert.deepEqual(response.status, 403); assert.deepEqual(response.raw, ''); assert.isUndefined(response.parsed); response.parsed = parsedData; next(); }; const apolloFetch = createApolloFetch({ uri: forbiddenUrl }); apolloFetch.useAfter(afterware); return assert.eventually.deepEqual( apolloFetch({ query: '' }), parsedData, ); }); it('handle multiple afterware', () => { const spy = sinon.spy(); const afterware1 = ({ response }, next) => { assert.deepEqual(response.status, 200); spy(); next(); }; const afterware2 = ({ response }, next) => { spy(); next(); }; const swapi = createApolloFetch({ uri: 'http://graphql-swapi.test/' }); swapi.useAfter(afterware1); swapi.useAfter(afterware2); // this is a stub for the end user client api const simpleRequest = { query: print(complexQueryWithTwoVars), variables: { personNum: 1, filmNum: 1, }, debugName: 'People query', }; return swapi(simpleRequest) .then(result => { assert.deepEqual(result, <FetchResult>complexResult); assert(spy.calledTwice, 'both afterware should be called'); }) .catch(console.log); }); }); describe('multiple requests', () => { before(() => { fetchMock.post(swapiUrl, swapiResolver); }); afterEach(fetchMock.reset); after(fetchMock.restore); it('handle multiple middlewares', () => { const testWare1 = TestWare([{ key: 'personNum', val: 1 }]); const testWare2 = TestWare([{ key: 'filmNum', val: 1 }]); const swapi = createApolloFetch({ uri: 'http://graphql-swapi.test/' }); swapi.use(testWare1).use(testWare2); // this is a stub for the end user client api const simpleRequest = { query: print(complexQueryWithTwoVars), variables: {}, debugName: 'People query', }; return assert.eventually .deepEqual(swapi(simpleRequest), complexResult) .then(() => assert.eventually.deepEqual(swapi(simpleRequest), complexResult), ); }); it('handle multiple afterware', () => { const spy = sinon.spy(); const afterware1 = ({ response }, next) => { assert.deepEqual(response.status, 200); spy(); next(); }; const afterware2 = ({ response }, next) => { spy(); next(); }; const swapi = createApolloFetch({ uri: 'http://graphql-swapi.test/' }); swapi.useAfter(afterware1).useAfter(afterware2); // this is a stub for the end user client api const simpleRequest = { query: print(complexQueryWithTwoVars), variables: { personNum: 1, filmNum: 1, }, debugName: 'People query', }; return swapi(simpleRequest) .then(result => { assert.deepEqual(result, <FetchResult>complexResult); assert(spy.calledTwice, 'both afterware should be called'); spy.reset(); }) .then(() => swapi(simpleRequest).then(result => { assert.deepEqual(result, <FetchResult>complexResult); assert(spy.calledTwice, 'both afterware should be called'); }), ); }); it('handle multiple middleware and afterware', () => { const testWare1 = TestWare([{ key: 'personNum', val: 1 }]); const testWare2 = TestWare([{ key: 'filmNum', val: 1 }]); const spy = sinon.spy(); const afterware1 = ({ response }, next) => { assert.deepEqual(response.status, 200); spy(); next(); }; const afterware2 = ({ response }, next) => { spy(); next(); }; const swapi = createApolloFetch({ uri: 'http://graphql-swapi.test/' }); swapi .useAfter(afterware1) .useAfter(afterware2) .use(testWare1) .use(testWare2); // this is a stub for the end user client api const simpleRequest = { query: print(complexQueryWithTwoVars), variables: {}, debugName: 'People query', }; return swapi(simpleRequest) .then(result => { assert.deepEqual(result, <FetchResult>complexResult); assert(spy.calledTwice, 'both afterware should be called'); spy.reset(); }) .then(() => swapi(simpleRequest).then(result => { assert.deepEqual(result, <FetchResult>complexResult); assert(spy.calledTwice, 'both afterware should be called'); }), ); }); }); describe('batched query', () => { const data = { data: { hello: 'world', uri: '/graphql' } }; const batch = [data, data]; before(() => { fetchMock.post('batch', batch); fetchMock.post('failed batch', data); }); afterEach(() => { fetchMock.reset(); }); it('should call Fetch with GraphQLRequest Array and return the array of FetchResults', () => { const apolloFetch = createApolloFetch({ uri: 'batch', }); const operations = [simpleQueryWithNoVars, simpleQueryWithNoVars]; return apolloFetch(operations).then(results => { assert.deepEqual(results, batch); assert(fetchMock.called('batch')); assert.equal(fetchMock.calls('batch').length, 1); assert.deepEqual( (<RequestInit>fetchMock.lastCall('batch')[1]).body, JSON.stringify(operations), ); }); }); it('should call Fetch with GraphQLRequest Array and return the array of FetchResults', () => { const apolloFetch = createApolloFetch({ uri: 'batch', }); const operations = [simpleQueryWithNoVars, simpleQueryWithNoVars]; return apolloFetch(operations).then(results => { assert.deepEqual(results, batch); assert(fetchMock.called('batch')); assert.equal(fetchMock.calls('batch').length, 1); assert.deepEqual( (<RequestInit>fetchMock.lastCall('batch')[1]).body, JSON.stringify(operations), ); }); }); it('should throw an error if response is not an array', done => { const apolloFetch = createApolloFetch({ uri: 'failed batch', }); const operations = [simpleQueryWithNoVars, simpleQueryWithNoVars]; apolloFetch(operations).then(assert).catch(error => { done(); }); }); }); describe('batched Middleware', () => { it('should throw an error if not a function', () => { assert.throws(() => createApolloFetch().batchUse(<any>{})); }); it('should get array GraphQLRequest and pass result to constructOptions', done => { const operations = [simpleQueryWithNoVars, simpleQueryWithNoVars]; let receivedOpts; const apolloFetch = createApolloFetch({ uri: 'batch', constructOptions: (request, options) => { assert(Array.isArray(request)); const tmp = operations; tmp.push(simpleQueryWithVar); assert.deepEqual(operations, <any[]>request); receivedOpts.headers = {}; receivedOpts.headers.stub = 'value'; assert.deepEqual(receivedOpts, options); done(); return constructDefaultOptions(request, options); }, }); apolloFetch.batchUse(({ requests, options }, next) => { assert.deepEqual(requests, operations); requests.push(simpleQueryWithVar); receivedOpts = { ...options }; options.headers = {}; options.headers.stub = 'value'; next(); }); apolloFetch(operations); }); }); describe('batched Afterware', () => { const data = { data: { hello: 'world', uri: '/graphql' } }; const batch = [data, data]; const operations = [simpleQueryWithNoVars, simpleQueryWithNoVars]; before(() => { fetchMock.post('batch', batch); fetchMock.post('401', 401); }); afterEach(fetchMock.reset); after(fetchMock.restore); it('should throw an error if not a function', () => { assert.throws(() => createApolloFetch().batchUseAfter(<any>{})); }); it('should get array of results return modified result', () => { const apolloFetch = createApolloFetch({ uri: 'batch', }); apolloFetch.batchUseAfter(({ response, options }, next) => { assert.deepEqual(response.parsed, batch); assert.deepEqual(fetchMock.lastCall()[1], options); assert(Array.isArray(response.parsed)); response.parsed.push(data); next(); }); return apolloFetch(operations).then(results => { const tmp = [...batch]; tmp.push(data); assert.deepEqual(results, tmp); }); }); it('should get access to the response status', done => { const apolloFetch = createApolloFetch({ uri: '401', }); apolloFetch.batchUseAfter(({ response, options }, next) => { assert.deepEqual(fetchMock.lastCall()[1], options); assert.isUndefined(response.parsed); assert.deepEqual(response.status, 401); done(); }); apolloFetch(operations); }); }); describe('constructOptions', () => { const operation = simpleQueryWithNoVars; const operations = [simpleQueryWithNoVars, simpleQueryWithNoVars]; const opts = { headers: { stub: 'header', }, }; it('should pass single GraphQLRequest to constructOptions and call fetch with result', done => { const apolloFetch = createApolloFetch({ uri: 'batch', customFetch: (uri, options) => { assert.deepEqual(uri, 'batch'); assert.deepEqual(options, opts); return done(); }, constructOptions: (request, options) => { assert.deepEqual(request, operation); return { ...opts }; }, }); apolloFetch(operation).catch(e => void 0); }); it('should pass array of GraphQLRequest to constructOptions and call fetch with result', done => { const apolloFetch = createApolloFetch({ uri: 'batch', customFetch: (uri, options) => { assert.deepEqual(uri, 'batch'); assert.deepEqual(options.body, JSON.stringify(operations)); delete options.body; assert.deepEqual(options, opts); throw done(); }, constructOptions: (request, options) => { assert.deepEqual(request, operations); return { ...opts, body: JSON.stringify(request) }; }, }); apolloFetch(operations).catch(e => void 0); }); }); }); // simulate middleware by altering variables and options function TestWare( variables: Array<{ key: string; val: any }> = [], options: Array<{ key: string; val: any }> = [], bodyParams: Array<{ key: string; val: any }> = [], ) { return (request: RequestAndOptions, next: Function): void => { variables.map(variable => { (<any>request.request.variables)[variable.key] = variable.val; }); options.map(variable => { (<any>request.options)[variable.key] = variable.val; }); bodyParams.map(param => { request.request[param.key as string] = param.val; }); next(); }; }
the_stack
import * as ts from '@terascope/utils'; import { ExecutionContextConfig, RunSliceResult, WorkerSliceState, WorkerStatus, SliceStatus, JobAPIInstances } from './interfaces'; import { WorkerOperationLifeCycle, Slice, sliceAnalyticsMetrics, SliceAnalyticsData } from '../interfaces'; import { FetcherCore, ProcessorCore, OperationCore } from '../operations/core'; import JobObserver from '../operations/job-observer'; import BaseExecutionContext from './base'; import { getMetric } from './utils'; /** * WorkerExecutionContext is designed to add more * functionality to interface with the * Execution Configuration and any Operation. */ export class WorkerExecutionContext extends BaseExecutionContext<WorkerOperationLifeCycle> implements WorkerOperationLifeCycle { // ... readonly processors: ProcessorCore[]; /** the active (or last) run slice */ sliceState: WorkerSliceState | undefined; status: WorkerStatus = 'initializing'; private readonly _fetcher: FetcherCore; private _queue: ((input: any) => Promise<ts.DataEntity[]>)[]; constructor(config: ExecutionContextConfig) { super(config, 'worker_context'); this._methodRegistry.set('onSliceInitialized', new Set()); this._methodRegistry.set('onSliceStarted', new Set()); this._methodRegistry.set('onSliceFinalizing', new Set()); this._methodRegistry.set('onSliceFinished', new Set()); this._methodRegistry.set('onSliceFailed', new Set()); this._methodRegistry.set('onSliceRetry', new Set()); this._methodRegistry.set('onOperationStart', new Set()); this._methodRegistry.set('onOperationComplete', new Set()); this._methodRegistry.set('onFlushStart', new Set()); this._methodRegistry.set('onFlushEnd', new Set()); // register the job-observer first this.api.addToRegistry('job-observer', JobObserver); // then register the apis specified in config.apis for (const apiConfig of this.config.apis || []) { const name = apiConfig._name; const apiMod = this._loader.loadAPI(name, this.assetIds); this.api.addToRegistry(name, apiMod.API); } // then register an api associated to a Reader const [readerConfig, ...processorConfigs] = this.config.operations; const readerMod = this._loader.loadReader(readerConfig._op, this.assetIds); if (readerMod.API) { this.api.addToRegistry(readerConfig._op, readerMod.API); } // then register any apis associated to the processors this.processors = []; for (const opConfig of processorConfigs) { const name = opConfig._op; const pMod = this._loader.loadProcessor(name, this.assetIds); if (pMod.API) { this.api.addToRegistry(name, pMod.API); } const pOp = new pMod.Processor(this.context, ts.cloneDeep(opConfig), this.config); this.processors.push(pOp); } // Then add the processors / readers const op = new readerMod.Fetcher(this.context, ts.cloneDeep(readerConfig), this.config); this._fetcher = op; this.addOperation(op); for (const pOp of this.processors) { this.addOperation(pOp); } this._queue = [ async (input: any) => { this._onOperationStart(0); if (this.status === 'flushing') { this._onOperationComplete(0, []); return []; } const results = await this.fetcher().handle(input); this._onOperationComplete(0, results); return results; }, async (input: any) => { await this.onSliceStarted(); return input; }, ]; let i = 0; for (const processor of this.processors) { const index = ++i; this._queue.push(async (input: any) => { this._onOperationStart(index); const results = await processor.handle(input); this._onOperationComplete(index, results); return results; }); } } async initialize(): Promise<void> { await super.initialize(); this.status = 'idle'; } async shutdown(): Promise<void> { try { await super.shutdown(); } finally { this.status = 'shutdown'; } } /** * Get a operation by name or index. * If name is used it will return the first match. */ getOperation<T extends OperationCore = OperationCore>(findBy: string | number): T { let index = -1; if (ts.isString(findBy)) { index = this.config.operations.findIndex((op) => op._op === findBy); } else if (ts.isInteger(findBy) && findBy >= 0) { index = findBy as number; } if (index === 0) { // @ts-expect-error return this._fetcher as T; } const processor = this.processors[index - 1]; if (processor == null) { throw new Error(`Unable to find operation by ${findBy}`); } // @ts-expect-error return processor as T; } /** The instance of a "Fetcher" */ fetcher<T extends FetcherCore = FetcherCore>(): T { return this._fetcher as T; } get apis(): JobAPIInstances { return this.api.apis; } get jobObserver(): JobObserver { const jobObserver = this.api.getObserver<JobObserver>('job-observer'); if (jobObserver == null) throw new Error("Job Observer hasn't not be initialized"); return jobObserver; } async initializeSlice(slice: Slice): Promise<void> { const currentSliceId = this._sliceId; if (this.status !== 'flushing') { this.status = 'running'; } this.sliceState = { status: 'starting', position: -1, slice, }; if (currentSliceId === slice.slice_id) return; this.onSliceInitialized(); } /** * Run a slice against the fetcher and then processors. * * @todo this should handle slice retries. */ async runSlice(slice?: Slice): Promise<RunSliceResult> { if (slice) await this.initializeSlice(slice); if (!this.sliceState) throw new Error('No slice specified to run'); const maxRetries = this.config.max_retries; const maxTries = maxRetries > 0 ? maxRetries + 1 : 0; const retryOptions = { retries: maxTries, delay: 100, }; let remaining = maxTries; return ts.pRetry(() => { remaining--; return this._runSliceOnce(remaining > 0); }, retryOptions); } async flush(): Promise<RunSliceResult | undefined> { if (!this.sliceState) return; if (this.sliceState.status === 'failed') return; if (this.status === 'shutdown') return; await this.onFlushStart(); const { position } = this.sliceState; if (position < 1) { this.logger.info(`flushing the currently running slice ${this._sliceId}`); return; } if (this.processingSlice) { this.logger.info(`waiting until slice ${this._sliceId} is finished before flushing`, { position }); const workerShutdown = ts.get(this.context, 'sysconfig.teraslice.shutdown_timeout', 60000); const timeoutMs = Math.round(workerShutdown * 0.8); await new Promise<void>((resolve) => { const startTime = Date.now(); const interval = setInterval(() => { if (!this.processingSlice) { clearTimeout(interval); return resolve(); } const elapsed = Date.now() - startTime; if (elapsed >= timeoutMs) { this.logger.error( new ts.TSError('Timeout waiting for slice to finish before flushing', { context: { start: new Date(startTime), timeoutMs, sliceState: this.sliceState, }, }) ); clearTimeout(interval); return resolve(); } }, 10); }); } this.logger.info(`flushing slice ${this._sliceId}`); return this._runSliceOnce(false); } get processingSlice(): boolean { if (!this.sliceState) return false; return ['started', 'starting'].includes(this.sliceState.status); } async onFlushStart(): Promise<void> { this.status = 'flushing'; this.events.emit('slice:flush:start', this._slice); await this._runMethodAsync('onFlushStart'); } async onFlushEnd(): Promise<void> { this.events.emit('slice:flush:end', this._slice); await this._runMethodAsync('onFlushEnd'); } async onSliceInitialized(): Promise<void> { this.events.emit('slice:initialize', this._slice); await this._runMethodAsync('onSliceInitialized', this._sliceId); } async onSliceStarted(): Promise<void> { this._updateSliceState('started'); await this._runMethodAsync('onSliceStarted', this._sliceId); } async onSliceFinalizing(): Promise<void> { this.events.emit('slice:finalize', this._slice); await this._runMethodAsync('onSliceFinalizing', this._sliceId); } async onSliceFinished(): Promise<void> { this.status = 'idle'; await this._runMethodAsync('onSliceFinished', this._sliceId); } async onSliceFailed(): Promise<void> { this._updateSliceState('failed'); this.events.emit('slice:failure', this._slice); await this._runMethodAsync('onSliceFailed', this._sliceId); } async onSliceRetry(): Promise<void> { this.events.emit('slice:retry', this._slice); await this._runMethodAsync('onSliceRetry', this._sliceId); } private _onOperationComplete(index: number, records: ts.DataEntity[]) { this._runMethod('onOperationComplete', this._sliceId, index, records.length, records); } private _onOperationStart(index: number) { if (this.sliceState) { this.sliceState.position = index; } this._runMethod('onOperationStart', this._sliceId, index); } private _updateSliceState(status: SliceStatus) { if (!this.sliceState) throw new Error('No active slice to update'); this.sliceState.status = status; if (status === 'completed') { this.sliceState.analytics = this.jobObserver.getAnalytics(); return; } if (status === 'flushed') { this.sliceState.analytics = this._mergeAnalytics(); } } private async _runSliceOnce(shouldRetry: boolean): Promise<RunSliceResult> { if (!this.sliceState) throw new Error('No active slice to run'); if (this.status === 'shutdown') { throw new ts.TSError('Slice shutdown during slice execution', { retryable: false, }); } if (this.status !== 'flushing') { this.status = 'running'; } try { const request = ts.cloneDeep(this.sliceState.slice.request); const results: ts.DataEntity[] = await ts.waterfall(request, this._queue, ts.isProd); if (this.status === 'flushing') { this._updateSliceState('flushed'); this.onFlushEnd(); } else { this._updateSliceState('completed'); } return { results, status: this.sliceState.status, analytics: this.sliceState.analytics, }; } catch (err) { this.logger.error(err, 'A slice error occurred', { slice: this.sliceState.slice }); if (shouldRetry) { try { await this.onSliceRetry(); } catch (retryErr) { throw new ts.TSError(err, { reason: `Slice failed to retry: ${ts.toString(retryErr)}`, retryable: false, }); } } this._updateSliceState('failed'); throw err; } } private _mergeAnalytics(): SliceAnalyticsData | undefined { const analytics = this.jobObserver.getAnalytics(); if (!analytics) return; const sliceState = this.sliceState!; const ops = this.config.operations.length; const hasPrevious = sliceState.analytics != null; const previous = sliceState.analytics || this.jobObserver.defaultAnalytics(); for (const metric of sliceAnalyticsMetrics) { for (let i = 0; i < ops; i++) { const previousMetric = getMetric(previous[metric], i); const currentMetric = getMetric(analytics[metric], i); if (hasPrevious && metric === 'size' && currentMetric > previousMetric) { const opName = this.config.operations[i]._op; const diff = currentMetric - previousMetric; this.logger.info(`operation "${opName}" flushed an additional ${diff} records`); } const updated = previousMetric + currentMetric; analytics[metric][i] = updated; } } return analytics; } private get _sliceId(): string { return this.sliceState ? this.sliceState.slice.slice_id : ''; } private get _slice() { return this.sliceState && this.sliceState.slice; } }
the_stack
import { useField } from '@/vee-validate'; import { onMounted } from '@vue/runtime-core'; import { mountWithHoc, setValue, flushPromises } from './helpers'; describe('useField()', () => { const REQUIRED_MESSAGE = 'Field is required'; const MIN_MESSAGE = 'Field must be at least 3'; test('validates when value changes', async () => { mountWithHoc({ setup() { const { value, errorMessage } = useField('field', val => (val ? true : REQUIRED_MESSAGE)); return { value, errorMessage, }; }, template: ` <input name="field" v-model="value" /> <span>{{ errorMessage }}</span> `, }); const input = document.querySelector('input'); const error = document.querySelector('span'); setValue(input as any, ''); await flushPromises(); expect(error?.textContent).toBe(REQUIRED_MESSAGE); }); test('valid flag is correct after reset', async () => { mountWithHoc({ setup() { const { value: value1, meta: meta1, resetField: reset1, } = useField('field', val => (val ? true : REQUIRED_MESSAGE)); const { value: value2, meta: meta2, resetField: reset2, } = useField('field', val => (!val || (val as string).length >= 3 ? true : MIN_MESSAGE)); return { value1, value2, meta1, meta2, reset1, reset2, }; }, template: ` <input id="input1" name="field" v-model="value1" /> <span id="meta1">{{ meta1.valid ? 'valid' : 'invalid' }}</span> <button id="r1" @click="reset1()">Reset</button> <input id="input2" name="field" v-model="value2" /> <span id="meta2">{{ meta2.valid ? 'valid' : 'invalid' }}</span> <button id="r2" @click="reset2()">Reset</button> `, }); const input1 = document.querySelector('#input1') as HTMLInputElement; const meta1 = document.querySelector('#meta1'); const input2 = document.querySelector('#input2') as HTMLInputElement; const meta2 = document.querySelector('#meta2'); await flushPromises(); expect(meta1?.textContent).toBe('invalid'); expect(meta2?.textContent).toBe('valid'); setValue(input1, '12'); setValue(input2, '12'); await flushPromises(); expect(meta1?.textContent).toBe('valid'); expect(meta2?.textContent).toBe('invalid'); // trigger reset (document.querySelector('#r1') as HTMLButtonElement).click(); (document.querySelector('#r2') as HTMLButtonElement).click(); await flushPromises(); expect(meta1?.textContent).toBe('invalid'); expect(meta2?.textContent).toBe('valid'); }); test('valid flag is synced with fields errors length', async () => { mountWithHoc({ setup() { const { value, meta, resetField } = useField('field', val => (val ? true : REQUIRED_MESSAGE)); return { value, meta, resetField, }; }, template: ` <input name="field" v-model="value" /> <span id="meta">{{ meta.valid ? 'valid' : 'invalid' }}</span> <button @click="resetField({ errors: ['bad'] })">Reset</button> `, }); await flushPromises(); const meta = document.querySelector('#meta'); const input = document.querySelector('input') as HTMLInputElement; expect(meta?.textContent).toBe('invalid'); setValue(input, '12'); await flushPromises(); expect(meta?.textContent).toBe('valid'); // trigger reset document.querySelector('button')?.click(); await flushPromises(); expect(meta?.textContent).toBe('invalid'); }); test('dirty flag is false after reset', async () => { mountWithHoc({ setup() { const { value, meta, resetField } = useField('field', val => (val ? true : REQUIRED_MESSAGE)); return { value, meta, resetField, }; }, template: ` <input name="field" v-model="value" /> <span id="meta">{{ meta.dirty ? 'dirty' : 'clean' }}</span> <button @click="resetField()">Reset</button> `, }); const input = document.querySelector('input') as HTMLInputElement; const meta = document.querySelector('#meta'); await flushPromises(); expect(meta?.textContent).toBe('clean'); setValue(input, ''); await flushPromises(); expect(meta?.textContent).toBe('dirty'); // trigger reset document.querySelector('button')?.click(); await flushPromises(); expect(meta?.textContent).toBe('clean'); }); test('dirty flag is false after reset with a new value', async () => { mountWithHoc({ setup() { const { value, meta, resetField } = useField('field', val => (val ? true : REQUIRED_MESSAGE)); return { value, meta, resetField, }; }, template: ` <input name="field" v-model="value" /> <span id="meta">{{ meta.dirty ? 'dirty' : 'clean' }}</span> <button @click="resetField({ value: '12' })">Reset</button> `, }); const input = document.querySelector('input') as HTMLInputElement; const meta = document.querySelector('#meta'); await flushPromises(); expect(meta?.textContent).toBe('clean'); setValue(input, ''); await flushPromises(); expect(meta?.textContent).toBe('dirty'); // trigger reset document.querySelector('button')?.click(); await flushPromises(); expect(meta?.textContent).toBe('clean'); }); describe('has validation modes', () => { test('silent mode does not generate messages', async () => { let validateFn!: ReturnType<typeof useField>['validate']; mountWithHoc({ setup() { const { errorMessage, validate } = useField('field', val => (val ? true : REQUIRED_MESSAGE)); validateFn = validate; return { errorMessage, }; }, template: ` <span>{{ errorMessage }}</span> `, }); const error = document.querySelector('span'); expect(error?.textContent).toBe(''); // won't show any errors await validateFn({ mode: 'silent' }); await flushPromises(); expect(error?.textContent).toBe(''); }); test('validated-only mode only generates messages when it was validated before by user action', async () => { let validateFn!: ReturnType<typeof useField>['validate']; mountWithHoc({ setup() { const { errorMessage, validate, value, setErrors } = useField('field', val => val ? true : REQUIRED_MESSAGE ); validateFn = validate; // marks it as dirty/touched value.value = ''; onMounted(() => { setErrors(''); }); return { errorMessage, }; }, template: ` <span>{{ errorMessage }}</span> `, }); const error = document.querySelector('span'); expect(error?.textContent).toBe(''); // won't show any errors await validateFn({ mode: 'validated-only' }); await flushPromises(); expect(error?.textContent).toBe(REQUIRED_MESSAGE); }); test('force mode always generates new error messages', async () => { let validateFn!: ReturnType<typeof useField>['validate']; mountWithHoc({ setup() { const { errorMessage, validate } = useField('field', val => (val ? true : REQUIRED_MESSAGE)); validateFn = validate; return { errorMessage, }; }, template: ` <span>{{ errorMessage }}</span> `, }); const error = document.querySelector('span'); expect(error?.textContent).toBe(''); // won't show any errors await validateFn({ mode: 'force' }); await flushPromises(); expect(error?.textContent).toBe(REQUIRED_MESSAGE); }); }); describe('generic function chains', () => { test('when bails is true', async () => { mountWithHoc({ setup() { const { value: value1, meta: meta1, errors: errors1, resetField: reset1, } = useField('field', [ val => (val ? true : REQUIRED_MESSAGE), val => ((val as string)?.length >= 3 ? true : MIN_MESSAGE), ]); const { value: value2, meta: meta2, errors: errors2, resetField: reset2, } = useField('field', [ val => ((val as string)?.length >= 3 ? true : MIN_MESSAGE), val => (val ? true : REQUIRED_MESSAGE), ]); return { value1, value2, meta1, meta2, errors1, errors2, reset1, reset2, }; }, template: ` <input id="input1" name="field" v-model="value1" /> <span id="meta1">{{ meta1.valid ? 'valid' : 'invalid' }}</span> <span id="errors1">{{ errors1.length }}</span> <span v-for="(e, idx) in errors1" :id="'errormessage1' + idx">{{ e }}</span> <button id="r1" @click="reset1()">Reset</button> <input id="input2" name="field" v-model="value2" /> <span id="meta2">{{ meta2.valid ? 'valid' : 'invalid' }}</span> <span id="errors2">{{ errors2.length }}</span> <span v-for="(e, idx) in errors2" :id="'errormessage2' + idx">{{ e }}</span> <button id="r2" @click="reset2()">Reset</button> `, }); const input1 = document.querySelector('#input1') as HTMLInputElement; const meta1 = document.querySelector('#meta1'); const errors1 = document.querySelector('#errors1'); const input2 = document.querySelector('#input2') as HTMLInputElement; const meta2 = document.querySelector('#meta2'); const errors2 = document.querySelector('#errors2'); await flushPromises(); expect(meta1?.textContent).toBe('invalid'); expect(meta2?.textContent).toBe('invalid'); setValue(input1, ''); setValue(input2, ''); await flushPromises(); let errorMessage10 = document.querySelector('#errormessage10'); let errorMessage20 = document.querySelector('#errormessage20'); expect(meta1?.textContent).toBe('invalid'); expect(meta2?.textContent).toBe('invalid'); expect(errors1?.textContent).toBe('1'); expect(errors2?.textContent).toBe('1'); expect(errorMessage10?.textContent).toBe(REQUIRED_MESSAGE); expect(errorMessage20?.textContent).toBe(MIN_MESSAGE); setValue(input1, '12'); setValue(input2, '12'); await flushPromises(); errorMessage10 = document.querySelector('#errormessage10'); errorMessage20 = document.querySelector('#errormessage20'); expect(meta1?.textContent).toBe('invalid'); expect(meta2?.textContent).toBe('invalid'); expect(errors1?.textContent).toBe('1'); expect(errors2?.textContent).toBe('1'); expect(errorMessage10?.textContent).toBe(MIN_MESSAGE); expect(errorMessage20?.textContent).toBe(MIN_MESSAGE); setValue(input1, '123'); setValue(input2, '123'); await flushPromises(); expect(meta1?.textContent).toBe('valid'); expect(meta2?.textContent).toBe('valid'); expect(errors1?.textContent).toBe('0'); expect(errors2?.textContent).toBe('0'); // trigger reset (document.querySelector('#r1') as HTMLButtonElement).click(); (document.querySelector('#r2') as HTMLButtonElement).click(); await flushPromises(); expect(meta1?.textContent).toBe('invalid'); expect(meta2?.textContent).toBe('invalid'); }); test('when bails is false', async () => { mountWithHoc({ setup() { const { value: value1, meta: meta1, errors: errors1, resetField: reset1, } = useField( 'field', [val => (val ? true : REQUIRED_MESSAGE), val => ((val as string)?.length >= 3 ? true : MIN_MESSAGE)], { bails: false } ); const { value: value2, meta: meta2, errors: errors2, resetField: reset2, } = useField( 'field', [val => ((val as string)?.length >= 3 ? true : MIN_MESSAGE), val => (val ? true : REQUIRED_MESSAGE)], { bails: false } ); return { value1, value2, meta1, meta2, errors1, errors2, reset1, reset2, }; }, template: ` <input id="input1" name="field" v-model="value1" /> <span id="meta1">{{ meta1.valid ? 'valid' : 'invalid' }}</span> <span id="errors1">{{ errors1.length }}</span> <span v-for="(e, idx) in errors1" :id="'errormessage1' + idx">{{ e }}</span> <button id="r1" @click="reset1()">Reset</button> <input id="input2" name="field" v-model="value2" /> <span id="meta2">{{ meta2.valid ? 'valid' : 'invalid' }}</span> <span id="errors2">{{ errors2.length }}</span> <span v-for="(e, idx) in errors2" :id="'errormessage2' + idx">{{ e }}</span> <button id="r2" @click="reset2()">Reset</button> `, }); const input1 = document.querySelector('#input1') as HTMLInputElement; const meta1 = document.querySelector('#meta1'); const errors1 = document.querySelector('#errors1'); const input2 = document.querySelector('#input2') as HTMLInputElement; const meta2 = document.querySelector('#meta2'); const errors2 = document.querySelector('#errors2'); await flushPromises(); expect(meta1?.textContent).toBe('invalid'); expect(meta2?.textContent).toBe('invalid'); setValue(input1, ''); setValue(input2, ''); await flushPromises(); let errorMessage10 = document.querySelector('#errormessage10'); const errorMessage11 = document.querySelector('#errormessage11'); let errorMessage20 = document.querySelector('#errormessage20'); const errorMessage21 = document.querySelector('#errormessage21'); expect(meta1?.textContent).toBe('invalid'); expect(meta2?.textContent).toBe('invalid'); expect(errors1?.textContent).toBe('2'); expect(errors2?.textContent).toBe('2'); expect(errorMessage10?.textContent).toBe(REQUIRED_MESSAGE); expect(errorMessage11?.textContent).toBe(MIN_MESSAGE); expect(errorMessage20?.textContent).toBe(MIN_MESSAGE); expect(errorMessage21?.textContent).toBe(REQUIRED_MESSAGE); setValue(input1, '12'); setValue(input2, '12'); await flushPromises(); errorMessage10 = document.querySelector('#errormessage10'); errorMessage20 = document.querySelector('#errormessage20'); expect(meta1?.textContent).toBe('invalid'); expect(meta2?.textContent).toBe('invalid'); expect(errors1?.textContent).toBe('1'); expect(errors2?.textContent).toBe('1'); expect(errorMessage10?.textContent).toBe(MIN_MESSAGE); expect(errorMessage20?.textContent).toBe(MIN_MESSAGE); setValue(input1, '123'); setValue(input2, '123'); await flushPromises(); expect(meta1?.textContent).toBe('valid'); expect(meta2?.textContent).toBe('valid'); expect(errors1?.textContent).toBe('0'); expect(errors2?.textContent).toBe('0'); // trigger reset (document.querySelector('#r1') as HTMLButtonElement).click(); (document.querySelector('#r2') as HTMLButtonElement).click(); await flushPromises(); expect(meta1?.textContent).toBe('invalid'); expect(meta2?.textContent).toBe('invalid'); }); }); });
the_stack
import { LocDictionary } from "../localizationDictionary"; import { ISetupInitArgs, saveSettings } from "./setupInit"; import { IdfMirror, IEspIdfLink, IEspIdfTool, SetupMode, StatusType, } from "../views/setup/types"; import * as idfConf from "../idfConfiguration"; import { ensureDir } from "fs-extra"; import path from "path"; import vscode from "vscode"; import { expressInstall } from "./espIdfDownloadStep"; import { IdfToolsManager } from "../idfToolsManager"; import { installExtensionPyReqs } from "./installPyReqs"; import { OutputChannel } from "../logger/outputChannel"; import { Logger } from "../logger/logger"; import { createPyReqs } from "./pyReqsInstallStep"; import { downloadIdfTools } from "./toolsDownloadStep"; import { installIdfGit, installIdfPython } from "./embedGitPy"; import { getOpenOcdRules } from "./addOpenOcdRules"; const locDic = new LocDictionary("SetupPanel"); export class SetupPanel { public static currentPanel: SetupPanel | undefined; public static createOrShow( extensionPath: string, setupArgs?: ISetupInitArgs ) { const column = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.viewColumn : vscode.ViewColumn.One; if (SetupPanel.currentPanel) { SetupPanel.currentPanel.panel.reveal(column); } else { SetupPanel.currentPanel = new SetupPanel( extensionPath, column, setupArgs ); } } public static isCreatedAndHidden(): boolean { return ( SetupPanel.currentPanel && SetupPanel.currentPanel.panel.visible === false ); } public static postMessage(content: any) { if (SetupPanel.currentPanel) { SetupPanel.currentPanel.panel.webview.postMessage(content); } } private static readonly viewType = "setupPanel"; private readonly panel: vscode.WebviewPanel; private disposables: vscode.Disposable[] = []; constructor( private extensionPath: string, column: vscode.ViewColumn, setupArgs: ISetupInitArgs ) { const setupPanelTitle = locDic.localize( "setupPanel.panelName", "ESP-IDF Setup" ); this.panel = vscode.window.createWebviewPanel( SetupPanel.viewType, setupPanelTitle, column, { enableScripts: true, retainContextWhenHidden: true, localResourceRoots: [ vscode.Uri.file(path.join(this.extensionPath, "dist", "views")), ], } ); this.panel.iconPath = vscode.Uri.file( path.join(extensionPath, "media", "espressif_icon.png") ); const scriptPath = this.panel.webview.asWebviewUri( vscode.Uri.file( path.join(extensionPath, "dist", "views", "setup-bundle.js") ) ); this.panel.webview.html = this.createSetupHtml(scriptPath); const containerPath = process.platform === "win32" ? process.env.USERPROFILE : process.env.HOME; const defaultEspIdfPathContainer = path.join(containerPath, "esp"); this.panel.webview.onDidReceiveMessage(async (message) => { switch (message.command) { case "checkEspIdfTools": if (message.espIdf && message.pyPath && message.toolsPath) { await this.checkRequiredTools( message.espIdf, message.toolsPath, setupArgs.gitPath ); } break; case "installEspIdf": if ( message.espIdfContainer && message.selectedEspIdfVersion && message.toolsPath && typeof message.selectedPyPath !== undefined && typeof message.manualEspIdfPath !== undefined && typeof message.mirror !== undefined && typeof message.setupMode !== undefined ) { if (message.espIdfContainer === defaultEspIdfPathContainer) { await ensureDir(defaultEspIdfPathContainer); } await this.autoInstall( message.toolsPath, message.selectedEspIdfVersion, message.selectedPyPath, message.manualEspIdfPath, message.espIdfContainer, message.mirror, message.setupMode ); } break; case "installEspIdfTools": if ( message.espIdf && message.pyPath && message.toolsPath && typeof message.mirror !== undefined ) { await this.installEspIdfTools( message.espIdf, message.pyPath, message.toolsPath, setupArgs.gitPath, message.mirror ); } break; case "openEspIdfFolder": const selectedFolder = await this.openFolder(); this.panel.webview.postMessage({ command: "updateEspIdfFolder", selectedFolder, }); break; case "openEspIdfContainerFolder": const selectedContainerFolder = await this.openFolder(); this.panel.webview.postMessage({ command: "updateEspIdfContainerFolder", selectedContainerFolder, }); break; case "openEspIdfToolsFolder": const selectedToolsFolder = await this.openFolder(); this.panel.webview.postMessage({ command: "updateEspIdfToolsFolder", selectedToolsFolder, }); break; case "openPythonPath": const selectedPyPath = await this.openFile(); this.panel.webview.postMessage({ command: "updatePythonPath", selectedPyPath, }); break; case "requestInitialValues": const pathSep = path.sep; this.panel.webview.postMessage({ command: "initialLoad", espIdfContainer: defaultEspIdfPathContainer, espIdf: setupArgs.espIdfPath, espToolsPath: setupArgs.espToolsPath, gitVersion: setupArgs.gitVersion, hasPrerequisites: setupArgs.hasPrerequisites, idfVersion: setupArgs.espIdfVersion, idfVersions: setupArgs.espIdfVersionsList, pathSep, platform: process.platform, pyBinPath: setupArgs.pyBinPath, pyVersionList: setupArgs.pythonVersions, toolsResults: setupArgs.toolsResults, }); break; case "saveCustomSettings": if ( message.espIdfPath && message.toolsPath && message.pyBinPath && message.tools ) { const { exportedPaths, exportedVars } = this.getCustomSetupSettings( message.tools ); this.panel.webview.postMessage({ command: "updateEspIdfToolsStatus", status: StatusType.installed, }); await this.installPyReqs( message.espIdfPath, message.toolsPath, message.pyBinPath, exportedPaths, exportedVars, setupArgs.gitPath ); } break; case "usePreviousSettings": if ( setupArgs.espIdfPath && setupArgs.pyBinPath && setupArgs.exportedPaths && setupArgs.exportedVars && setupArgs.espToolsPath ) { this.panel.webview.postMessage({ command: "updateIdfGitStatus", status: StatusType.installed, }); this.panel.webview.postMessage({ command: "updateIdfPythonStatus", status: StatusType.installed, }); this.panel.webview.postMessage({ command: "updateEspIdfStatus", status: StatusType.installed, }); this.panel.webview.postMessage({ command: "updateEspIdfToolsStatus", status: StatusType.installed, }); this.panel.webview.postMessage({ command: "updatePyVEnvStatus", status: StatusType.started, }); this.panel.webview.postMessage({ command: "goToCustomPage", installing: true, page: "/status", }); await installExtensionPyReqs( setupArgs.espToolsPath, setupArgs.pyBinPath ); await saveSettings( setupArgs.espIdfPath, setupArgs.pyBinPath, setupArgs.exportedPaths, setupArgs.exportedVars, setupArgs.espToolsPath, setupArgs.gitPath ); this.panel.webview.postMessage({ command: "setIsInstalled", isInstalled: true, }); await this.getOpenOcdRulesPath(); } break; default: break; } }); this.panel.onDidDispose(() => this.dispose(), null, this.disposables); } setupErrHandler(error: Error) { const errMsg = error.message ? error.message : "Error during ESP-IDF setup"; if (errMsg.indexOf("ERROR_EXISTING_ESP_IDF") !== -1) { SetupPanel.postMessage({ command: "setEspIdfErrorStatus", errorMsg: error.message, }); } else if (errMsg.indexOf("ERROR_INVALID_PYTHON") !== -1) { SetupPanel.postMessage({ command: "setPyExecErrorStatus", errorMsg: error.message, }); } else if (errMsg.indexOf("ERROR_INVALID_PIP") !== -1) { SetupPanel.postMessage({ command: "setPyExecErrorStatus", errorMsg: error.message, }); } else { SetupPanel.postMessage({ command: "setEspIdfErrorStatus", errorMsg: "", }); } OutputChannel.appendLine(errMsg); Logger.errorNotify(errMsg, error); OutputChannel.show(); SetupPanel.postMessage({ command: "goToCustomPage", installing: false, page: "/autoinstall", }); } private async autoInstall( toolsPath: string, selectedIdfVersion: IEspIdfLink, pyPath: string, espIdfPath: string, idfContainerPath: string, mirror: IdfMirror, setupMode: SetupMode ) { return await vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, title: "ESP-IDF Setup:", cancellable: true, }, async ( progress: vscode.Progress<{ message: string; increment?: number }>, cancelToken: vscode.CancellationToken ) => { try { SetupPanel.postMessage({ command: "goToCustomPage", installing: true, page: "/status", }); let idfPythonPath = pyPath, idfGitPath = "git"; if (process.platform === "win32") { const embedPaths = await this.installEmbedPyGit( toolsPath, progress, cancelToken ); idfGitPath = embedPaths.idfGitPath; idfPythonPath = embedPaths.idfPythonPath; } await expressInstall( selectedIdfVersion, idfPythonPath, espIdfPath, idfContainerPath, toolsPath, mirror, setupMode, idfGitPath, progress, cancelToken ); } catch (error) { this.setupErrHandler(error); } } ); } private async checkRequiredTools( idfPath: string, toolsInfo: IEspIdfTool[], gitPath: string ) { const toolsManager = await IdfToolsManager.createIdfToolsManager( idfPath, gitPath ); const pathToVerify = toolsInfo .reduce((prev, curr, i) => { return prev + path.delimiter + curr.path; }, "") .slice(1); const foundVersions = await toolsManager.verifyPackages(pathToVerify); const updatedToolsInfo = toolsInfo.map((tool) => { const isToolVersionCorrect = tool.expected.indexOf(foundVersions[tool.name]) > -1; tool.doesToolExist = isToolVersionCorrect; if (isToolVersionCorrect) { tool.progress = "100.00%"; tool.hashResult = true; } else { tool.progress = "0.00%"; tool.hashResult = false; } return tool; }); this.panel.webview.postMessage({ command: "setRequiredToolsInfo", toolsInfo: updatedToolsInfo, }); } private getCustomSetupSettings(toolsInfo: IEspIdfTool[]) { const exportedPaths = toolsInfo .reduce((prev, curr, i) => { return prev + path.delimiter + curr.path; }, "") .slice(1); const exportedVars = {}; for (let tool of toolsInfo) { for (let envKey of Object.keys(tool.env)) { if (Object.keys(exportedVars).indexOf(envKey) === -1) { exportedVars[envKey] = tool.env[envKey]; } } } const exportedVarsStr = JSON.stringify(exportedVars); return { exportedPaths, exportedVars: exportedVarsStr }; } private async installEspIdfTools( idfPath: string, pyPath: string, toolsPath: string, gitPath: string, mirror: IdfMirror ) { return await vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, title: "ESP-IDF Tools Setup:", cancellable: true, }, async ( progress: vscode.Progress<{ message: string; increment?: number }>, cancelToken: vscode.CancellationToken ) => { try { SetupPanel.postMessage({ command: "goToCustomPage", installing: true, page: "/status", }); await downloadIdfTools( idfPath, toolsPath, pyPath, gitPath, mirror, progress, cancelToken ); } catch (error) { this.setupErrHandler(error); } } ); } private async installPyReqs( idfPath: string, toolsPath: string, pyPath: string, exportPaths: string, exportVars: string, gitPath: string ) { return await vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, title: "ESP-IDF Python Requirements:", cancellable: true, }, async ( progress: vscode.Progress<{ message: string; increment?: number }>, cancelToken: vscode.CancellationToken ) => { try { SetupPanel.postMessage({ command: "goToCustomPage", installing: true, page: "/status", }); await createPyReqs( idfPath, toolsPath, pyPath, exportPaths, exportVars, gitPath, progress, cancelToken ); } catch (error) { this.setupErrHandler(error); } } ); } private async installEmbedPyGit( toolsPath: string, progress: vscode.Progress<{ message: string; increment?: number }>, cancelToken: vscode.CancellationToken ) { const idfGitPath = await installIdfGit(toolsPath, progress, cancelToken); SetupPanel.postMessage({ command: "updateIdfGitStatus", status: StatusType.installed, }); const idfPythonPath = await installIdfPython( toolsPath, progress, cancelToken ); SetupPanel.postMessage({ command: "updateIdfPythonStatus", status: StatusType.installed, }); const confTarget = idfConf.readParameter( "idf.saveScope" ) as vscode.ConfigurationTarget; await idfConf.writeParameter("idf.gitPath", idfGitPath, confTarget); return { idfPythonPath, idfGitPath }; } private async getOpenOcdRulesPath() { try { await getOpenOcdRules(); } catch (error) { this.setupErrHandler(error); } } private async openFolder() { const selectedFolder = await vscode.window.showOpenDialog({ canSelectFolders: true, canSelectFiles: false, canSelectMany: false, }); if (selectedFolder && selectedFolder.length > 0) { return selectedFolder[0].fsPath; } else { vscode.window.showInformationMessage("No folder selected"); } } private async openFile() { const selectedFolder = await vscode.window.showOpenDialog({ canSelectFolders: false, canSelectFiles: true, canSelectMany: false, }); if (selectedFolder && selectedFolder.length > 0) { return selectedFolder[0].fsPath; } else { vscode.window.showInformationMessage("No folder selected"); } } private createSetupHtml(scriptPath: vscode.Uri): string { return `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ESP-IDF Setup</title> </head> <body> <div id="app"></div> </body> <script src="${scriptPath}"></script> </html>`; } public dispose() { SetupPanel.currentPanel = undefined; this.panel.dispose(); } }
the_stack
import * as filetype from 'file-type'; import * as fs from 'fs'; import { BoundingBox, Document, Page, SpannedTableCell, Table, TableCell, TableRow, Word, Drawing, Text, } from '../../types/DocumentRepresentation'; import * as utils from '../../utils'; import * as CommandExecuter from '../../utils/CommandExecuter'; import logger from '../../utils/Logger'; import { Module } from '../Module'; import * as defaultConfig from './defaultConfig.json'; import { SvgLine } from '../../types/DocumentRepresentation/SvgLine'; import drawingToTable from './DrawingToTableHelper'; import drawingLineMerge from './DrawingLineMergeHelper'; import { json2document } from '../../utils/json2document'; export interface Options { pages?: number[]; flavor?: string; table_areas?: string[]; } export type JsonTableCell = { size: { width: number; height: number; }, location: { x: number; y: number; }, colSpan: number, rowSpan: number, } export type JsonTable = { size: { width: number; height: number; }, location: { x: number; y: number; }, rows: number[][], cols: number[][], cells: JsonTableCell[][], content?: string[][], flavor?: string, } type JsonTablePage = { page: number; tables: JsonTable[]; } const defaultOptions = (defaultConfig as any) as Options; export interface TableExtractorResult { stdout: string; stderr: string; status: number; } type SpannedCellPosition = { x: number; y: number; direction: 'left' | 'top' | 'right'; }; export interface TableExtractor { readTables(inputFile: string, options: Options): Promise<TableExtractorResult>; } const defaultExtractor: TableExtractor = { readTables(inputFile: string, options: Options): Promise<TableExtractorResult> { let pages: string = 'all'; let flavor: string = 'lattice'; const lineScale: string = '45'; if (options.pages.length !== 0) { pages = options.pages.toString(); } if (!['lattice', 'stream'].includes(options.flavor)) { logger.warn( `table detection flavor asked for: ${options.flavor} is not a possibility. defaulting to 'lattice'`, ); } else { flavor = options.flavor; } return CommandExecuter.detectTables( inputFile, flavor, lineScale, pages, options.table_areas || [], ) .then(stdout => ({ stdout, stderr: '', status: 0, })) .catch(({ error }) => { return { stdout: '', stderr: error, status: 1, }; }); }, }; export class TableDetectionModule extends Module<Options> { public static moduleName = 'table-detection'; private extractor: TableExtractor; constructor(options?: Options) { super(options, defaultOptions); this.setExtractor(defaultExtractor); } public setExtractor(extractor: TableExtractor) { this.extractor = extractor; } public async main(doc: Document): Promise<Document> { try { if (!fs.existsSync(doc.inputFile)) { logger.warn(`Input file ${doc.inputFile} cannot be found. Not performing table detection.`); return doc; } } catch (err) { logger.error(`Could not check if the input file ${doc.inputFile} exists: ${err}..`); return doc; } const fileType: { ext: string; mime: string } = filetype(fs.readFileSync(doc.inputFile)); if (fileType === null || fileType.ext !== 'pdf') { logger.warn(`Input file ${doc.inputFile} is not a PDF; Not performing table detection.`); return doc; } if (doc.getElementsOfType<Table>(Table).length !== 0) { logger.warn('Document already has tables. Not performing table detection.'); return doc; } for (const config of this.options.runConfig) { const tableExtractor = await this.extractor.readTables(doc.inputFile, config); if (tableExtractor.status === 0) { const tablesData = JSON.parse(tableExtractor.stdout); this.addTables(tablesData, doc); } } if (this.options.checkDrawings && doc.drawingsFile && fs.existsSync(doc.drawingsFile)) { logger.info('Looking for table candidates on Drawings...'); const drawingTablesData = this.findTablesOnDrawings(doc); this.addTables(drawingTablesData, doc); } this.removeWordsUsedInCells(doc); const tableCount = doc.getElementsOfType<Table>(Table).length; logger.info(`${tableCount} tables found on document.`); return doc; } private addTables(tablesData: JsonTablePage[], doc: Document) { tablesData.map(pageData => { pageData.tables.filter(table => table != null).map(table => { this.addTable(table, doc.pages[pageData.page - 1]); }); }); } private addTable(tableData: JsonTable, page: Page) { const pageHeight = page.box.height; const table: Table = this.createTable(tableData, pageHeight); table.content = this.createRows(tableData, page); if (tableData.content && tableData.flavor === 'stream') { table.content = this.joinCellsByContent(table.content, tableData.content); } if (!this.isFalseTable(table)) { page.elements = page.elements.concat(table); } } private joinCellsByContent(tableContent: TableRow[], tableData: string[][]): TableRow[] { const mergeCandidateCells = this.getMergeCandidateCellPositions(tableContent, tableData); Object.keys(mergeCandidateCells).forEach(cellRow => { const groupsToMerge = []; mergeCandidateCells[cellRow].forEach(cellColGroup => { let cellSubGroup = [cellColGroup[0]]; for (let i = 0; i < cellColGroup.length; i += 1) { const expectedTextInSubGroup = cellSubGroup .map(cellCol => tableData[cellRow][cellCol].trim()) .join(' ') .trim(); const tableContentSubGroup: TableCell[] = tableContent[ cellRow ].content.filter((_, index) => cellSubGroup.includes(index)); const subgroupText = tableContentSubGroup .map(cell => cell.toString().trim()) .join(' ') .trim(); if (expectedTextInSubGroup === subgroupText) { groupsToMerge.push(cellSubGroup); } if ( subgroupText.length > expectedTextInSubGroup.length || expectedTextInSubGroup === subgroupText ) { cellSubGroup = []; } if (cellColGroup.length > i + 1) { cellSubGroup.push(cellColGroup[i + 1]); } } }); if (groupsToMerge.length > 0) { tableContent[cellRow].mergeCells(groupsToMerge); } }); return tableContent; } private getMergeCandidateCellPositions(tableContent: TableRow[], tableData: string[][]): object { const mergeCandidateCells = {}; /* having the expected text content in each cell in tableData, this looks for cells in tableContent whose text content is different from the expected ex: tableContent: | this is only one | cell | | foo | bar | tableData: | this is only one cell | | | foo | bar | will give mergeCandidateCells = { '0': [0,1] } because content in [0,0] and [0,1] is different than the expected */ tableData.forEach((dataRow, nRow) => { dataRow.forEach((cellStr, nCol) => { const tableCellContent = tableContent[nRow].content[nCol].toString(); const expectedCellContent = cellStr.toString(); if (tableCellContent !== expectedCellContent) { if (!mergeCandidateCells[nRow]) { mergeCandidateCells[nRow] = []; } mergeCandidateCells[nRow].push(nCol); } }); }); /* now I group the candidate Cells by consecutive numbers. Grouped results will tell which cells could be joined together into one Cell and check if that new content matches the expected content For now groups with only one value are not considered (possible vertical join or string encoding problem) */ Object.keys(mergeCandidateCells).forEach(nRow => { mergeCandidateCells[nRow] = utils .groupConsecutiveNumbersInArray(mergeCandidateCells[nRow]) .filter(group => group.length > 1); if (mergeCandidateCells[nRow].length === 0) { delete mergeCandidateCells[nRow]; } }); return mergeCandidateCells; } private isFalseTable(table: Table): boolean { const isFalse = table.content.some((_, index) => !this.existAdjacentRow(index, table)); const only1Row = table.content.length === 1; const only1Col = table.content.every(row => row.content .filter(col => !(col instanceof SpannedTableCell)).length <= 1, ); const rowsHeightSum = table.content.reduce((total, row) => total + row.height, 0); const rowRights = table.content.map(row => row.right).sort((a, b) => a - b); return isFalse || only1Row || only1Col || Math.ceil(rowsHeightSum) < Math.floor(table.height) || rowRights[rowRights.length - 1] - rowRights[0] > 5; } private existAdjacentRow(rowIndex: number, table: Table): TableRow { if (rowIndex + 1 === table.content.length) { return this.existPreviousRow(rowIndex, table); } const row = table.content[rowIndex]; const findRowWithTop = Math.ceil(row.box.top + row.box.height); return table.content .filter(rowToFind => Math.ceil(rowToFind.box.top) === findRowWithTop) .shift(); } private existPreviousRow(rowIndex: number, table: Table): TableRow { const row = table.content[rowIndex]; const findRowWithBottom = Math.ceil(row.box.top); return table.content .filter( rowToFind => Math.ceil(rowToFind.box.top + rowToFind.box.height) === findRowWithBottom, ) .shift(); } private createTable(tableData: JsonTable, pageHeight: number): Table { const tableBounds = new BoundingBox( tableData.location.x, pageHeight - tableData.location.y, tableData.size.width, tableData.size.height, ); return new Table([], tableBounds); } private createRows(tableData: JsonTable, page: Page): TableRow[] { const pageWords = page.getElementsOfType<Word>(Word); // this is used to keep track of the position of cells that are merged into another const spannedCells: SpannedCellPosition[] = []; return tableData.cells.map((row, rowIndex) => { const tableCells: TableCell[] = this.createRowCells(row, rowIndex, page.box.height, pageWords, spannedCells, tableData.cols, tableData.rows); const maxRight = Math.max(...tableCells.filter(tc => !!tc.box).map(tc => tc.right)); const minLeft = Math.min(...tableCells.filter(tc => !!tc.box).map(tc => tc.left)); const minTop = Math.min(...tableCells.filter(tc => !!tc.box).map(tc => tc.top)); const minBottom = Math.min(...tableCells.filter(tc => !!tc.box).map(tc => tc.bottom)); const rowWidth = maxRight - minLeft; const rowHeight = minBottom - minTop; return new TableRow( tableCells, new BoundingBox( minLeft, minTop, rowWidth, rowHeight, ), ); }); } private createRowCells( row: JsonTableCell[], rowIndex: number, pageHeight: number, pageWords: Word[], spannedCells: SpannedCellPosition[], cols: number[][], rows: number[][], ): TableCell[] { const cells: TableCell[] = []; for (let colIndex = 0; colIndex < cols.length; colIndex++) { // cell at (colIndex,rowIndex) is spanned, push SpannedTableCell const spannedCell = spannedCells.find(sc => sc.x === colIndex && sc.y === rowIndex); if (spannedCell) { const [x1, x2] = cols[colIndex]; const [y1, y2] = rows[rowIndex].map(y => pageHeight - y); const box = new BoundingBox(x1, y1, x2 - x1, y2 - y1); cells.push(new SpannedTableCell(box, spannedCell.direction)); if (row.length < cols.length) { row.splice(colIndex, 0, null); } } else { const cell = row[colIndex]; if (cell) { // detect spanned cells based on colSpan and rowSpan of the current cell [...Array(cell.colSpan || 1).keys()].forEach(x => { [...Array(cell.rowSpan || 1).keys()].forEach(y => { if (x !== 0 || y !== 0) { spannedCells.push({ x: x + colIndex, y: y + rowIndex, direction: x > 0 ? 'left' : 'top', }); } }); }); const cellBounds = new BoundingBox( cell.location.x, pageHeight - cell.location.y, cell.size.width, cell.size.height, ); const tableCell: TableCell = new TableCell(cellBounds); tableCell.colspan = cell.colSpan; tableCell.rowspan = cell.rowSpan; tableCell.content = this.wordsInCellBox(cellBounds, pageWords); cells.push(tableCell); } } } return cells; } private wordsInCellBox(cellBounds: BoundingBox, pageWords: Word[]): Word[] { return pageWords.filter( w => BoundingBox.getOverlap(w.box, cellBounds).box1OverlapProportion > 0.75, ); } private removeWordsUsedInCells(document: Document) { document.pages.forEach(page => { const cellWordsIds = page .getElementsOfType<TableCell>(TableCell) .map(cell => cell.content) .reduce((a, b) => a.concat(b), []) .map(element => element.id); page.elements = page.elements.filter(element => { const isWord = element instanceof Word; const isUsedInCell = cellWordsIds.includes(element.id); return (isWord && !isUsedInCell) || !isWord; }); }); } private findTablesOnDrawings(doc: Document): JsonTablePage[] { const jsonResult: JsonTablePage[] = []; const drawingsJson = JSON.parse(fs.readFileSync(doc.drawingsFile, { encoding: 'utf8' })); const drawingsDoc = json2document(drawingsJson); drawingsDoc.pages.forEach(drawingPage => { const pageDrawings = drawingPage.getElementsOfType<Drawing>(Drawing); const docPage = doc.pages.find(p => p.pageNumber === drawingPage.pageNumber); const improvedDrawings = pageDrawings .filter(d => this.drawingIsTableCandidate(d, docPage)) .map(drawingLineMerge); const tables = improvedDrawings .filter(d => this.drawingIsTable(d, docPage)) .map(d => drawingToTable(d, docPage.height)); jsonResult.push({ page: docPage.pageNumber, tables }); }); return jsonResult; } private drawingIsTableCandidate(d: Drawing, p: Page): boolean { const totalLines = d.content.length; const vhLines = (d.content as SvgLine[]).filter(l => l.isVertical() || l.isHorizontal()); // percentage of lines that are Horizontal or Vertical const vhLinesPercentage = totalLines > 0 ? vhLines.length / totalLines : 0; // Text elements strictly inside the bounding box of the drawing const textInsideDrawing = (p.getElementsSubset(d.box) as Text[]); return vhLinesPercentage > 0.4 && textInsideDrawing.length > 0; } private drawingIsTable(d: Drawing, p: Page): boolean { // if there is already a Table in the position of the drawing, skips. if (p.getElementsOfType<Table>(Table).some(table => BoundingBox.getOverlap(table.box, d.box).box1OverlapProportion > 0.9)) { return false; } const vhLines = (d.content as SvgLine[]).filter(l => l.isVertical() || l.isHorizontal()); // Text elements strictly inside the bounding box of the drawing const textInsideDrawing = (p.getElementsSubset(d.box) as Text[]); // subset of `textInsideDrawing` elements that are overlapping with any h/v SvgLine of the Drawing. const overLappingTextInsideDrawing = textInsideDrawing.filter(t => vhLines.some(line => this.lineOverlapsText(line, t)), ); // percentage of text elements inside drawing that are overlapping with any h/v drawing line. const overlappingTextPercentage = textInsideDrawing.length > 0 ? overLappingTextInsideDrawing.length / textInsideDrawing.length : 0; // horizontal lines that have (almost) the same width than the box of the drawing const fullWidthHorizontalLines = (d.content as SvgLine[]).filter(l => { const lineW = Math.abs(l.fromX - l.toX); // TODO replace 2 with tolerance value return l.isHorizontal() && lineW + 2 >= d.width && lineW - 2 <= d.width; }); // vertical lines that have (almost) the same height than the box of the drawing const fullHeightVerticalLines = (d.content as SvgLine[]).filter(l => { const lineH = Math.abs(l.fromY - l.toY); return l.isVertical() && lineH + 1 >= d.height && lineH - 1 <= d.height; }); const verticalLinesInMiddle = (d.content as SvgLine[]).filter(l => { const minL = Math.min(l.fromX, l.toX); const maxL = Math.max(l.fromX, l.toX); return l.isVertical() && Math.floor(minL) > d.left && Math.ceil(maxL) < d.right && Math.abs(l.fromY - l.toY) >= d.height / 3.1; }); // at least a couple of "main" lines have to intersect const mainLinesIntersect = fullWidthHorizontalLines.some(hl => verticalLinesInMiddle.some(vl => vl.intersects(hl))); return overlappingTextPercentage < 0.4 && fullWidthHorizontalLines.length >= 3 && fullHeightVerticalLines.length >= 2 && verticalLinesInMiddle.length >= 1 && mainLinesIntersect; } private lineOverlapsText(line: SvgLine, e: Text): boolean { if (!e.box) return false; const svgLines = e.box.toSvgLines(); const bottom = svgLines[2]; return svgLines.some(boxLine => line.intersects(boxLine)) && bottom.fromY - e.bottom > 3; } }
the_stack
import { workspace, Selection } from 'vscode'; import { resetConfiguration, updateConfiguration } from "../util/configuration"; import { testCommand } from "../util/generic"; suite("Table formatter.", () => { suiteSetup(async () => { await resetConfiguration(); }); suiteTeardown(async () => { await resetConfiguration(); }); test("Normal", () => { return testCommand('editor.action.formatDocument', [ '| a | b |', '| --- | --- |', '| c | d |' ], new Selection(0, 0, 0, 0), [ '| a | b |', '| --- | --- |', '| c | d |' ], new Selection(0, 0, 0, 0)); }); test("Normal, without leading and trailing pipes", () => { return testCommand('editor.action.formatDocument', [ '', 'a |b', '---| ---', 'c|de' ], new Selection(0, 0, 0, 0), [ '', '| a | b |', '| --- | --- |', '| c | de |' ], new Selection(0, 0, 0, 0)); }); test("Plain pipes should always be cell separators", () => { return testCommand('editor.action.formatDocument', [ '| a | b |', '| --- | --- |', '| c `a|b` | d |' ], new Selection(0, 0, 0, 0), [ '| a | b |', '| ---- | --- |', '| c `a | b` | d |' ], new Selection(0, 0, 0, 0)); }); // https://github.github.com/gfm/#example-200 test(String.raw`Contains escaped pipes '\|'`, () => { return testCommand('editor.action.formatDocument', [ '| a | b |', '| --- | --- |', '| c `a\\|b` | d |', '| c **a\\|b** | d |' ], new Selection(0, 0, 0, 0), [ '| a | b |', '| ---------- | --- |', '| c `a\\|b` | d |', '| c **a\\|b** | d |' ], new Selection(0, 0, 0, 0)); }); test("CJK characters", () => { return testCommand('editor.action.formatDocument', [ '| a | b |', '| --- | --- |', '| c 中文 | d |' ], new Selection(0, 0, 0, 0), [ '| a | b |', '| ------ | --- |', '| c 中文 | d |' ], new Selection(0, 0, 0, 0)); }); test("Not table", () => { return testCommand('editor.action.formatDocument', [ 'a | b', '---' ], new Selection(0, 0, 0, 0), [ 'a | b', '---' ], new Selection(0, 0, 0, 0)); }); test("Indented table, belongs to a list item", () => { return testCommand('editor.action.formatDocument', [ '1. A list', ' | a | b |', ' | --- | --- |', ' | c | d |' ], new Selection(0, 0, 0, 0), [ '1. A list', ' | a | b |', ' | --- | --- |', ' | c | d |' ], new Selection(0, 0, 0, 0)); }); test("Mixed-indented table (no normalization)", () => { return testCommand('editor.action.formatDocument', [ ' | a | b |', ' | --- | --- |', ' | c | d |' ], new Selection(0, 0, 0, 0), [ ' | a | b |', ' | --- | --- |', ' | c | d |' ], new Selection(0, 0, 0, 0)); }); // This is definitely WRONG. It may produce an indented code block! // test("Mixed-indented table (normalization)", async () => { // await updateConfiguration({ config: [["markdown.extension.tableFormatter.normalizeIndentation", true]] }); // await testCommand('editor.action.formatDocument', // [ // ' | a | b |', // ' | --- | --- |', // ' | c | d |' // ], // new Selection(0, 0, 0, 0), // [ // ' | a | b |', // ' | --- | --- |', // ' | c | d |' // ], // new Selection(0, 0, 0, 0) // ); // await resetConfiguration(); // }); test("Mixed ugly table", () => { return testCommand('editor.action.formatDocument', [ '| a | b | c ', ' --- | --- | :---:', ' c | d | e |' ], new Selection(0, 0, 0, 0), [ '| a | b | c |', '| --- | --- | :---: |', '| c | d | e |' ], new Selection(0, 0, 0, 0)); }); test("Alignment and padding within cells", () => { return testCommand('editor.action.formatDocument', [ '| Column L | Column C | Column R |', '| ---- | :----: | ----: |', '| c | d | e |', '| fg | hi | jk |' ], new Selection(0, 0, 0, 0), [ '| Column L | Column C | Column R |', '| -------- | :------: | -------: |', '| c | d | e |', '| fg | hi | jk |' ], new Selection(0, 0, 0, 0)); }); test("Contains escaped pipes '\\|' in last data cell", () => { return testCommand('editor.action.formatDocument', [ '', // Changing the first expected char somehow crashes the selection logic and the test fails 'a|b', '---|---', 'c|d\\|e' ], new Selection(0, 0, 0, 0), [ '', '| a | b |', '| --- | ---- |', '| c | d\\|e |' ], new Selection(0, 0, 0, 0)); }); test("Reduced width table", () => { return testCommand('editor.action.formatDocument', [ '| a | b |', '| ------- | ---- |', '| c | d |' ], new Selection(0, 0, 0, 0), [ '| a | b |', '| --- | --- |', '| c | d |' ], new Selection(0, 0, 0, 0)); }); test("Empty cell with nothing between pipes (#381)", () => { return testCommand('editor.action.formatDocument', [ '| a | b | c |', '| --- | --- | --- |', '| a || c |' ], new Selection(0, 0, 0, 0), [ '| a | b | c |', '| --- | --- | --- |', '| a | | c |' ], new Selection(0, 0, 0, 0)); }); test("CTL: Thai", () => { return testCommand('editor.action.formatDocument', [ '| คุณครู | รั้วริม | ไอ้หนูน้อย |', '| --- | --- | --- |', '| Teacher | The border | kids |' ], new Selection(0, 0, 0, 0), [ '| คุณครู | รั้วริม | ไอ้หนูน้อย |', '| ------- | ---------- | ------- |', '| Teacher | The border | kids |' ], new Selection(0, 0, 0, 0)); }); test("Left-aligned single column table (#431)", () => { return testCommand('editor.action.formatDocument', [ '| h |', '| --- |', '| a |' ], new Selection(0, 0, 0, 0), [ '| h |', '| --- |', '| a |' ], new Selection(0, 0, 0, 0)); }); test("Centre-aligned single column table (#431)", () => { return testCommand('editor.action.formatDocument', [ '| h |', '| :---: |', '| a |' ], new Selection(0, 0, 0, 0), [ '| h |', '| :---: |', '| a |' ], new Selection(0, 0, 0, 0)); }); test("Right-aligned single column table (#431)", () => { return testCommand('editor.action.formatDocument', [ '| h |', '| ---: |', '| a |' ], new Selection(0, 0, 0, 0), [ '| h |', '| ---: |', '| a |' ], new Selection(0, 0, 0, 0)); }); test("Delimiter row without padding", async () => { await updateConfiguration({ config: [["markdown.extension.tableFormatter.delimiterRowNoPadding", true]] }); await testCommand('editor.action.formatDocument', [ '| a | b | c | d |', '| --- | :--- | ---: | :---: |', '| w | x | y | z |' ], new Selection(0, 0, 0, 0), [ '| a | b | c | d |', '|---|:---|---:|:---:|', '| w | x | y | z |' ], new Selection(0,0,0,0)); await resetConfiguration(); }); test("Delimiter row without padding, longer data", async () => { await updateConfiguration({ config: [["markdown.extension.tableFormatter.delimiterRowNoPadding", true]] }); await testCommand('editor.action.formatDocument', [ '| a | b-long | c | d-longest |', '| --- | :--- | ---: | :---: |', '| w | x | y-longer | z |' ], new Selection(0, 0, 0, 0), [ '| a | b-long | c | d-longest |', '|---|:-------|---------:|:---------:|', '| w | x | y-longer | z |' ], new Selection(0,0,0,0)); await resetConfiguration(); }); });
the_stack
import { Integrations, JSONObject, JSONValue, SegmentEvent, } from '@/core/events' import { Alias, Facade, Group, Identify, Page, Track } from '@segment/facade' import { Analytics, InitOptions } from '../../analytics' import { LegacySettings } from '../../browser' import { isOffline, isOnline } from '../../core/connection' import { Context, ContextCancelation } from '../../core/context' import { isServer } from '../../core/environment' import { Plugin } from '../../core/plugin' import { attempt } from '../../core/queue/delivery' import { asPromise } from '../../lib/as-promise' import { mergedOptions } from '../../lib/merged-options' import { pWhile } from '../../lib/p-while' import { PriorityQueue } from '../../lib/priority-queue' import { PersistedPriorityQueue } from '../../lib/priority-queue/persisted' import { applyDestinationMiddleware, DestinationMiddlewareFunction, } from '../middleware' import { tsubMiddleware } from '../routing-middleware' import { loadIntegration, resolveVersion, unloadIntegration } from './loader' import { LegacyIntegration } from './types' const klona = (evt: SegmentEvent): SegmentEvent => JSON.parse(JSON.stringify(evt)) export type ClassType<T> = new (...args: unknown[]) => T async function flushQueue( xt: Plugin, queue: PriorityQueue<Context> ): Promise<PriorityQueue<Context>> { const failedQueue: Context[] = [] if (isOffline()) { return queue } await pWhile( () => queue.length > 0 && isOnline(), async () => { const ctx = queue.pop() if (!ctx) { return } const result = await attempt(ctx, xt) const success = result instanceof Context if (!success) { failedQueue.push(ctx) } } ) // re-add failed tasks failedQueue.map((failed) => queue.pushWithBackoff(failed)) return queue } export class LegacyDestination implements Plugin { name: string version: string settings: Record<string, JSONValue> options: InitOptions = {} type: Plugin['type'] = 'destination' middleware: DestinationMiddlewareFunction[] = [] private _ready = false private _initialized = false private onReady: Promise<unknown> | undefined private onInitialize: Promise<unknown> | undefined integration: LegacyIntegration | undefined buffer: PriorityQueue<Context> flushing = false constructor( name: string, version: string, settings: Record<string, JSONValue> = {}, options: InitOptions ) { this.name = name this.version = version this.settings = { ...settings } // AJS-Renderer sets an extraneous `type` setting that clobbers // existing type defaults. We need to remove it if it's present if (this.settings['type'] && this.settings['type'] === 'browser') { delete this.settings['type'] } this.options = options this.buffer = new PersistedPriorityQueue(4, `dest-${name}`) this.scheduleFlush() } isLoaded(): boolean { return this._ready } ready(): Promise<unknown> { return this.onReady ?? Promise.resolve() } async load(ctx: Context, analyticsInstance: Analytics): Promise<void> { if (this._ready || this.onReady !== undefined) { return } this.integration = await loadIntegration( ctx, analyticsInstance, this.name, this.version, this.settings ) this.onReady = new Promise((resolve) => { const onReadyFn = (): void => { this._ready = true resolve(true) } this.integration!.once('ready', onReadyFn) }) this.onInitialize = new Promise((resolve) => { const onInit = (): void => { this._initialized = true resolve(true) } this.integration!.on('initialize', onInit) }) try { ctx.stats.increment('analytics_js.integration.invoke', 1, [ `method:initialize`, `integration_name:${this.name}`, ]) this.integration.initialize() } catch (error) { ctx.stats.increment('analytics_js.integration.invoke.error', 1, [ `method:initialize`, `integration_name:${this.name}`, ]) throw error } } unload(_ctx: Context, _analyticsInstance: Analytics): Promise<void> { return unloadIntegration(this.name, this.version) } addMiddleware(...fn: DestinationMiddlewareFunction[]): void { this.middleware = this.middleware.concat(...fn) } shouldBuffer(ctx: Context): boolean { return ( // page events can't be buffered because of destinations that automatically add page views ctx.event.type !== 'page' && (isOffline() || this._ready === false || this._initialized === false) ) } private async send<T extends Facade>( ctx: Context, clz: ClassType<T>, eventType: 'track' | 'identify' | 'page' | 'alias' | 'group' ): Promise<Context> { if (this.shouldBuffer(ctx)) { this.buffer.push(ctx) this.scheduleFlush() return ctx } const plan = this.options?.plan?.track const ev = ctx.event.event if (plan && ev && this.name !== 'Segment.io') { // events are always sent to segment (legacy behavior) const planEvent = plan[ev] if (planEvent?.enabled === false) { ctx.updateEvent('integrations', { ...ctx.event.integrations, All: false, 'Segment.io': true, }) ctx.cancel( new ContextCancelation({ retry: false, reason: `Event ${ev} disabled for integration ${this.name} in tracking plan`, type: 'Dropped by plan', }) ) return ctx } else { ctx.updateEvent('integrations', { ...ctx.event.integrations, ...planEvent?.integrations, }) } if (planEvent?.enabled && planEvent?.integrations[this.name] === false) { ctx.cancel( new ContextCancelation({ retry: false, reason: `Event ${ev} disabled for integration ${this.name} in tracking plan`, type: 'Dropped by plan', }) ) return ctx } } const afterMiddleware = await applyDestinationMiddleware( this.name, klona(ctx.event), this.middleware ) if (afterMiddleware === null) { return ctx } const event = new clz(afterMiddleware, {}) ctx.stats.increment('analytics_js.integration.invoke', 1, [ `method:${eventType}`, `integration_name:${this.name}`, ]) try { if (this.integration) { await asPromise( this.integration.invoke.call(this.integration, eventType, event) ) } } catch (err) { ctx.stats.increment('analytics_js.integration.invoke.error', 1, [ `method:${eventType}`, `integration_name:${this.name}`, ]) throw err } return ctx } async track(ctx: Context): Promise<Context> { return this.send(ctx, Track as ClassType<Track>, 'track') } async page(ctx: Context): Promise<Context> { if (this.integration?._assumesPageview && !this._initialized) { this.integration.initialize() } return this.onInitialize!.then(() => { return this.send(ctx, Page as ClassType<Page>, 'page') }) } async identify(ctx: Context): Promise<Context> { return this.send(ctx, Identify as ClassType<Identify>, 'identify') } async alias(ctx: Context): Promise<Context> { return this.send(ctx, Alias as ClassType<Alias>, 'alias') } async group(ctx: Context): Promise<Context> { return this.send(ctx, Group as ClassType<Group>, 'group') } private scheduleFlush(): void { if (this.flushing) { return } // eslint-disable-next-line @typescript-eslint/no-misused-promises setTimeout(async () => { this.flushing = true this.buffer = await flushQueue(this, this.buffer) this.flushing = false if (this.buffer.todo > 0) { this.scheduleFlush() } }, Math.random() * 5000) } } export async function ajsDestinations( settings: LegacySettings, globalIntegrations: Integrations = {}, options?: InitOptions ): Promise<LegacyDestination[]> { if (isServer()) { return [] } if (settings.plan) { options = options ?? {} options.plan = settings.plan } const routingRules = settings.middlewareSettings?.routingRules ?? [] const routingMiddleware = tsubMiddleware(routingRules) // merged remote CDN settings with user provided options const integrationOptions = mergedOptions(settings, options ?? {}) as Record< string, JSONObject > return Object.entries(settings.integrations) .map(([name, integrationSettings]) => { if (name.startsWith('Segment')) { return } const allDisableAndNotDefined = globalIntegrations.All === false && globalIntegrations[name] === undefined if (globalIntegrations[name] === false || allDisableAndNotDefined) { return } const { type, bundlingStatus, versionSettings } = integrationSettings // We use `!== 'unbundled'` (versus `=== 'bundled'`) to be inclusive of // destinations without a defined value for `bundlingStatus` const deviceMode = bundlingStatus !== 'unbundled' && (type === 'browser' || versionSettings?.componentTypes?.includes('browser')) // checking for iterable is a quick fix we need in place to prevent // errors showing Iterable as a failed destiantion. Ideally, we should // fix the Iterable metadata instead, but that's a longer process. if ((!deviceMode && name !== 'Segment.io') || name === 'Iterable') { return } const version = resolveVersion(integrationSettings) const destination = new LegacyDestination( name, version, integrationOptions[name], options as object ) const routing = routingRules.filter( (rule) => rule.destinationName === name ) if (routing.length > 0) { destination.addMiddleware(routingMiddleware) } return destination }) .filter((xt) => xt !== undefined) as LegacyDestination[] }
the_stack
import assert from 'assert'; import { TypeMap } from '../type'; import Node, { SourceRange, NLAnnotationMap, AnnotationMap, AnnotationSpec, implAnnotationsToSource, nlAnnotationsToSource, } from './base'; import NodeVisitor from './visitor'; import { Value, VarRefValue, EnumValue, BooleanValue } from './values'; import { Invocation, DeviceSelector, InputParam } from './invocation'; import { Stream, Table, Action, VarRefAction, } from './legacy'; import { Expression, ChainExpression } from './expression'; import { FunctionDef } from './function_def'; import { ClassDef } from './class_def'; import { Program } from './program'; import { AbstractSlot, OldSlot } from './slots'; import TypeChecker from '../typecheck'; import SchemaRetriever from '../schema'; import * as Optimizer from '../optimize'; import { TokenStream } from '../new-syntax/tokenstream'; import List from '../utils/list'; /** * The base class of all AST nodes that represent complete ThingTalk * statements. * */ export abstract class Statement extends Node { /** * Iterate all slots (scalar value nodes) in this statement. * * @deprecated This method is only appropriate for filters and input parameters. * You should use {@link Ast.Statement.iterateSlots2} instead. */ abstract iterateSlots() : Generator<OldSlot, void>; /** * Iterate all slots (scalar value nodes) in this statement. */ abstract iterateSlots2() : Generator<DeviceSelector|AbstractSlot, void>; /** * Clone this statement. */ abstract clone() : Statement; } function declarationLikeToProgram(self : FunctionDeclaration|Example) : Program { const nametoslot : { [key : string] : number } = {}; let i = 0; for (const name in self.args) nametoslot[name] = i++; let declarations : FunctionDeclaration[], statements : TopLevelExecutableStatement[]; if (self instanceof Example) { declarations = []; statements = [new ExpressionStatement(null, self.value.clone())]; } else { declarations = self.declarations.map((d) => d.clone()); statements = self.statements.map((s) => { if (s instanceof ReturnStatement) return new ExpressionStatement(s.location, s.expression.clone()); else return s.clone(); }); } const program = new Program(null, [], declarations, statements); program.visit(new class extends NodeVisitor { visitVarRefValue(value : VarRefValue) { if (value.name in nametoslot) value.name = '__const_SLOT_' + nametoslot[value.name]; return true; } }); return program; } /** * A ThingTalk function declaration. * * A declaration statement creates a new, locally scoped, function * implemented as ThingTalk expression. The name can then be invoked * in subsequent statements. * */ export class FunctionDeclaration extends Statement { /** * The name of the declared function. */ name : string; /** * Arguments available to the function. */ args : TypeMap; declarations : FunctionDeclaration[]; statements : ExecutableStatement[]; /** * The declaration natural language annotations (translatable annotations). */ nl_annotations : NLAnnotationMap; /** * The declaration annotations. */ impl_annotations : AnnotationMap; /** * The type definition corresponding to this function. * * This property is guaranteed not `null` after type-checking. */ schema : FunctionDef|null; /** * Construct a new declaration statement. * * @param location - the position of this node in the source code * @param name - the name being bound by this statement * @param type - what type of function is being declared, * either `stream`, `query`, `action`, `program` or `procedure` * @param args - any arguments available to the function * @param value - the declaration body * @param metadata - declaration metadata (translatable annotations) * @param annotations - declaration annotations * @param schema - the type definition corresponding to this declaration */ constructor(location : SourceRange|null, name : string, args : TypeMap, declarations : FunctionDeclaration[], statements : ExecutableStatement[], annotations : AnnotationSpec = {}, schema : FunctionDef|null = null) { super(location); assert(typeof name === 'string'); this.name = name; assert(typeof args === 'object'); this.args = args; this.declarations = declarations; this.statements = statements; this.nl_annotations = annotations.nl || {}; this.impl_annotations = annotations.impl || {}; this.schema = schema; } optimize() : this { return Optimizer.optimizeProgram(this); } toSource() : TokenStream { let list : TokenStream = List.concat('function', this.name, '(', '\t=+'); let first = true; for (const argname in this.args) { const argtype = this.args[argname]; if (first) first = false; else list = List.concat(list, ',', '\n'); list = List.concat(list, argname, ':', argtype.toSource()); } list = List.concat(list, ')', '\t=-', ' ', '{', '\t+', '\n'); for (const stmt of this.declarations) list = List.concat(list, stmt.toSource(), '\n'); for (const stmt of this.statements) list = List.concat(list, stmt.toSource(), '\n'); list = List.concat(list, '\t-', '}'); return list; } get metadata() : NLAnnotationMap { return this.nl_annotations; } get annotations() : AnnotationMap { return this.impl_annotations; } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitFunctionDeclaration(this)) { for (const decl of this.declarations) decl.visit(visitor); for (const stmt of this.statements) stmt.visit(visitor); } visitor.exit(this); } *iterateSlots() : Generator<OldSlot, void> { // the declaration refers to a nested scope, we don't need to // slot fill it now } *iterateSlots2() : Generator<DeviceSelector|AbstractSlot, void> { // the declaration refers to a nested scope, we don't need to // slot fill it now } clone() : FunctionDeclaration { const newArgs = {}; Object.assign(newArgs, this.args); const newMetadata = {}; Object.assign(newMetadata, this.nl_annotations); const newAnnotations = {}; Object.assign(newAnnotations, this.impl_annotations); return new FunctionDeclaration(this.location, this.name, newArgs, this.declarations.map((d) => d.clone()), this.statements.map((s) => s.clone()), { nl: newMetadata, impl: newAnnotations }, this.schema); } /** * Convert a declaration to a program. * * This will create a program that invokes the same code as the declaration value, * and will replace all parameters with slots. * * @return {Ast.Program} the new program */ toProgram() : Program { return declarationLikeToProgram(this); } } /** * `let result` statements, that assign the value of a ThingTalk expression to a name. * * Assignment statements are executable statements that evaluate the ThingTalk expression * and assign the result to the name, which becomes available for later use in the program. * */ export class Assignment extends Statement { /** * The name being assigned to. */ name : string; /** * The expression being assigned. */ value : Expression; /** * The signature corresponding to this assignment. * * This is the type that the assigned name has after the assignment statement. * This property is guaranteed not `null` after type-checking. */ schema : FunctionDef|null; /** * Construct a new assignment statement. * * @param {Ast~SourceRange|null} location - the position of this node * in the source code * @param {string} name - the name being assigned to * @param {Ast.Table} value - the expression being assigned * @param {Ast.FunctionDef | null} schema - the signature corresponding to this assignment */ constructor(location : SourceRange|null, name : string, value : Expression, schema : FunctionDef|null = null) { super(location); assert(typeof name === 'string'); this.name = name; assert(value instanceof Expression); this.value = value; this.schema = schema; } toSource() : TokenStream { return List.concat('let', this.name, ' ', '=', ' ', this.value.toSource(), ';'); } /** * Whether this assignment calls an action or executes a query. * * This will be `undefined` before typechecking, and then either `true` or `false`. */ get isAction() : boolean { return this.schema!.functionType === 'action'; } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitAssignment(this)) this.value.visit(visitor); visitor.exit(this); } *iterateSlots() : Generator<OldSlot, void> { yield* this.value.iterateSlots({}); } *iterateSlots2() : Generator<DeviceSelector|AbstractSlot, void> { yield* this.value.iterateSlots2({}); } clone() : Assignment { return new Assignment(this.location, this.name, this.value.clone(), this.schema); } } /** * @deprecated Use {@link ExpressionStatement} instead. */ export class Rule extends Statement { stream : Stream; actions : Action[]; isRule = true; /** * Construct a new rule statement. * * @param location - the position of this node * in the source code * @param stream - the stream to react to * @param actions - the actions to execute */ constructor(location : SourceRange|null, stream : Stream, actions : Action[]) { super(location); assert(stream instanceof Stream); this.stream = stream; assert(Array.isArray(actions)); this.actions = actions; } toSource() : TokenStream { assert(this.actions.length === 1); return List.concat(this.stream.toSource(), '=>', this.actions[0].toSource(), ';'); } toExpression() : ExpressionStatement { const exprs = [this.stream.toExpression()].concat(this.actions.filter((a) => !a.isNotify).map((a) => a.toExpression())); return new ExpressionStatement(this.location, new ChainExpression(this.location, exprs, null)); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitRule(this)) { this.stream.visit(visitor); for (const action of this.actions) action.visit(visitor); } visitor.exit(this); } *iterateSlots() : Generator<OldSlot, void> { const [,scope] = yield* this.stream.iterateSlots({}); for (const action of this.actions) yield* action.iterateSlots(scope); } *iterateSlots2() : Generator<DeviceSelector|AbstractSlot, void> { const [,scope] = yield* this.stream.iterateSlots2({}); for (const action of this.actions) yield* action.iterateSlots2(scope); } clone() : Rule { return new Rule(this.location, this.stream.clone(), this.actions.map((a) => a.clone())); } } /** * @deprecated Use {@link ExpressionStatement} instead. */ export class Command extends Statement { table : Table|null; actions : Action[]; isCommand = true; /** * Construct a new command statement. * * @param {Ast~SourceRange|null} location - the position of this node * in the source code * @param {Ast.Table|null} table - the table to read from * @param {Ast.Action[]} actions - the actions to execute */ constructor(location : SourceRange|null, table : Table|null, actions : Action[]) { super(location); assert(table === null || table instanceof Table); this.table = table; assert(Array.isArray(actions)); this.actions = actions; } toExpression() : ExpressionStatement { const exprs : Expression[] = []; if (this.table) exprs.push(this.table.toExpression([])); exprs.push(...this.actions.filter((a) => !a.isNotify).map((a) => a.toExpression())); return new ExpressionStatement(this.location, new ChainExpression(this.location, exprs, null)); } toSource() : TokenStream { assert(this.actions.length === 1); if (this.table) return List.concat(this.table.toSource(), '=>', this.actions[0].toSource(), ';'); else return List.concat(this.actions[0].toSource(), ';'); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitCommand(this)) { if (this.table !== null) this.table.visit(visitor); for (const action of this.actions) action.visit(visitor); } visitor.exit(this); } *iterateSlots() : Generator<OldSlot, void> { let scope = {}; if (this.table) [,scope] = yield* this.table.iterateSlots({}); for (const action of this.actions) yield* action.iterateSlots(scope); } *iterateSlots2() : Generator<DeviceSelector|AbstractSlot, void> { let scope = {}; if (this.table) [,scope] = yield* this.table.iterateSlots2({}); for (const action of this.actions) yield* action.iterateSlots2(scope); } clone() : Command { return new Command(this.location, this.table !== null ? this.table.clone() : null, this.actions.map((a) => a.clone())); } } class IsExecutableVisitor extends NodeVisitor { isExecutable = true; visitInvocation(invocation : Invocation) { const schema = invocation.schema; assert(schema instanceof FunctionDef); const params = new Map<string, Value>(); for (const in_param of invocation.in_params) params.set(in_param.name, in_param.value); const requireEither = schema.getImplementationAnnotation<string[][]>('require_either'); if (requireEither) { for (const requirement of requireEither) { let satisfied = false; for (const option of requirement) { if (params.has(option)) { satisfied = true; break; } } if (!satisfied) this.isExecutable = false; } } for (const arg of schema.iterateArguments()) { const requiredIf = arg.getImplementationAnnotation<string[]>('required_if'); if (requiredIf && !params.has(arg.name)) { let required = false; for (const requirement of requiredIf) { const [param, value] = requirement.split('='); const current = params.get(param); if (!current) continue; if ((current instanceof EnumValue && current.value === value) || (current instanceof BooleanValue && current.value === (value === 'true'))) { required = true; break; } } if (required) this.isExecutable = false; } } return true; } visitValue(value : Value) { if (value.isUndefined || !value.isConcrete()) this.isExecutable = false; return true; } } /** * A statement that evaluates an expression and presents the results * to the user. */ export class ExpressionStatement extends Statement { expression : ChainExpression; constructor(location : SourceRange|null, expression : Expression) { super(location); if (!(expression instanceof ChainExpression)) this.expression = new ChainExpression(location, [expression], expression.schema); else this.expression = expression; assert(this.expression.expressions.length > 0); } get first() : Expression { return this.expression.first; } get last() : Expression { return this.expression.last; } get stream() : Expression|null { const first = this.first; if (first.schema!.functionType === 'stream') return first; else return null; } get lastQuery() : Expression|null { return this.expression.lastQuery; } toLegacy(scope_params : string[] = []) : Rule|Command { const last = this.last; const action = last.schema!.functionType === 'action' ? last : null; let head : Stream|Table|null = null; if (action) { const remaining = this.expression.expressions.slice(0, this.expression.expressions.length-1); if (remaining.length > 0) { const converted = new ChainExpression(null, remaining, null).toLegacy([], scope_params); assert(converted instanceof Stream || converted instanceof Table); head = converted; } } else { const converted = this.expression.toLegacy([], scope_params); assert(converted instanceof Stream || converted instanceof Table); head = converted; } const actionIntoParams : InputParam[] = []; const convertedAction = action ? action.toLegacy(actionIntoParams, scope_params) : null; assert(convertedAction === null || convertedAction instanceof Action); if (convertedAction && convertedAction instanceof VarRefAction) convertedAction.in_params.push(...actionIntoParams); if (head instanceof Stream) return new Rule(this.location, head, convertedAction ? [convertedAction] : [Action.notifyAction()]); else return new Command(this.location, head, convertedAction ? [convertedAction] : [Action.notifyAction()]); } toSource() : TokenStream { return List.concat(this.expression.toSource(), ';'); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitExpressionStatement(this)) this.expression.visit(visitor); visitor.exit(this); } *iterateSlots() : Generator<OldSlot, void> { yield* this.expression.iterateSlots({}); } *iterateSlots2() : Generator<DeviceSelector|AbstractSlot, void> { yield* this.expression.iterateSlots2({}); } clone() : ExpressionStatement { return new ExpressionStatement(this.location, this.expression.clone()); } isExecutable() { const visitor = new IsExecutableVisitor; this.visit(visitor); return visitor.isExecutable; } } /** * A statement that explicitly sets the result of the current function. * * Only available inside a user-defined function. */ export class ReturnStatement extends Statement { constructor(location : SourceRange|null, public expression : Expression) { super(location); } toSource() : TokenStream { return List.concat('return', this.expression.toSource(), ';'); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitReturnStatement(this)) this.expression.visit(visitor); visitor.exit(this); } *iterateSlots() : Generator<OldSlot, void> { yield* this.expression.iterateSlots({}); } *iterateSlots2() : Generator<DeviceSelector|AbstractSlot, void> { yield* this.expression.iterateSlots2({}); } clone() : ReturnStatement { return new ReturnStatement(this.location, this.expression.clone()); } toLegacy(scope_params : string[] = []) : Command { const chain = this.expression instanceof ChainExpression ? this.expression : new ChainExpression(null, [this.expression], this.expression.schema); const last = chain.last; const action = last.schema!.functionType === 'action' ? last : null; let head : Table|null = null; if (action) { const remaining = chain.expressions.slice(0, chain.expressions.length-1); if (remaining.length > 0) { const converted = new ChainExpression(null, remaining, null).toLegacy([], scope_params); assert(converted instanceof Table); head = converted; } } else { const converted = chain.toLegacy([], scope_params); assert(converted instanceof Table); head = converted; } const convertedAction = action ? action.toLegacy([], scope_params) : null; assert(convertedAction === null || convertedAction instanceof Action); return new Command(this.location, head, convertedAction ? [convertedAction] : [Action.notifyAction()]); } } export type ExecutableStatement = Assignment | ExpressionStatement | ReturnStatement; export type TopLevelStatement = ClassDef | Dataset | FunctionDeclaration | TopLevelExecutableStatement; export type TopLevelExecutableStatement = Assignment | ExpressionStatement; /** * A single example (primitive template) in a ThingTalk dataset * */ export class Example extends Node { isExample = true; id : number; type : string; args : TypeMap; value : Expression; utterances : string[]; preprocessed : string[]; annotations : AnnotationMap; /** * Construct a new example. * * @param location - the position of this node in the source code * @param id - the ID of the example, or -1 if the example has no ID * @param {string} type - the type of this example, one of `stream`, `query`, * `action`, or `program` * @param {Ast.Stream|Ast.Table|Ast.Action|Ast.Program} - the code this example * maps to * @param {string[]} utterances - raw, unprocessed utterances for this example * @param {string[]} preprocessed - preprocessed (tokenized) utterances for this example * @param {Object.<string, any>} annotations - other annotations for this example */ constructor(location : SourceRange|null, id : number, type : string, args : TypeMap, value : Expression, utterances : string[], preprocessed : string[], annotations : AnnotationMap) { super(location); assert(typeof id === 'number'); this.id = id; this.type = type; assert(typeof args === 'object'); this.args = args; assert(value instanceof Expression); this.value = value; assert(Array.isArray(utterances) && Array.isArray(preprocessed)); this.utterances = utterances; this.preprocessed = preprocessed; assert(typeof annotations === 'object'); this.annotations = annotations; } toSource() : TokenStream { const annotations : AnnotationMap = {}; if (this.id >= 0) annotations.id = new Value.Number(this.id); Object.assign(annotations, this.annotations); const metadata : NLAnnotationMap = {}; if (this.utterances.length > 0) metadata.utterances = this.utterances; if (this.preprocessed.length > 0) metadata.preprocessed = this.preprocessed; let args : TokenStream = List.Nil; let first = true; for (const argname in this.args) { const argtype = this.args[argname]; if (first) first = false; else args = List.concat(args, ','); args = List.concat(args, argname, ':', argtype.toSource()); } let list : TokenStream = List.singleton(this.type); if (args !== List.Nil) list = List.concat(list, ' ', '(', args, ')'); list = List.concat(list, ' ', '=', ' ', this.value.toSource(), nlAnnotationsToSource(metadata), implAnnotationsToSource(annotations), ';'); return list; } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitExample(this)) this.value.visit(visitor); visitor.exit(this); } clone() : Example { return new Example( this.location, this.id, this.type, Object.assign({}, this.args), this.value.clone(), this.utterances.slice(0), this.preprocessed.slice(0), Object.assign({}, this.annotations) ); } /** * Typecheck this example. * * This method can be used to typecheck an example is isolation, * outside of a ThingTalk program. This is useful to typecheck a dataset * and discard examples that do not typecheck without failing the whole dataset. * * @param schemas - schema retriever object to retrieve Thingpedia information * @param [getMeta=false] - retrieve natural language metadata during typecheck */ async typecheck(schemas : SchemaRetriever, getMeta = false) : Promise<this> { const typeChecker = new TypeChecker(schemas, getMeta); await typeChecker.typeCheckExample(this); return this; } /** * Iterate all slots (scalar value nodes) in this example. * @deprecated Use {@link Ast.Example.iterateSlots2} instead. */ *iterateSlots() : Generator<OldSlot, void> { yield* this.value.iterateSlots({}); } /** * Iterate all slots (scalar value nodes) in this example. */ *iterateSlots2() : Generator<DeviceSelector|AbstractSlot, void> { yield* this.value.iterateSlots2({}); } /** * Convert a dataset example to a program. * * This will create a program that invokes the same code as the example value, * and will replace all parameters with slots. * * @return {Ast.Program} the new program */ toProgram() : Program { return declarationLikeToProgram(this); } } /** * A statement that declares a ThingTalk dataset (collection of primitive * templates). * */ export class Dataset extends Statement { name : string; examples : Example[]; nl_annotations : NLAnnotationMap; impl_annotations : AnnotationMap; /** * Construct a new dataset. * * @param location - the position of this node in the source code * @param name - the name of this dataset * @param language - the language code of this dataset, as 2 letter ISO code * @param examples - the examples in this dataset * @param [annotations={}]- dataset annotations */ constructor(location : SourceRange|null, name : string, examples : Example[], annotations : AnnotationSpec = {}) { super(location); assert(typeof name === 'string'); assert(!name.startsWith('@')); this.name = name; assert(Array.isArray(examples)); // of Example this.examples = examples; this.impl_annotations = annotations.impl||{}; this.nl_annotations = annotations.nl||{}; } toSource() : TokenStream { let list : TokenStream = List.concat('dataset', '@' + this.name, nlAnnotationsToSource(this.nl_annotations), implAnnotationsToSource(this.impl_annotations), ' ', '{', '\n', '\t+'); let first = true; for (const ex of this.examples) { // force an additional \n between examples if (first) first = false; else list = List.concat(list, '\n'); list = List.concat(list, ex.toSource(), '\n'); } list = List.concat(list, '\t-', '}'); return list; } get language() : string|undefined { const language = this.impl_annotations.language; if (language) return String(language.toJS()); else return undefined; } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitDataset(this)) { for (const example of this.examples) example.visit(visitor); } visitor.exit(this); } *iterateSlots() : Generator<OldSlot, void> { for (const ex of this.examples) yield* ex.iterateSlots(); } *iterateSlots2() : Generator<DeviceSelector|AbstractSlot, void> { for (const ex of this.examples) yield* ex.iterateSlots2(); } optimize() : Dataset { return Optimizer.optimizeDataset(this); } clone() : Dataset { const newMetadata = {}; Object.assign(newMetadata, this.nl_annotations); const newAnnotations = {}; Object.assign(newAnnotations, this.impl_annotations); return new Dataset(this.location, this.name, this.examples.map((e) => e.clone()), { nl: newMetadata, impl: newAnnotations }); } }
the_stack
import { Client, Event } from '@sentry/types'; import { getCurrentHub, Hub, Scope } from '../src'; const clientFn: any = jest.fn(); function makeClient() { return { getOptions: jest.fn(), captureEvent: jest.fn(), captureException: jest.fn(), close: jest.fn(), flush: jest.fn(), getDsn: jest.fn(), getIntegration: jest.fn(), setupIntegrations: jest.fn(), captureMessage: jest.fn(), } as unknown as Client; } /** * Return an array containing the arguments passed to the given mocked or spied-upon function. * * By default, the args passed to the first call of the function are returned, but it is also possible to retrieve the * nth call by passing `callIndex`. If the function wasn't called, an error message is returned instead. */ function getPassedArgs(mock: (...args: any[]) => any, callIndex: number = 0): any[] { const asMock = mock as jest.MockedFunction<(...args: any[]) => any>; return asMock.mock.calls[callIndex] || ["Error: Function wasn't called."]; } describe('Hub', () => { afterEach(() => { jest.restoreAllMocks(); jest.useRealTimers(); }); test('call bindClient with provided client when constructing new instance', () => { const testClient = makeClient(); const hub = new Hub(testClient); expect(hub.getClient()).toBe(testClient); }); test('push process into stack', () => { const hub = new Hub(); expect(hub.getStack()).toHaveLength(1); }); test('pass in filled layer', () => { const hub = new Hub(clientFn); expect(hub.getStack()).toHaveLength(1); }); test('isOlderThan', () => { const hub = new Hub(); expect(hub.isOlderThan(0)).toBeFalsy(); }); describe('pushScope', () => { test('simple', () => { const localScope = new Scope(); localScope.setExtra('a', 'b'); const hub = new Hub(undefined, localScope); hub.pushScope(); expect(hub.getStack()).toHaveLength(2); expect(hub.getStack()[1].scope).not.toBe(localScope); expect((hub.getStack()[1].scope as Scope as any)._extra).toEqual({ a: 'b' }); }); test('inherit client', () => { const testClient: any = { bla: 'a' }; const hub = new Hub(testClient); hub.pushScope(); expect(hub.getStack()).toHaveLength(2); expect(hub.getStack()[1].client).toBe(testClient); }); describe('bindClient', () => { test('should override current client', () => { const testClient = makeClient(); const nextClient = makeClient(); const hub = new Hub(testClient); hub.bindClient(nextClient); expect(hub.getStack()).toHaveLength(1); expect(hub.getStack()[0].client).toBe(nextClient); }); test('should bind client to the top-most layer', () => { const testClient: any = { bla: 'a' }; const nextClient: any = { foo: 'bar' }; const hub = new Hub(testClient); hub.pushScope(); hub.bindClient(nextClient); expect(hub.getStack()).toHaveLength(2); expect(hub.getStack()[0].client).toBe(testClient); expect(hub.getStack()[1].client).toBe(nextClient); }); test('should call setupIntegration method of passed client', () => { const testClient = makeClient(); const nextClient = makeClient(); const hub = new Hub(testClient); hub.bindClient(nextClient); expect(testClient.setupIntegrations).toHaveBeenCalled(); expect(nextClient.setupIntegrations).toHaveBeenCalled(); }); }); test('inherit processors', async () => { expect.assertions(1); const event: Event = { extra: { b: 3 }, }; const localScope = new Scope(); localScope.setExtra('a', 'b'); const hub = new Hub({ a: 'b' } as any, localScope); localScope.addEventProcessor(async (processedEvent: Event) => { processedEvent.dist = '1'; return processedEvent; }); hub.pushScope(); const pushedScope = hub.getStackTop().scope; return pushedScope!.applyToEvent(event).then(final => { expect(final!.dist).toEqual('1'); }); }); }); test('popScope', () => { const hub = new Hub(); hub.pushScope(); expect(hub.getStack()).toHaveLength(2); hub.popScope(); expect(hub.getStack()).toHaveLength(1); }); describe('withScope', () => { let hub: Hub; beforeEach(() => { hub = new Hub(); }); test('simple', () => { hub.withScope(() => { expect(hub.getStack()).toHaveLength(2); }); expect(hub.getStack()).toHaveLength(1); }); test('bindClient', () => { const testClient: any = { bla: 'a' }; hub.withScope(() => { hub.bindClient(testClient); expect(hub.getStack()).toHaveLength(2); expect(hub.getStack()[1].client).toBe(testClient); }); expect(hub.getStack()).toHaveLength(1); }); test('should bubble up exceptions', () => { const error = new Error('test'); expect(() => { hub.withScope(() => { throw error; }); }).toThrow(error); }); }); test('getCurrentClient', () => { const testClient: any = { bla: 'a' }; const hub = new Hub(testClient); expect(hub.getClient()).toBe(testClient); }); test('getStack', () => { const client: any = { a: 'b' }; const hub = new Hub(client); expect(hub.getStack()[0].client).toBe(client); }); test('getStackTop', () => { const testClient: any = { bla: 'a' }; const hub = new Hub(); hub.pushScope(); hub.pushScope(); hub.bindClient(testClient); expect(hub.getStackTop().client).toEqual({ bla: 'a' }); }); describe('configureScope', () => { test('should have an access to provide scope', () => { const localScope = new Scope(); localScope.setExtra('a', 'b'); const hub = new Hub({} as any, localScope); const cb = jest.fn(); hub.configureScope(cb); expect(cb).toHaveBeenCalledWith(localScope); }); test('should not invoke without client and scope', () => { const hub = new Hub(); const cb = jest.fn(); hub.configureScope(cb); expect(cb).not.toHaveBeenCalled(); }); }); describe('captureException', () => { test('simple', () => { const testClient = makeClient(); const hub = new Hub(testClient); hub.captureException('a'); const args = getPassedArgs(testClient.captureException); expect(args[0]).toBe('a'); }); test('should set event_id in hint', () => { const testClient = makeClient(); const hub = new Hub(testClient); hub.captureException('a'); const args = getPassedArgs(testClient.captureException); expect(args[1].event_id).toBeTruthy(); }); test('should keep event_id from hint', () => { const testClient = makeClient(); const hub = new Hub(testClient); const id = Math.random().toString(); hub.captureException('a', { event_id: id }); const args = getPassedArgs(testClient.captureException); expect(args[1].event_id).toBe(id); }); test('should generate hint if not provided in the call', () => { const testClient = makeClient(); const hub = new Hub(testClient); const ex = new Error('foo'); hub.captureException(ex); const args = getPassedArgs(testClient.captureException); expect(args[1].originalException).toBe(ex); expect(args[1].syntheticException).toBeInstanceOf(Error); expect(args[1].syntheticException.message).toBe('Sentry syntheticException'); }); }); describe('captureMessage', () => { test('simple', () => { const testClient = makeClient(); const hub = new Hub(testClient); hub.captureMessage('a'); const args = getPassedArgs(testClient.captureMessage); expect(args[0]).toBe('a'); }); test('should set event_id in hint', () => { const testClient = makeClient(); const hub = new Hub(testClient); hub.captureMessage('a'); const args = getPassedArgs(testClient.captureMessage); expect(args[2].event_id).toBeTruthy(); }); test('should keep event_id from hint', () => { const testClient = makeClient(); const hub = new Hub(testClient); const id = Math.random().toString(); hub.captureMessage('a', undefined, { event_id: id }); const args = getPassedArgs(testClient.captureMessage); expect(args[2].event_id).toBe(id); }); test('should generate hint if not provided in the call', () => { const testClient = makeClient(); const hub = new Hub(testClient); hub.captureMessage('foo'); const args = getPassedArgs(testClient.captureMessage); expect(args[2].originalException).toBe('foo'); expect(args[2].syntheticException).toBeInstanceOf(Error); expect(args[2].syntheticException.message).toBe('foo'); }); }); describe('captureEvent', () => { test('simple', () => { const event: Event = { extra: { b: 3 }, }; const testClient = makeClient(); const hub = new Hub(testClient); hub.captureEvent(event); const args = getPassedArgs(testClient.captureEvent); expect(args[0]).toBe(event); }); test('should set event_id in hint', () => { const event: Event = { extra: { b: 3 }, }; const testClient = makeClient(); const hub = new Hub(testClient); hub.captureEvent(event); const args = getPassedArgs(testClient.captureEvent); expect(args[1].event_id).toBeTruthy(); }); test('should keep event_id from hint', () => { const event: Event = { extra: { b: 3 }, }; const testClient = makeClient(); const hub = new Hub(testClient); const id = Math.random().toString(); hub.captureEvent(event, { event_id: id }); const args = getPassedArgs(testClient.captureEvent); expect(args[1].event_id).toBe(id); }); test('sets lastEventId', () => { const event: Event = { extra: { b: 3 }, }; const testClient = makeClient(); const hub = new Hub(testClient); hub.captureEvent(event); const args = getPassedArgs(testClient.captureEvent); expect(args[1].event_id).toEqual(hub.lastEventId()); }); test('transactions do not set lastEventId', () => { const event: Event = { extra: { b: 3 }, type: 'transaction', }; const testClient = makeClient(); const hub = new Hub(testClient); hub.captureEvent(event); const args = getPassedArgs(testClient.captureEvent); expect(args[1].event_id).not.toEqual(hub.lastEventId()); }); }); test('lastEventId should be the same as last created', () => { const event: Event = { extra: { b: 3 }, }; const hub = new Hub(); const eventId = hub.captureEvent(event); expect(eventId).toBe(hub.lastEventId()); }); describe('run', () => { test('simple', () => { const currentHub = getCurrentHub(); const myScope = new Scope(); const myClient: any = { a: 'b' }; myScope.setExtra('a', 'b'); const myHub = new Hub(myClient, myScope); myHub.run(hub => { expect(hub.getScope()).toBe(myScope); expect(hub.getClient()).toBe(myClient); expect(hub).toBe(getCurrentHub()); }); expect(currentHub).toBe(getCurrentHub()); }); test('should bubble up exceptions', () => { const hub = new Hub(); const error = new Error('test'); expect(() => { hub.run(() => { throw error; }); }).toThrow(error); }); }); describe('breadcrumbs', () => { test('withScope', () => { expect.assertions(6); const hub = new Hub(clientFn); hub.addBreadcrumb({ message: 'My Breadcrumb' }); hub.withScope(scope => { scope.addBreadcrumb({ message: 'scope breadcrumb' }); const event: Event = {}; void scope .applyToEvent(event) .then((appliedEvent: Event | null) => { expect(appliedEvent).toBeTruthy(); expect(appliedEvent!.breadcrumbs).toHaveLength(2); expect(appliedEvent!.breadcrumbs![0].message).toEqual('My Breadcrumb'); expect(appliedEvent!.breadcrumbs![0]).toHaveProperty('timestamp'); expect(appliedEvent!.breadcrumbs![1].message).toEqual('scope breadcrumb'); expect(appliedEvent!.breadcrumbs![1]).toHaveProperty('timestamp'); }) .then(null, e => { // eslint-disable-next-line no-console console.error(e); }); }); }); }); });
the_stack
"use strict"; import { GitRemoteLike, GitRepository } from "git/gitService"; import { toRepoName } from "../git/utils"; import * as paths from "path"; import * as qs from "querystring"; import { URI } from "vscode-uri"; import { SessionContainer } from "../container"; import { Logger } from "../logger"; import { Markerish, MarkerLocationManager } from "../managers/markerLocationManager"; import { MAX_RANGE_VALUE } from "../markerLocation/calculator"; import { BitbucketBoard, BitbucketCard, BitbucketCreateCardRequest, BitbucketCreateCardResponse, CreateThirdPartyCardRequest, DocumentMarker, FetchThirdPartyBoardsRequest, FetchThirdPartyBoardsResponse, FetchThirdPartyCardsRequest, FetchThirdPartyCardsResponse, FetchThirdPartyCardWorkflowRequest, FetchThirdPartyCardWorkflowResponse, FetchThirdPartyPullRequestCommitsRequest, FetchThirdPartyPullRequestCommitsResponse, FetchThirdPartyPullRequestRequest, FetchThirdPartyPullRequestResponse, GetMyPullRequestsRequest, GetMyPullRequestsResponse, MoveThirdPartyCardRequest, MoveThirdPartyCardResponse, ThirdPartyProviderCard } from "../protocol/agent.protocol"; import { CodemarkType, CSBitbucketProviderInfo, CSLocationArray, CSReferenceLocation } from "../protocol/api.protocol"; import { Arrays, log, lspProvider, Strings } from "../system"; import { ApiResponse, getOpenedRepos, getRemotePaths, ProviderCreatePullRequestRequest, ProviderCreatePullRequestResponse, ProviderPullRequestInfo, PullRequestComment, REFRESH_TIMEOUT, ThirdPartyIssueProviderBase, ThirdPartyProviderSupportsIssues, ThirdPartyProviderSupportsPullRequests } from "./provider"; interface BitbucketRepo { uuid: string; full_name: string; path: string; owner: { uuid: string; username: string; type: string; }; has_issues: boolean; } interface BitbucketPermission { permission: string; repository: BitbucketRepo; } interface BitbucketUser { uuid: string; display_name: string; account_id: string; } interface BitbucketValues<T> { values: T; next: string; } interface BitbucketPullRequest { id: number; title: string; state: string; destination: { branch: { name: string; }; }; source: { branch: { name: string; }; }; links: { html: { href: string }; comments: { href: string; }; }; } interface BitbucketPullRequestComment { id: string; user: { account_id: string; nickname: string; }; content: { raw: string; }; created_on: string; links: { html: { href: string }; code: { href: string } }; inline: { to?: number; from?: number; outdated?: boolean; path: string; }; pullrequest: { id: number; title: string; links: { html: { href: string; }; }; }; } interface GetPullRequestsResponse extends BitbucketValues<BitbucketPullRequest[]> {} interface GetPullRequestCommentsResponse extends BitbucketValues<BitbucketPullRequestComment[]> {} /** * BitBucket provider * @see https://developer.atlassian.com/bitbucket/api/2/reference/ */ @lspProvider("bitbucket") export class BitbucketProvider extends ThirdPartyIssueProviderBase<CSBitbucketProviderInfo> implements ThirdPartyProviderSupportsIssues, ThirdPartyProviderSupportsPullRequests { private _bitbucketUserId: string | undefined; private _knownRepos = new Map<string, BitbucketRepo>(); private _reposWithIssues: BitbucketRepo[] = []; get displayName() { return "Bitbucket"; } get name() { return "bitbucket"; } get headers() { return { Authorization: `Bearer ${this.accessToken}`, "Content-Type": "application/json" }; } getPRExternalContent(comment: PullRequestComment) { return { provider: { name: this.displayName, icon: this.name, id: this.providerConfig.id }, subhead: `#${comment.pullRequest.id}`, actions: [ { label: "Open Comment", uri: comment.url }, { label: `Open Merge Request #${comment.pullRequest.id}`, uri: comment.pullRequest.url } ] }; } async onConnected(providerInfo?: CSBitbucketProviderInfo) { super.onConnected(providerInfo); this._bitbucketUserId = await this.getMemberId(); this._knownRepos = new Map<string, BitbucketRepo>(); } @log() async getBoards(request?: FetchThirdPartyBoardsRequest): Promise<FetchThirdPartyBoardsResponse> { void (await this.ensureConnected()); const openRepos = await getOpenedRepos<BitbucketRepo>( r => r.domain === "bitbucket.org", p => this.get<BitbucketRepo>(`/repositories/${p}`), this._knownRepos ); let boards: BitbucketBoard[]; if (openRepos.size > 0) { const bitbucketRepos = Array.from(openRepos.values()); boards = bitbucketRepos .filter(r => r.has_issues) .map(r => ({ id: r.uuid, name: r.full_name, apiIdentifier: r.full_name, path: r.path, singleAssignee: true // bitbucket issues only allow one assignee })); } else { let bitbucketRepos: BitbucketRepo[] = []; try { let apiResponse = await this.get<BitbucketValues<BitbucketPermission[]>>( `/user/permissions/repositories?${qs.stringify({ fields: "+values.repository.has_issues" })}` ); bitbucketRepos = apiResponse.body.values.map(p => p.repository); while (apiResponse.body.next) { apiResponse = await this.get<BitbucketValues<BitbucketPermission[]>>( apiResponse.body.next ); bitbucketRepos = bitbucketRepos.concat(apiResponse.body.values.map(p => p.repository)); } } catch (err) { Logger.error(err); debugger; } bitbucketRepos = bitbucketRepos.filter(r => r.has_issues); this._reposWithIssues = [...bitbucketRepos]; boards = bitbucketRepos.map(r => { return { ...r, id: r.uuid, name: r.full_name, apiIdentifier: r.full_name, singleAssignee: true // bitbucket issues only allow one assignee }; }); } return { boards }; } // FIXME -- implement this async getCardWorkflow( request: FetchThirdPartyCardWorkflowRequest ): Promise<FetchThirdPartyCardWorkflowResponse> { return { workflow: [] }; } @log() async getCards(request: FetchThirdPartyCardsRequest): Promise<FetchThirdPartyCardsResponse> { void (await this.ensureConnected()); const cards: ThirdPartyProviderCard[] = []; if (this._reposWithIssues.length === 0) await this.getBoards(); await Promise.all( this._reposWithIssues.map(async repo => { const { body } = await this.get<{ uuid: string; [key: string]: any }>( `/repositories/${repo.full_name}/issues` ); // @ts-ignore body.values.forEach(card => { cards.push({ id: card.id, url: card.links.html.href, title: card.title, modifiedAt: new Date(card.updated_on).getTime(), tokenId: card.id, body: card.content ? card.content.raw : "" }); }); }) ); return { cards }; } @log() async createCard(request: CreateThirdPartyCardRequest) { void (await this.ensureConnected()); const data = request.data as BitbucketCreateCardRequest; const cardData: { [key: string]: any } = { title: data.title, content: { raw: data.description, markup: "markdown" } }; if (data.assignee) { cardData.assignee = { uuid: data.assignee.uuid }; } const response = await this.post<{}, BitbucketCreateCardResponse>( `/repositories/${data.repoName}/issues`, cardData ); let card = response.body; let issueResponse; try { const strippedPath = card.links.self.href.split(this.baseUrl)[1]; issueResponse = await this.get<BitbucketCard>(strippedPath); } catch (err) { Logger.error(err); return card; } card = issueResponse.body; card.url = card.links.html!.href; return card; } @log() async moveCard(request: MoveThirdPartyCardRequest): Promise<MoveThirdPartyCardResponse> { return { success: false }; } private async getMemberId() { const userResponse = await this.get<{ uuid: string; [key: string]: any }>(`/user`); return userResponse.body.uuid; } @log() async getAssignableUsers(request: { boardId: string }) { void (await this.ensureConnected()); try { const repoResponse = await this.get<BitbucketRepo>(`/repositories/${request.boardId}`); if (repoResponse.body.owner.type === "team") { let members: BitbucketUser[] = []; let apiResponse = await this.get<BitbucketValues<BitbucketUser[]>>( `/users/${repoResponse.body.owner.username}/members` ); members = apiResponse.body.values; while (apiResponse.body.next) { apiResponse = await this.get<BitbucketValues<BitbucketUser[]>>(apiResponse.body.next); members = members.concat(apiResponse.body.values); } return { users: members.map(u => ({ ...u, id: u.account_id, displayName: u.display_name })) }; } else { const userResponse = await this.get<BitbucketUser>("/user"); const user = userResponse.body; return { users: [{ ...user, id: user.account_id, displayName: user.display_name }] }; } } catch (ex) { Logger.error(ex); return { users: [] }; } } @log() getPullRequest( request: FetchThirdPartyPullRequestRequest ): Promise<FetchThirdPartyPullRequestResponse> { throw new Error("Method not implemented."); } @log() getPullRequestCommits( request: FetchThirdPartyPullRequestCommitsRequest ): Promise<FetchThirdPartyPullRequestCommitsResponse> { throw new Error("Method not implemented."); } @log() getMyPullRequests( request: GetMyPullRequestsRequest ): Promise<GetMyPullRequestsResponse[][] | undefined> { throw new Error("Method not implemented."); } @log() getPullRequestDocumentMarkers({ uri, repoId, streamId }: { uri: URI; repoId: string | undefined; streamId: string; }): Promise<DocumentMarker[]> { return super.getPullRequestDocumentMarkersCore({ uri, repoId, streamId }); } async getRemotePaths(repo: any, _projectsByRemotePath: any) { // TODO don't need this ensureConnected -- doesn't hit api await this.ensureConnected(); const remotePaths = await getRemotePaths( repo, this.getIsMatchingRemotePredicate(), _projectsByRemotePath ); return remotePaths; } protected getOwnerFromRemote(remote: string): { owner: string; name: string } { // HACKitude yeah, sorry const uri = URI.parse(remote); const split = uri.path.split("/"); const owner = split[1]; const name = toRepoName(split[2]); return { owner, name }; } async createPullRequest( request: ProviderCreatePullRequestRequest ): Promise<ProviderCreatePullRequestResponse | undefined> { void (await this.ensureConnected()); try { const repoInfo = await this.getRepoInfo({ remote: request.remote }); if (repoInfo && repoInfo.error) { return { error: repoInfo.error }; } const { owner, name } = this.getOwnerFromRemote(request.remote); const createPullRequestResponse = await this.post< BitBucketCreatePullRequestRequest, BitBucketCreatePullRequestResponse >(`/repositories/${owner}/${name}/pullrequests`, { source: { branch: { name: request.headRefName } }, destination: { branch: { name: request.baseRefName } }, title: request.title, description: this.createDescription(request) }); const title = `#${createPullRequestResponse.body.id} ${createPullRequestResponse.body.title}`; return { url: createPullRequestResponse.body.links.html.href, title: title }; } catch (ex) { Logger.error(ex, `${this.displayName}: createPullRequest`, { remote: request.remote, head: request.headRefName, base: request.baseRefName }); let message = ex.message; if (message.indexOf("credentials lack one or more required privilege scopes") > -1) { message += "\n\nYou may need to disconnect and reconnect your Bitbucket for CodeStream integration to create your first Pull Request."; } return { error: { type: "PROVIDER", message: `${this.displayName}: ${message}` } }; } } async getRepoInfo(request: { remote: string }): Promise<any> { try { const { owner, name } = this.getOwnerFromRemote(request.remote); const repoResponse = await this.get<BitBucketRepo>(`/repositories/${owner}/${name}`); const pullRequestResponse = await this.get<BitBucketPullRequest>( `/repositories/${owner}/${name}/pullrequests?state=OPEN` ); let pullRequests: ProviderPullRequestInfo[] = []; if (pullRequestResponse && pullRequestResponse.body && pullRequestResponse.body.values) { pullRequests = pullRequestResponse.body.values.map(_ => { return { id: _.id, url: _.links!.html!.href, baseRefName: _.destination.branch.name, headRefName: _.source.branch.name }; }); } return { id: repoResponse.body.uuid, defaultBranch: repoResponse.body && repoResponse.body.mainbranch && repoResponse.body.mainbranch.name && repoResponse.body.mainbranch.type === "branch" ? repoResponse.body.mainbranch.name : undefined, pullRequests: pullRequests }; } catch (ex) { Logger.error(ex, `${this.displayName}: getRepoInfo`, { remote: request.remote }); return { error: { type: "PROVIDER", message: `${this.displayName}: ${ex.message}` } }; } } private _commentsByRepoAndPath = new Map< string, { expiresAt: number; comments: Promise<PullRequestComment[]> } >(); private _isMatchingRemotePredicate = (r: GitRemoteLike) => r.domain === "bitbucket.org"; getIsMatchingRemotePredicate() { return this._isMatchingRemotePredicate; } @log() async getCommentsForPath( filePath: string, repo: GitRepository ): Promise<PullRequestComment[] | undefined> { const cc = Logger.getCorrelationContext(); try { const relativePath = Strings.normalizePath(paths.relative(repo.path, filePath)); const cacheKey = `${repo.path}|${relativePath}`; const cachedComments = this._commentsByRepoAndPath.get(cacheKey); if (cachedComments !== undefined && cachedComments.expiresAt > new Date().getTime()) { // NOTE: Keep this await here, so any errors are caught here return await cachedComments.comments; } super.invalidatePullRequestDocumentMarkersCache(); const remotePath = await getRemotePaths( repo, this.getIsMatchingRemotePredicate(), this._knownRepos ); const commentsPromise: Promise<PullRequestComment[]> = remotePath != null ? this._getCommentsForPathCore(filePath, relativePath, remotePath) : Promise.resolve([]); this._commentsByRepoAndPath.set(cacheKey, { expiresAt: new Date().setMinutes(new Date().getMinutes() + REFRESH_TIMEOUT), comments: commentsPromise }); // Since we aren't cached, we want to just kick of the request to get the comments (which will fire a notification) // This could probably be enhanced to wait for the commentsPromise for a short period of time (maybe 1s?) to see if it will complete, to avoid the notification roundtrip for fast requests return undefined; } catch (ex) { Logger.error(ex, cc); return undefined; } } private async _getCommentsForPathCore( filePath: string, relativePath: string, remotePaths: string[] ) { const comments = []; for (const remotePath of remotePaths) { const pullRequestsResponse = await this.get<GetPullRequestsResponse>( `/repositories/${remotePath}/pullrequests?${qs.stringify({ q: "comment_count>0" })}` ); const prComments = ( await Promise.all( pullRequestsResponse.body.values.map(pr => this._getPullRequestComments(pr, relativePath)) ) ).reduce((group, current) => group.concat(current), []); comments.push(...prComments); } // If we have any comments, fire a notification if (comments.length !== 0) { void SessionContainer.instance().documentMarkers.fireDidChangeDocumentMarkers( URI.file(filePath).toString(), "codemarks" ); } return comments; } private async _getPullRequestComments( pr: BitbucketPullRequest, filePath: string ): Promise<PullRequestComment[]> { const comments: PullRequestComment[] = []; let nextPage: string | undefined = pr.links.comments.href.replace(this.baseUrl, ""); while (nextPage) { const commentsResponse: ApiResponse<GetPullRequestCommentsResponse> = await this.get( `${nextPage}?${qs.stringify({ q: `inline.path="${filePath}"`, fields: "values.inline.*,values.content.raw,values.user.nickname,values.user.account_id,values.links.html.href,values.created_on,values.links.code.href,values.id" })}` ); comments.push( ...Arrays.filterMap(commentsResponse.body.values, comment => { if (comment.inline.outdated) return undefined; const [source, destination] = comment.links.code.href .match(/\:([^\/][\d\S]+)\?/)![1] .split(".."); const [commit, line] = comment.inline.from ? [destination, comment.inline.from] : [source, comment.inline.to]; if (line == null) return undefined; return { commit, id: comment.id, text: comment.content.raw, code: "", author: { ...comment.user, id: comment.user.account_id }, line: Number(line), path: comment.inline.path, url: comment.links.html.href, createdAt: new Date(comment.created_on).getTime(), pullRequest: { id: pr.id, title: pr.title, url: pr.links.html.href, isOpen: pr.state === "OPEN", targetBranch: pr.destination.branch.name, sourceBranch: pr.source.branch.name } }; }) ); if (commentsResponse.body.next) { nextPage = commentsResponse.body.next.replace(this.baseUrl, ""); } else { nextPage = undefined; } } return comments; } } interface BitBucketCreatePullRequestRequest { source: { branch: { name: string; }; }; destination: { branch: { name: string; }; }; title: string; description?: string; } interface BitBucketCreatePullRequestResponse { id: string; links: { html: { href: string } }; number: number; title: string; } interface BitBucketRepo { uuid: string; mainbranch?: { name?: string; type?: string; }; } interface BitBucketPullRequest { values: { id: string; source: { branch: { name: string; }; }; destination: { branch: { name: string; }; }; links: { html: { href: string } }; }[]; }
the_stack
import { isNullOrUndefined } from "util"; import { deleteAt } from "../Helpers"; import { CssNodeDump } from "./Types"; export default class CssNode { /** A mapping of keys to CSS properties */ private _children: Array<CssNode>; /** Keep track of names added */ private _childNames = new Set<string>(); private _name: string; private _selector: string; private _properties: Map<string, string>; private parent?: CssNode; public description?: string; /** * Create a new CSS node * @param name * @param properties * @param selector */ constructor(name: string, properties: object, selector?: string) { this._name = name; this._children = new Array<CssNode>(); this._properties = new Map<string, string>(); for (let k in properties) { this._properties.set(k, properties[k]); } // Use name as selector if not provided this._selector = selector || name; } get isRoot() { return isNullOrUndefined(this.parent); } get name() { return this._name; } set name(newName: string) { this._name = newName; } get selector() { return this._selector; } set selector(newSelector: string) { this._selector = newSelector; } /** Get the root of the tree */ get treeRoot() { let parent = this.parent; if (!parent) { return this; } while (true) { if (isNullOrUndefined(parent.parent)) { return parent; } else { parent = parent.parent; } } } /** Compute the full CSS selector for this subtree */ get fullSelector() { // Build an array of all of this node's ancestors let nodes = new Array<CssNode>(this); let parent = this.parent; while (!isNullOrUndefined(parent)) { nodes.push(parent); parent = parent.parent; } // Now ordered from top to bottom nodes = nodes.reverse(); let selectors = new Array<string>(); // Build CSS selector by traversing from the top down, // appending each node's selector to each selector in the // current array of selectors as we go for (let node of nodes) { // Split selectors by comma and remove extra whitespace let partialSelectors = node.selector.split(',').map( (sel: string) => sel.trim()); if (selectors.length > 0) { let buffer = [...selectors]; selectors = new Array<string>(); for (let selector of buffer) { for (let partialSelector of partialSelectors) { const space = (partialSelector.charAt(0) === ":") ? "" : " "; selectors.push(`${selector}${space}${partialSelector}`); } } } else { // Base case selectors = [...partialSelectors]; } } return selectors.join(', '); } /** Get this node's path in the subtree */ get fullPath() { let parent = this.parent; let path = [ this.name ]; while (!isNullOrUndefined(parent)) { path.push(parent.name); parent = parent.parent; } // Remove top most name from path path = path.slice(0, path.length - 1); return path.reverse(); } get children() { return this._children; } get properties(): Map<string, string> { return this._properties; } set properties(data: Map<string, string>) { this._properties = data; } static load(data: CssNodeDump): CssNode { let rootNode = new CssNode(data.name, {}, data.selector); rootNode.properties = new Map<string, string>(data.properties); rootNode.description = data.description; // Load children for (let node of data.children) { rootNode.addNode(CssNode.load(node)); } return rootNode; } deepCopy(): CssNode { return CssNode.load(this.dump()); } dump() : CssNodeDump { let data: CssNodeDump = { children: this.children.map((elem) => elem.dump()), name: this.name, description: this.description, properties: Array.from(this.properties.entries()), selector: this.selector } return data; } private formatProperties() { let cssProperties = new Array<string>(); if (this.properties.size > 0) { for (let [property, entry] of this.properties.entries()) { cssProperties.push(`\t${property}: ${entry};`); } } return cssProperties.join('\n'); } /** Return a CSS stylesheet */ stylesheet() { let cssProperties = this.formatProperties(); const thisCss = this.properties.size > 0 ? `${this.fullSelector} {\n${cssProperties}\n}` : ``; let childStylesheets = new Array<string>(); for (let cssTree of this.children.values()) { const childCss = cssTree.stylesheet(); if (childCss.length > 0) { childStylesheets.push(childCss); } } let finalStylesheet = [ thisCss ]; if (childStylesheets.length > 0) { finalStylesheet = finalStylesheet.concat(childStylesheets); } return finalStylesheet.join('\n\n'); } /** * Add a CssNode and return a reference to the added node * @param css */ add(name: string, properties, selector?: string): CssNode { return this.addNode(new CssNode(name, properties, selector || name)); } addNode(node: CssNode): CssNode { if (this.hasName(node.name)) { throw new Error(`Already have a child named ${node.name}`); } node.parent = this; this.children.push(node); this._childNames.add(node.name); return this.children[this.children.length - 1]; } // TODO: Add tests delete(path: string[]) { const parent = this.findNode(path.slice(0, path.length - 1)); const childName = path[path.length - 1]; if (parent && parent.hasName(childName)) { parent.deleteDirectChild(childName); } } private deleteDirectChild(name: string) { this._childNames.delete(name); let deleteIndex = -1; for (let i in this._children) { if (this._children[i].name === name) { deleteIndex = parseInt(i); break; } } if (deleteIndex >= 0) { this._children = deleteAt(this._children, deleteIndex); } } /** * Returns true if there is already a child node with the given name * @param name Name to look for */ hasName(name: string) { return this._childNames.has(name); } /** Return a copy of this subtree with the same names and selectors * but with no properties * @param name New name for the copy (defaults to current name) * @param selector Additional selector to append on to current selector */ copySkeleton(name?: string, selector?: string): CssNode { const newName = name || this.name; let newSelector = selector || this.selector; let newTree = new CssNode(newName, {}, newSelector); for (let node of this.children) { newTree.addNode(node.copySkeleton()); } return newTree; } /** * Find a CSS node somewhere in this subtree * @param path A list of names ordered from higher up in the tree to lower */ findNode(path: string | string[]): CssNode | undefined { if (path.length === 0) { return this; } if (!Array.isArray(path)) { path = [path]; } for (let node of this.children) { if (node.name === path[0]) { // No more subtrees to traverse if (path.length === 1) { return node; } return node.findNode(path.slice(1)); } } return; } mustFindNode(path: string | string[]): CssNode { const result = this.findNode(path); if (!result) { const pathStr = Array.isArray(path) ? path.join(', ') : path; throw new Error(`Couldn't find node at ${pathStr}`); } return result; } setProperty(path: string[], key: string, value: string) { const targetNode = this.findNode(path); if (targetNode) { targetNode.properties.set(key, value); } } deleteProperty(path: string[], key: string) { const targetNode = this.findNode(path); if (targetNode) { targetNode.properties.delete(key); } } updateProperties(properties: Array<[string, string]>, path?: string | string[]) { const targetNode = path ? this.findNode(path) : this; if (targetNode) { properties.forEach((pair) => { targetNode.properties.set(pair[0], pair[1]); }) } return this; } setProperties(properties: Array<[string, string]>, path?: string | string[]) { const targetNode = path ? this.findNode(path) : this; if (targetNode) { targetNode.properties = new Map<string, string>(properties); } return this; } } /** A non-modifiable CSS node */ export class ReadonlyCssNode { private node: CssNode; constructor(node: CssNode) { this.node = node; } get children() { return this.node.children.map((node) => new ReadonlyCssNode(node)); } get description() { return this.node.description; } get fullPath(): string[] { return this.node.fullPath; } get fullSelector(): string { return this.node.fullSelector; } get isRoot(): boolean { return this.node.isRoot; } get name(): string { return this.node.name; } get properties(): Map<string, string> { return this.node.properties; } get selector(): string { return this.node.selector; } hasName(name: string) { return this.node.hasName(name); } }
the_stack
import * as fs from 'fs'; import { each, endsWith, every, filter, find, first, flatMap, isFunction, map, some, trimStart } from 'lodash'; import { Models } from 'omnisharp-client'; import { DriverState } from 'omnisharp-client'; import { createObservable } from 'omnisharp-client'; import * as path from 'path'; import { BehaviorSubject, Observable, ReplaySubject, Scheduler, Subject } from 'rxjs'; import { gt as semverGt, SemVer } from 'semver'; import { CompositeDisposable, Disposable, IDisposable } from 'ts-disposables'; import { metadataOpener } from './metadata-editor'; import { isOmnisharpTextEditor, OmnisharpEditorContext, IOmnisharpTextEditor } from './omnisharp-text-editor'; import { ProjectViewModel } from './project-view-model'; import { Solution } from './solution'; import { SolutionManager } from './solution-manager'; import { ViewModel } from './view-model'; // Time we wait to try and do our active switch tasks. const DEBOUNCE_TIMEOUT = 100; const statefulProperties = ['isOff', 'isConnecting', 'isOn', 'isReady', 'isError']; function wrapEditorObservable(observable: Observable<IOmnisharpTextEditor>) { return observable .subscribeOn(Scheduler.async) .observeOn(Scheduler.async) .filter(editor => !editor || editor && !editor.isDestroyed()); } class OmniManager implements IDisposable { private disposable: CompositeDisposable; private _editors: Observable<IOmnisharpTextEditor>; private _configEditors: Observable<IOmnisharpTextEditor>; private _underlyingEditors = new Set<IOmnisharpTextEditor>(); private _supportedExtensions = ['project.json', '.cs', '.csx']; private _packageDir: string; private _atomVersion: SemVer; public get viewModelStatefulProperties() { return statefulProperties; } private _activeEditorOrConfigEditorSubject = new BehaviorSubject<IOmnisharpTextEditor>(null); private _activeEditorOrConfigEditor = wrapEditorObservable(<Observable<IOmnisharpTextEditor>><any>this._activeEditorOrConfigEditorSubject) .debounceTime(DEBOUNCE_TIMEOUT) .publishReplay(1) .refCount(); private _activeEditor = wrapEditorObservable(<Observable<IOmnisharpTextEditor>><any>this._activeEditorOrConfigEditorSubject) .debounceTime(DEBOUNCE_TIMEOUT) .map(x => x && x.omnisharp && !x.omnisharp.config ? x : null) .publishReplay(1) .refCount(); private _activeConfigEditor = wrapEditorObservable(<Observable<IOmnisharpTextEditor>><any>this._activeEditorOrConfigEditorSubject) .debounceTime(DEBOUNCE_TIMEOUT) .map(x => x && x.omnisharp && x.omnisharp.config ? x : null) .publishReplay(1) .refCount(); private _activeProject = this._activeEditorOrConfigEditor .filter(editor => editor && !editor.isDestroyed()) .switchMap(editor => editor.omnisharp.solution.model.getProjectForEditor(editor)) .distinctUntilChanged() .publishReplay(1) .refCount(); private _activeFramework = this._activeEditorOrConfigEditor .filter(editor => editor && !editor.isDestroyed()) .switchMap(editor => editor.omnisharp.solution.model.getProjectForEditor(editor)) .switchMap(project => project.observe.activeFramework, (project, framework) => ({ project, framework })) .distinctUntilChanged() .publishReplay(1) .refCount(); private _diagnosticsSubject = new Subject<Models.DiagnosticLocation[]>(); private _diagnostics = this._diagnosticsSubject.publishReplay(1).refCount(); public get diagnostics() { return this._diagnostics; } private _diagnosticCountsSubject = new Subject<{ [key: string]: number; }>(); private _diagnosticCounts = this._diagnosticCountsSubject.publishReplay(1).refCount(); public get diagnosticsCounts() { return this._diagnosticCounts; } private _diagnosticsByFileSubject = new Subject<Map<string, Models.DiagnosticLocation[]>>(); private _diagnosticsByFile = this._diagnosticsByFileSubject.publishReplay(1).refCount(); public get diagnosticsByFile() { return this._diagnosticsByFile; } private _isOff = true; public get isOff() { return this._isOff; } public get isOn() { return !this.isOff; } // tslint:disable-next-line:max-func-body-length public activate() { this.disposable = new CompositeDisposable(); this.disposable.add(metadataOpener()); const editors = this._createTextEditorObservable(this.disposable); this._editors = wrapEditorObservable(editors.filter(x => !x.omnisharp.config)); this._configEditors = wrapEditorObservable(editors.filter(x => x.omnisharp.config)); // Restore solutions after the server was disconnected this.disposable.add(SolutionManager.activeSolution.subscribe(solution => { each(filter(atom.workspace.getTextEditors(), x => this._isOmniSharpEditor(x) && !(<any>x).omnisharp), x => { SolutionManager.getSolutionForEditor(x); }); })); SolutionManager.activate(this._activeEditorOrConfigEditor); // we are only off if all our solutions are disconncted or erroed. this.disposable.add( SolutionManager.solutionAggregateObserver.state .subscribe(z => { this._isOff = every(z, x => x.value === DriverState.Disconnected || x.value === DriverState.Error); })); this.disposable.add( createObservable<Atom.TextEditor>(observer => { const dis = atom.workspace.observeActivePaneItem((pane: any) => { if (pane && pane.getGrammar && pane.getPath && this.isValidGrammar(pane.getGrammar())) { observer.next(<Atom.TextEditor>pane); return; } observer.next(null); }); return () => dis.dispose(); }) .concatMap(pane => { if (!pane || isOmnisharpTextEditor(pane)) { return Observable.of(pane); } return wrapEditorObservable( SolutionManager.getSolutionForEditor(pane) .map(x => <IOmnisharpTextEditor>pane) ); }) .subscribe(this._activeEditorOrConfigEditorSubject)); this.disposable.add(Disposable.create(() => { this._activeEditorOrConfigEditorSubject.next(null); })); // Cache this result, because the underlying implementation of observe will // create a cache of the last recieved value. This allows us to pick pick // up from where we left off. const codeCheckAggregate = this.aggregateListener.listenTo(z => z.model.observe.diagnostics) .debounceTime(200) .map(data => flatMap(data, x => x.value)); const codeCheckCountAggregate = this.aggregateListener.listenTo(z => z.model.observe.diagnosticsCounts) .debounceTime(200) .map(items => { const result: typeof ViewModel.prototype.diagnosticCounts = {}; each(items, y => { each(y.value, (x, k) => { if (!result[k]) { result[k] = 0; } result[k] += x; }); }); return result; }); const codeCheckByFileAggregate = this.aggregateListener.listenTo(z => z.model.observe.diagnosticsByFile.map(x => z.model.diagnosticsByFile)) .debounceTime(200) .map(x => { const map = new Map<string, Models.DiagnosticLocation[]>(); each(x, z => { for (const [file, diagnostics] of z.value) { map.set(file, diagnostics); } }); return map; }); const showDiagnosticsForAllSolutions = new ReplaySubject<boolean>(1); this.disposable.add(atom.config.observe('omnisharp-atom.showDiagnosticsForAllSolutions', enabled => { showDiagnosticsForAllSolutions.next(enabled); })); this.disposable.add(showDiagnosticsForAllSolutions); const baseDiagnostics = Observable.combineLatest( // Combine both the active model and the configuration changes together this.activeModel.startWith(null), showDiagnosticsForAllSolutions, showDiagnosticsForAllSolutions .skip(1) .startWith(atom.config.get<boolean>('omnisharp-atom.showDiagnosticsForAllSolutions')), (model, enabled, wasEnabled) => ({ model, enabled, wasEnabled })) // If the setting is enabled (and hasn"t changed) then we don"t need to redo the subscription .filter(ctx => (!(ctx.enabled && ctx.wasEnabled === ctx.enabled))) .share(); this.disposable.add( baseDiagnostics .switchMap(ctx => { const { enabled, model } = ctx; if (enabled) { return codeCheckAggregate; } else if (model) { return model.observe.diagnostics; } return Observable.of([]); }) .startWith([]) .subscribe(this._diagnosticsSubject), baseDiagnostics .switchMap(ctx => { const { enabled, model } = ctx; if (enabled) { return codeCheckCountAggregate; } else if (model) { return model.observe.diagnosticsCounts; } return <any>Observable.empty<{ [index: string]: number; }>(); }) .startWith({}) .subscribe(this._diagnosticCountsSubject), baseDiagnostics .switchMap(ctx => { const { enabled, model } = ctx; if (enabled) { return codeCheckByFileAggregate; } else if (model) { return model.observe.diagnosticsByFile.map(x => model.diagnosticsByFile); } return Observable.of(new Map<string, Models.DiagnosticLocation[]>()); }) .startWith(new Map<string, Models.DiagnosticLocation[]>()) .subscribe(this._diagnosticsByFileSubject) ); } public dispose() { if (SolutionManager._unitTestMode_) { return; } this.disposable.dispose(); SolutionManager.deactivate(); } public connect() { SolutionManager.connect(); } public disconnect() { SolutionManager.disconnect(); } public toggle() { if (SolutionManager.connected) { SolutionManager.disconnect(); } else { SolutionManager.connect(); } } public navigateTo(response: { FileName: string; Line: number; Column: number; }) { return Observable.fromPromise( atom.workspace.open(response.FileName, <any>{ initialLine: response.Line, initialColumn: response.Column }) ); } public getFrameworks(projects: string[]): string { const frameworks = map(projects, (project: string) => { return project.indexOf('+') === -1 ? '' : project.split('+')[1]; }).filter((fw: string) => fw.length > 0); return frameworks.join(','); } public addTextEditorCommand(commandName: string, callback: (...args: any[]) => any) { return atom.commands.add('atom-text-editor', commandName, event => { const editor = atom.workspace.getActiveTextEditor(); if (!editor) { return; } if (some(this._supportedExtensions, ext => endsWith(editor.getPath(), ext))) { event.stopPropagation(); event.stopImmediatePropagation(); callback(event); } }); } /** * This property can be used to listen to any event that might come across on any solutions. * This is a mostly functional replacement for `registerConfiguration`, though there has been * one place where `registerConfiguration` could not be replaced. */ public get listener() { return SolutionManager.solutionObserver; } /** * This property can be used to observe to the aggregate or combined responses to any event. * A good example of this is, for code check errors, to aggregate all errors across all open solutions. */ public get aggregateListener() { return SolutionManager.solutionAggregateObserver; } /** * This property gets a list of solutions as an observable. * NOTE: This property will not emit additions or removals of solutions. */ public get solutions() { return Observable.defer(() => Observable.from<Solution>(SolutionManager.activeSolutions)); } /* * This method allows us to forget about the entire solution model. * Call this method with a specific editor, or just with a callback to capture the current editor * * The callback will then issue the request * NOTE: This API only exposes the operation Api and doesn"t expose the event api, as we are requesting something to happen */ public request<T>(editor: Atom.TextEditor, callback: (solution: Solution) => Observable<T>): Observable<T>; public request<T>(callback: (solution: Solution) => Observable<T>): Observable<T>; public request<T>( editor: Atom.TextEditor | ((solution: Solution) => Observable<T> | Promise<T>), callback?: (solution: Solution) => Observable<T>): Observable<T> { if (isFunction(editor)) { callback = <any>editor; editor = null; } if (!editor) { editor = atom.workspace.getActiveTextEditor(); } const solutionCallback = (solution: Solution) => callback(solution.withEditor(<any>editor)); let result: Observable<T>; if (editor && isOmnisharpTextEditor(editor)) { result = solutionCallback(editor.omnisharp.solution) .share(); result.subscribe(); return result; } let solutionResult: Observable<Solution>; if (editor) { solutionResult = SolutionManager.getSolutionForEditor(<Atom.TextEditor>editor); } else { solutionResult = SolutionManager.activeSolution.take(1); } result = solutionResult .filter(z => !!z) .flatMap(solutionCallback) .share(); // Ensure that the underying promise is connected // (if we don"t subscribe to the reuslt of the request, which is not a requirement). result.subscribe(); return result; } public getProject(editor: Atom.TextEditor) { if (isOmnisharpTextEditor(editor) && editor.omnisharp.project) { return Observable.of(editor.omnisharp.project); } return SolutionManager.getSolutionForEditor(editor) .flatMap(z => z.model.getProjectForEditor(editor)) .take(1); } public getSolutionForProject(project: ProjectViewModel<any>) { return Observable.of( first(filter(SolutionManager.activeSolutions, solution => some(solution.model.projects, p => p.name === project.name))) ); } public getSolutionForEditor(editor: Atom.TextEditor) { if (isOmnisharpTextEditor(editor)) { return Observable.of(editor.omnisharp.solution); } return SolutionManager.getSolutionForEditor(editor); } /** * Allows for views to observe the active model as it changes between editors */ public get activeModel() { return SolutionManager.activeSolution.map(z => z.model); } public switchActiveModel(callback: (model: ViewModel, cd: CompositeDisposable) => void): IDisposable { const outerCd = new CompositeDisposable(); outerCd.add(this.activeModel.filter(z => !!z).subscribe(model => { const cd = new CompositeDisposable(); outerCd.add(cd); model.disposable.add(cd); cd.add(this.activeModel.filter(active => active !== model) .subscribe(() => { model.disposable.remove(cd); outerCd.remove(cd); cd.dispose(); })); callback(model, cd); })); return outerCd; } public get activeSolution() { return SolutionManager.activeSolution; } public switchActiveSolution(callback: (solution: Solution, cd: CompositeDisposable) => void): IDisposable { const outerCd = new CompositeDisposable(); outerCd.add(this.activeSolution.filter(z => !!z).subscribe(solution => { const cd = new CompositeDisposable(); outerCd.add(cd); solution.disposable.add(cd); cd.add(this.activeSolution.filter(active => active !== solution) .subscribe(() => { solution.disposable.remove(cd); outerCd.remove(cd); cd.dispose(); })); callback(solution, cd); })); return outerCd; } public get activeEditor() { return this._activeEditor; } public switchActiveEditor(callback: (editor: IOmnisharpTextEditor, cd: CompositeDisposable) => void): IDisposable { const outerCd = new CompositeDisposable(); outerCd.add(this.activeEditor.filter(z => !!z).subscribe(editor => { const cd = new CompositeDisposable(); outerCd.add(cd); editor.omnisharp.solution.disposable.add(cd); cd.add(this.activeEditor.filter(active => active !== editor) .subscribe(() => { editor.omnisharp.solution.disposable.remove(cd); outerCd.remove(cd); cd.dispose(); })); callback(editor, cd); })); return outerCd; } public whenEditorConnected(editor: Atom.TextEditor) { if (isOmnisharpTextEditor(editor)) { return editor.omnisharp.solution .whenConnected() .map(z => editor); } return SolutionManager.getSolutionForEditor(editor) .flatMap(solution => solution.whenConnected(), () => <IOmnisharpTextEditor>editor); } public get activeConfigEditor() { return this._activeConfigEditor; } public switchActiveConfigEditor(callback: (editor: IOmnisharpTextEditor, cd: CompositeDisposable) => void): IDisposable { const outerCd = new CompositeDisposable(); outerCd.add(this.activeConfigEditor.filter(z => !!z).subscribe(editor => { const cd = new CompositeDisposable(); outerCd.add(cd); editor.omnisharp.solution.disposable.add(cd); cd.add(this.activeConfigEditor.filter(active => active !== editor) .subscribe(() => { editor.omnisharp.solution.disposable.remove(cd); outerCd.remove(cd); cd.dispose(); })); callback(editor, cd); })); return outerCd; } public get activeEditorOrConfigEditor() { return this._activeEditorOrConfigEditor; } public switchActiveEditorOrConfigEditor(callback: (editor: IOmnisharpTextEditor, cd: CompositeDisposable) => void): IDisposable { const outerCd = new CompositeDisposable(); outerCd.add(this.activeEditorOrConfigEditor.filter(z => !!z).subscribe(editor => { const cd = new CompositeDisposable(); outerCd.add(cd); cd.add(this.activeEditorOrConfigEditor.filter(active => active !== editor) .subscribe(() => { outerCd.remove(cd); cd.dispose(); })); callback(editor, cd); })); return outerCd; } public get activeProject() { return this._activeProject; } public get activeFramework() { return this._activeFramework; } public get editors() { return this._editors; } public get configEditors() { return this._configEditors; } public eachEditor(callback: (editor: IOmnisharpTextEditor, cd: CompositeDisposable) => void): IDisposable { const outerCd = new CompositeDisposable(); outerCd.add(this._editors.subscribe(editor => { const cd = new CompositeDisposable(); outerCd.add(cd); editor.omnisharp.solution.disposable.add(cd); cd.add(editor.onDidDestroy((() => { editor.omnisharp.solution.disposable.remove(cd); outerCd.remove(cd); cd.dispose(); }))); callback(editor, cd); })); return outerCd; } public eachConfigEditor(callback: (editor: IOmnisharpTextEditor, cd: CompositeDisposable) => void): IDisposable { const outerCd = new CompositeDisposable(); outerCd.add(this._configEditors.subscribe(editor => { const cd = new CompositeDisposable(); outerCd.add(cd); editor.omnisharp.solution.disposable.add(cd); cd.add(editor.onDidDestroy((() => { editor.omnisharp.solution.disposable.remove(cd); outerCd.remove(cd); cd.dispose(); }))); callback(editor, cd); })); return outerCd; } public registerConfiguration(callback: (solution: Solution) => void) { SolutionManager.registerConfiguration(callback); } private get _kick_in_the_pants_() { return SolutionManager._kick_in_the_pants_; } public get grammars() { return filter(atom.grammars.getGrammars(), grammar => some(this._supportedExtensions, ext => some((<any>grammar).fileTypes, ft => trimStart(ext, '.') === ft))); } public isValidGrammar(grammar: FirstMate.Grammar) { return some(this.grammars, { scopeName: (<any>grammar).scopeName }); } public get packageDir() { if (!this._packageDir) { console.info(`getPackageDirPaths: ${atom.packages.getPackageDirPaths()}`); this._packageDir = find(atom.packages.getPackageDirPaths(), packagePath => { console.info(`packagePath ${packagePath} exists: ${fs.existsSync(path.join(packagePath, 'omnisharp-atom'))}`); return fs.existsSync(path.join(packagePath, 'omnisharp-atom')); }); // Fallback, this is for unit testing on travis mainly if (!this._packageDir) { this._packageDir = path.resolve(__dirname, '../../..'); } } return this._packageDir; } public get atomVersion() { if (!this._atomVersion) { this._atomVersion = new SemVer(<any>atom.getVersion()); } return this._atomVersion; } public atomVersionGreaterThan(version: string) { return semverGt(<any>atom.getVersion(), version); } private _isOmniSharpEditor(editor: Atom.TextEditor) { return some(this._supportedExtensions, ext => endsWith(editor.getPath(), ext)); } private _createTextEditorObservable(disposable: CompositeDisposable) { const safeGuard = this._createSafeGuard(this._supportedExtensions, disposable); const observeTextEditors = createObservable<Atom.TextEditor>(observer => { const dis = atom.workspace.observeTextEditors((editor: Atom.TextEditor) => { observer.next(editor); }); return () => dis.dispose(); }).share(); this.disposable.add( Observable.merge(observeTextEditors.filter(x => !!x.getPath()), safeGuard) .mergeMap(editor => SolutionManager.getSolutionForEditor(editor), (editor, solution) => <IOmnisharpTextEditor>editor) .subscribe(), OmnisharpEditorContext.created .subscribe(editor => { this._underlyingEditors.add(editor); editor.omnisharp.config = endsWith(editor.getPath(), 'project.json'); const dis = Disposable.create(() => { this._underlyingEditors.delete(editor); }); this.disposable.add( dis, editor.onDidDestroy(() => dis.dispose()) ); editor.omnisharp.solution.disposable.add(dis); }) ); const liveEditors = OmnisharpEditorContext.created; return Observable.merge( Observable.defer(() => Observable.from<IOmnisharpTextEditor>(<any>this._underlyingEditors)), liveEditors ); } private _createSafeGuard(extensions: string[], disposable: CompositeDisposable) { const editorSubject = new Subject<IOmnisharpTextEditor>(); disposable.add(atom.workspace.observeActivePaneItem((pane: any) => editorSubject.next(pane))); const editorObservable = editorSubject.filter(z => z && !!z.getGrammar).startWith(null); return Observable.zip(editorObservable, editorObservable.skip(1), (editor, nextEditor) => ({ editor, nextEditor })) .debounceTime(50) .switchMap(({ nextEditor }) => { const path = nextEditor.getPath(); if (!path) { // editor isn"t saved yet. if (nextEditor && this._isOmniSharpEditor(nextEditor)) { atom.notifications.addInfo('OmniSharp', { detail: 'Functionality will limited until the file has been saved.' }); } return new Promise<Atom.TextEditor>((resolve, reject) => { const disposer = nextEditor.onDidChangePath(() => { resolve(nextEditor); disposer.dispose(); }); }); } return Promise.resolve(null); }) .filter(x => !!x); } } // tslint:disable-next-line:export-name variable-name export const Omni = new OmniManager();
the_stack
import { Sorts, SortDirection, ConnectableTypeEnum } from "./globalTypes"; // ==================================================== // GraphQL query operation: ChannelTableContentsSet // ==================================================== export interface ChannelTableContentsSet_channel_counts { __typename: "ChannelCounts"; contents: number | null; blocks: number | null; channels: number | null; } export interface ChannelTableContentsSet_channel_can { __typename: "ChannelCan"; update: boolean | null; } export interface ChannelTableContentsSet_channel_blokks_Attachment_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ChannelTableContentsSet_channel_blokks_Attachment_connection_user { __typename: "User"; name: string; } export interface ChannelTableContentsSet_channel_blokks_Attachment_connection { __typename: "Connection"; can: ChannelTableContentsSet_channel_blokks_Attachment_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ChannelTableContentsSet_channel_blokks_Attachment_connection_user | null; } export interface ChannelTableContentsSet_channel_blokks_Attachment_user { __typename: "User"; name: string; } export interface ChannelTableContentsSet_channel_blokks_Attachment_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelTableContentsSet_channel_blokks_Attachment_source { __typename: "ConnectableSource"; url: string | null; provider_url: string | null; } export interface ChannelTableContentsSet_channel_blokks_Attachment_counts { __typename: "BlockCounts"; public_channels: number | null; } export interface ChannelTableContentsSet_channel_blokks_Attachment { __typename: "Attachment"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelTableContentsSet_channel_blokks_Attachment_connection | null; created_at: string | null; updated_at: string | null; title: string; user: ChannelTableContentsSet_channel_blokks_Attachment_user | null; can: ChannelTableContentsSet_channel_blokks_Attachment_can | null; source: ChannelTableContentsSet_channel_blokks_Attachment_source | null; counts: ChannelTableContentsSet_channel_blokks_Attachment_counts | null; file_url: string | null; image_url: string | null; } export interface ChannelTableContentsSet_channel_blokks_Embed_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ChannelTableContentsSet_channel_blokks_Embed_connection_user { __typename: "User"; name: string; } export interface ChannelTableContentsSet_channel_blokks_Embed_connection { __typename: "Connection"; can: ChannelTableContentsSet_channel_blokks_Embed_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ChannelTableContentsSet_channel_blokks_Embed_connection_user | null; } export interface ChannelTableContentsSet_channel_blokks_Embed_user { __typename: "User"; name: string; } export interface ChannelTableContentsSet_channel_blokks_Embed_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelTableContentsSet_channel_blokks_Embed_source { __typename: "ConnectableSource"; url: string | null; provider_url: string | null; } export interface ChannelTableContentsSet_channel_blokks_Embed_counts { __typename: "BlockCounts"; public_channels: number | null; } export interface ChannelTableContentsSet_channel_blokks_Embed { __typename: "Embed"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelTableContentsSet_channel_blokks_Embed_connection | null; created_at: string | null; updated_at: string | null; title: string; user: ChannelTableContentsSet_channel_blokks_Embed_user | null; can: ChannelTableContentsSet_channel_blokks_Embed_can | null; source: ChannelTableContentsSet_channel_blokks_Embed_source | null; counts: ChannelTableContentsSet_channel_blokks_Embed_counts | null; embed_html: string | null; image_url: string | null; } export interface ChannelTableContentsSet_channel_blokks_Image_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ChannelTableContentsSet_channel_blokks_Image_connection_user { __typename: "User"; name: string; } export interface ChannelTableContentsSet_channel_blokks_Image_connection { __typename: "Connection"; can: ChannelTableContentsSet_channel_blokks_Image_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ChannelTableContentsSet_channel_blokks_Image_connection_user | null; } export interface ChannelTableContentsSet_channel_blokks_Image_user { __typename: "User"; name: string; } export interface ChannelTableContentsSet_channel_blokks_Image_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelTableContentsSet_channel_blokks_Image_source { __typename: "ConnectableSource"; url: string | null; provider_url: string | null; } export interface ChannelTableContentsSet_channel_blokks_Image_counts { __typename: "BlockCounts"; public_channels: number | null; } export interface ChannelTableContentsSet_channel_blokks_Image { __typename: "Image"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelTableContentsSet_channel_blokks_Image_connection | null; created_at: string | null; updated_at: string | null; title: string; user: ChannelTableContentsSet_channel_blokks_Image_user | null; can: ChannelTableContentsSet_channel_blokks_Image_can | null; source: ChannelTableContentsSet_channel_blokks_Image_source | null; find_original_url: string | null; counts: ChannelTableContentsSet_channel_blokks_Image_counts | null; image_url: string | null; } export interface ChannelTableContentsSet_channel_blokks_Link_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ChannelTableContentsSet_channel_blokks_Link_connection_user { __typename: "User"; name: string; } export interface ChannelTableContentsSet_channel_blokks_Link_connection { __typename: "Connection"; can: ChannelTableContentsSet_channel_blokks_Link_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ChannelTableContentsSet_channel_blokks_Link_connection_user | null; } export interface ChannelTableContentsSet_channel_blokks_Link_user { __typename: "User"; name: string; } export interface ChannelTableContentsSet_channel_blokks_Link_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelTableContentsSet_channel_blokks_Link_source { __typename: "ConnectableSource"; url: string | null; provider_url: string | null; } export interface ChannelTableContentsSet_channel_blokks_Link_counts { __typename: "BlockCounts"; public_channels: number | null; } export interface ChannelTableContentsSet_channel_blokks_Link { __typename: "Link"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelTableContentsSet_channel_blokks_Link_connection | null; created_at: string | null; updated_at: string | null; title: string; user: ChannelTableContentsSet_channel_blokks_Link_user | null; can: ChannelTableContentsSet_channel_blokks_Link_can | null; source: ChannelTableContentsSet_channel_blokks_Link_source | null; counts: ChannelTableContentsSet_channel_blokks_Link_counts | null; image_url: string | null; } export interface ChannelTableContentsSet_channel_blokks_PendingBlock_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ChannelTableContentsSet_channel_blokks_PendingBlock_connection_user { __typename: "User"; name: string; } export interface ChannelTableContentsSet_channel_blokks_PendingBlock_connection { __typename: "Connection"; can: ChannelTableContentsSet_channel_blokks_PendingBlock_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ChannelTableContentsSet_channel_blokks_PendingBlock_connection_user | null; } export interface ChannelTableContentsSet_channel_blokks_PendingBlock_user { __typename: "User"; name: string; } export interface ChannelTableContentsSet_channel_blokks_PendingBlock_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelTableContentsSet_channel_blokks_PendingBlock_counts { __typename: "BlockCounts"; public_channels: number | null; } export interface ChannelTableContentsSet_channel_blokks_PendingBlock { __typename: "PendingBlock"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelTableContentsSet_channel_blokks_PendingBlock_connection | null; created_at: string | null; updated_at: string | null; title: string; user: ChannelTableContentsSet_channel_blokks_PendingBlock_user | null; can: ChannelTableContentsSet_channel_blokks_PendingBlock_can | null; counts: ChannelTableContentsSet_channel_blokks_PendingBlock_counts | null; } export interface ChannelTableContentsSet_channel_blokks_Text_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ChannelTableContentsSet_channel_blokks_Text_connection_user { __typename: "User"; name: string; } export interface ChannelTableContentsSet_channel_blokks_Text_connection { __typename: "Connection"; can: ChannelTableContentsSet_channel_blokks_Text_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ChannelTableContentsSet_channel_blokks_Text_connection_user | null; } export interface ChannelTableContentsSet_channel_blokks_Text_user { __typename: "User"; name: string; } export interface ChannelTableContentsSet_channel_blokks_Text_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelTableContentsSet_channel_blokks_Text_source { __typename: "ConnectableSource"; url: string | null; } export interface ChannelTableContentsSet_channel_blokks_Text_counts { __typename: "BlockCounts"; public_channels: number | null; } export interface ChannelTableContentsSet_channel_blokks_Text { __typename: "Text"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelTableContentsSet_channel_blokks_Text_connection | null; created_at: string | null; updated_at: string | null; title: string; user: ChannelTableContentsSet_channel_blokks_Text_user | null; can: ChannelTableContentsSet_channel_blokks_Text_can | null; source: ChannelTableContentsSet_channel_blokks_Text_source | null; counts: ChannelTableContentsSet_channel_blokks_Text_counts | null; content: string; html: string; } export interface ChannelTableContentsSet_channel_blokks_Channel_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; manage: boolean | null; } export interface ChannelTableContentsSet_channel_blokks_Channel_connection_user { __typename: "User"; name: string; } export interface ChannelTableContentsSet_channel_blokks_Channel_connection { __typename: "Connection"; can: ChannelTableContentsSet_channel_blokks_Channel_connection_can | null; position: number; selected: boolean; id: number; created_at: string | null; user: ChannelTableContentsSet_channel_blokks_Channel_connection_user | null; } export interface ChannelTableContentsSet_channel_blokks_Channel_user { __typename: "User"; name: string; } export interface ChannelTableContentsSet_channel_blokks_Channel_can { __typename: "ChannelCan"; mute: boolean | null; } export interface ChannelTableContentsSet_channel_blokks_Channel_counts { __typename: "ChannelCounts"; connected_to_channels: number | null; contents: number | null; } export interface ChannelTableContentsSet_channel_blokks_Channel { __typename: "Channel"; id: number; href: string | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelTableContentsSet_channel_blokks_Channel_connection | null; created_at: string | null; updated_at: string | null; title: string; user: ChannelTableContentsSet_channel_blokks_Channel_user | null; can: ChannelTableContentsSet_channel_blokks_Channel_can | null; visibility: string; counts: ChannelTableContentsSet_channel_blokks_Channel_counts | null; } export type ChannelTableContentsSet_channel_blokks = ChannelTableContentsSet_channel_blokks_Attachment | ChannelTableContentsSet_channel_blokks_Embed | ChannelTableContentsSet_channel_blokks_Image | ChannelTableContentsSet_channel_blokks_Link | ChannelTableContentsSet_channel_blokks_PendingBlock | ChannelTableContentsSet_channel_blokks_Text | ChannelTableContentsSet_channel_blokks_Channel; export interface ChannelTableContentsSet_channel { __typename: "Channel"; id: number; counts: ChannelTableContentsSet_channel_counts | null; can: ChannelTableContentsSet_channel_can | null; blokks: ChannelTableContentsSet_channel_blokks[] | null; } export interface ChannelTableContentsSet { /** * A single channel */ channel: ChannelTableContentsSet_channel | null; } export interface ChannelTableContentsSetVariables { id: string; page: number; per: number; sort?: Sorts | null; direction?: SortDirection | null; type?: ConnectableTypeEnum | null; user_id?: string | null; }
the_stack
import { action } from 'mobx'; import { observer } from 'mobx-react-lite'; import React, { useEffect, useState } from 'react'; import { Button, Checkbox, FormField, Grid, Header, Input, Modal, Select, SpaceBetween, StatusIndicator, Table, TokenGroup, } from '@awsui/components-react'; import * as c from '@aws-accelerator/config'; import { useI18n } from '@/components/i18n-context'; import { TypeTreeNode } from '@/types'; import { AcceleratorConfigurationNode } from '../configuration'; import { LabelWithDescription } from './label-with-description'; import { OptionDefinition } from '../../../../node_modules/@awsui/components-react/internal/components/option/interfaces'; import { useCheckboxInput, useInput } from '@/utils/hooks'; const ouConfigNode = AcceleratorConfigurationNode.nested('organizational-units'); const mandatoryAccountConfigNode = AcceleratorConfigurationNode.nested('mandatory-account-configs'); const workloadAccountConfigNode = AcceleratorConfigurationNode.nested('workload-account-configs'); interface SimpleVpcUnitValue { name: string; description: string; deploy: string; region: string; cidr: any[]; 'tgw-attach': any, subnets: any, guiCidr: any, } export interface VpcTableProps { state: any; } export const VpcTable: React.VFC<VpcTableProps> = observer(({ state }) => { const { tr } = useI18n(); const [modalVisible, setModalVisible] = useState(false); const [selectedItem, setSelectedItem] = useState<SimpleVpcUnitValue | undefined>(); const [modalInitialValue, setModalInitialValue] = useState<Partial<SimpleVpcUnitValue>>({}); const nodes = getVpcNodes(state); const nodesList: any[] = [] const populateNodesList = () => { for (let each in nodes) { nodesList.push(nodes[each].get(state) ?? {}) } } populateNodesList() const makeCidrList = (cidrPool: any) => { let cidrList = [] for (let each in cidrPool) { cidrList.push(["(" + cidrPool[each].pool + ", " + cidrPool[each].size] + ")") } return cidrList } const organizationalUnitsNode = AcceleratorConfigurationNode.nested('organizational-units').get(state); const mandatoryAccountConfigNodeState = AcceleratorConfigurationNode.nested('mandatory-account-configs').get(state); const getDefinedIn = (vpcName: string) => { return vpcName in organizationalUnitsNode ? 'Organizational Unit' : 'Account'; } const isSubnetShared = (vpcName: string) => { if (vpcName in organizationalUnitsNode) { return organizationalUnitsNode[vpcName]['vpc'][0].subnets?.find((s: any) => s['share-to-ou-accounts'] || s['share-to-specific-accounts']) != null; } else if ((vpcName.toLowerCase()) in mandatoryAccountConfigNodeState) { return mandatoryAccountConfigNodeState[vpcName.toLowerCase()]['vpc'][0].subnets?.find((s: any) => s['share-to-ou-accounts'] || s['share-to-specific-accounts']) != null; } else { for (let each in mandatoryAccountConfigNodeState) { if(mandatoryAccountConfigNodeState.hasOwnProperty('vpc') && mandatoryAccountConfigNodeState[each]['vpc'][0]['name'] === vpcName) { return mandatoryAccountConfigNodeState[each]['vpc'][0].subnets?.find((s: any) => s['share-to-ou-accounts'] || s['share-to-specific-accounts']) != null; } } } } const isTgwAttached = (vpcName: string) => { if (vpcName in organizationalUnitsNode) { return organizationalUnitsNode[vpcName]['vpc'][0].hasOwnProperty('tgw-attach') } else if ((vpcName.toLowerCase()) in mandatoryAccountConfigNodeState) { return mandatoryAccountConfigNodeState[vpcName.toLowerCase()]['vpc'][0].hasOwnProperty('tgw-attach'); } else { for (let each in mandatoryAccountConfigNodeState) { if(mandatoryAccountConfigNodeState.hasOwnProperty('vpc') && mandatoryAccountConfigNodeState[each]['vpc'][0]['name'] === vpcName) { return mandatoryAccountConfigNodeState[each]['vpc'][0].hasOwnProperty('tgw-attach'); } } } } const vpcItems: SimpleVpcUnitValue[] = Object.entries(nodesList).map( ([key, vpcConfig]: [string, any]) => { return { name: vpcConfig?.name, description: vpcConfig?.description ?? '', deploy: vpcConfig?.deploy ?? '', region: vpcConfig?.region, cidr: vpcConfig?.cidr, "tgw-attach": vpcConfig?.['tgw-attach'], subnets: vpcConfig?.subnets, guiCidr: makeCidrList(vpcConfig?.cidr) }; }, ); const handleEdit = () => { setModalInitialValue(selectedItem ?? {}); setModalVisible(true); }; const handleSubmit = action((value: SimpleVpcUnitValue) => { const {name, deploy, region, cidr} = value; for (let each in nodesList) { if (nodesList[each].name === name) { nodesList[each].deploy = deploy; nodesList[each].region = region; nodesList[each].cidr = cidr; } } setModalVisible(false); }) return ( <> { <EditVpcModal visible={modalVisible} initialValue={modalInitialValue} state={state} onDismiss={() => setModalVisible(false)} onSubmit={handleSubmit} /> } <Table items={vpcItems} trackBy="name" selectionType="single" selectedItems={selectedItem ? [selectedItem] : []} onSelectionChange={e => setSelectedItem(e.detail.selectedItems?.[0])} columnDefinitions={[ { header: 'Name', cell: ({ name, description }) => <LabelWithDescription label={name} description={description} />, }, { header: 'Defined in', cell: ({ name }) => getDefinedIn(name), }, { header: 'Deploy', cell: ({ deploy }) => deploy, }, { header: 'Shared', cell: ({ name }) => (isSubnetShared( name ) ? 'Yes' : 'No'), }, { header: 'TGW Attached', cell: ({ name }) => (isTgwAttached(name) ? 'Yes' : 'No'), }, { header: 'Region', cell: ({ region }) => region, }, { header: 'CIDR Pool(s) and Size', cell: ({ guiCidr }) => guiCidr.join(" || ") }, ]} header={ <Header variant="h2" counter={`(${nodes.length})`} description={tr('wizard.headers.vpcs_desc')} actions={ <SpaceBetween size="xs" direction="horizontal"> <Button disabled={selectedItem == null} onClick={handleEdit}> {tr('buttons.edit')} </Button> </SpaceBetween> } > {tr('wizard.headers.vpcs')} </Header> } footer={<StatusIndicator type="info">{tr('wizard.labels.vpcs_use_graphical_editor')}</StatusIndicator>} /> </> ); }); interface EditVpcModalProps { visible: boolean; initialValue: Partial<SimpleVpcUnitValue>; state: any; onDismiss: () => void; onSubmit: (value: SimpleVpcUnitValue) => void; } const EditVpcModal = ({ visible, initialValue, state, onDismiss, onSubmit }: EditVpcModalProps) => { const { tr } = useI18n(); const nameInputProps = useInput(); const useSharedInputProps = useCheckboxInput(); const useTGWProps = useCheckboxInput(); const organizationalUnitsNode = AcceleratorConfigurationNode.nested('organizational-units').get(state); const mandatoryAccountConfigNodeState = AcceleratorConfigurationNode.nested('mandatory-account-configs').get(state); const regionsNode = AcceleratorConfigurationNode.nested('global-options').nested('supported-regions'); const regionsNodeState = regionsNode.get(state) ?? {} var modalCidrList: any[] = [] const makeCidrList = () => { for (const each in initialValue.cidr) { let entry = [initialValue.cidr[parseInt(each)].pool, initialValue.cidr[parseInt(each)].size].join(", ") modalCidrList.push({label: entry, dismissLabel: entry}) } } console.log(modalCidrList) const [deployOption, setDeployOption] = useState<OptionDefinition>({ label: initialValue.deploy, value: initialValue.deploy }); const [regionOption, setRegionOption] = useState<OptionDefinition>({ label: initialValue.region, value: initialValue.region }); const [cidrList, setCidrList] = useState<any[]>([]); const [newCidr, setNewCidr] = useState(""); const [newCidrSize, setNewCidrSize] = useState<OptionDefinition>({ label: '16', value: '16' }); const configCidrList = (cidrs: any[]) => { var configCidrList: any[] = [] for (let each in cidrs) { var cidrSplit = cidrs[each].label.split(", ") configCidrList.push( { pool: cidrSplit[0], size: parseInt(cidrSplit[1]), } ) } return configCidrList } const handleSubmit = () => { onSubmit({ name: initialValue.name ?? '', description: initialValue.description ?? '', deploy: deployOption.value ?? '', region: regionOption.value ?? '', cidr: configCidrList(cidrList), "tgw-attach": initialValue['tgw-attach'], subnets: initialValue['subnets'], guiCidr: initialValue.guiCidr }) } useEffect(() => { makeCidrList() setCidrList([...modalCidrList]) setDeployOption({ label: initialValue.deploy, value: initialValue.deploy }) setRegionOption({ label: initialValue.region, value: initialValue.region }) }, [visible]); var options: { label: string; value: string; }[] = [] const populateSelect = () => { for (const each in regionsNodeState) { options.push({label: regionsNodeState[each], value: regionsNodeState[each]}) } } var cidrSizeOptions: {label: string; value: string; }[] = [] const populateSize = () => { for (let i=16; i <= 24; i++) { cidrSizeOptions.push({label: String(i), value: String(i)}) } } const vpcTitle = {title: "VPC Name", desc: "The name of the VPC that will be deployed"} const definedIn = {title: "Defined in", desc: "The location in which this VPC is defined in"} const deployTitle = {title: "Deploy", desc: "Local if being configured inside an account or shared-network if being configured inside an OU"} const regionTitle = {title: "Region", desc: "Region for the VPC"} const cidrPoolTitle = {title: "CIDR Pool Name & Size", desc: "The name of the CIDR pool to assign IP addresses from and the size of the CIDR pool to assign to the VPC. Size must be between 16-28."} const getDefinedIn = (vpcName: string) => { return organizationalUnitsNode && (vpcName in organizationalUnitsNode) ? 'Organizational Unit' : 'Account'; } return ( <Modal visible={visible} header={<Header variant="h3">{tr('wizard.headers.edit_vpc')}</Header>} footer={ <Button variant="primary" className="float-button" onClick={handleSubmit}> {tr('buttons.save_changes')} </Button> } onDismiss={onDismiss} > <form onSubmit={event => { event.stopPropagation(); event.preventDefault(); handleSubmit(); }} > {populateSize()} {populateSelect()} <SpaceBetween size="s"> <FormField label={vpcTitle.title} description={vpcTitle.desc}> <Input value={String(initialValue.name)} disabled /> </FormField> <FormField label={definedIn.title} description={definedIn.desc} stretch> <Input value={getDefinedIn(String(initialValue.name))} disabled /> </FormField> <FormField label={deployTitle.title} description={deployTitle.desc} stretch> <Select selectedOption={deployOption} onChange={({ detail }) => setDeployOption(detail.selectedOption) } options={[ { label: "shared-network", value: "shared-network" }, { label: "local", value: "local" },]} selectedAriaLabel="Selected" /> </FormField> <FormField label={regionTitle.title} description={regionTitle.desc} stretch> <Select selectedOption={regionOption} onChange={({ detail }) => setRegionOption(detail.selectedOption) } options={options} selectedAriaLabel="Selected" /> </FormField> <FormField label={cidrPoolTitle.title} description={cidrPoolTitle.desc} stretch> <SpaceBetween size="xs"> <TokenGroup onDismiss={({ detail: { itemIndex } }) => { setCidrList([ ...cidrList.slice(0, itemIndex), ...cidrList.slice(itemIndex + 1) ]); }} items={cidrList} /> <Grid gridDefinition={[{ colspan: 5}, { colspan: 5 }, {colspan: 2}]} > <div> <Input placeholder="Enter CIDR Name" onChange={({ detail }) => setNewCidr(detail.value)} value={newCidr} /> </div> <div> <Select placeholder="Enter CIDR Size" selectedOption={newCidrSize} onChange={({ detail }) => setNewCidrSize(detail.selectedOption) } options={cidrSizeOptions} selectedAriaLabel="Selected" /> </div> <div> <Button variant="normal" formAction="none" onClick={ () => { cidrList.push({label: newCidr + ", " + newCidrSize.value, dismissLabel: "Remove item"}) setCidrList([...cidrList]) }} >Add</Button> </div> </Grid> </SpaceBetween> </FormField> <SpaceBetween size="s" direction="horizontal"> <Checkbox checked disabled /> <span>Subnet shared <i>(Edit temporarily disabled)</i></span> </SpaceBetween> <SpaceBetween size="s" direction="horizontal"> <Checkbox checked disabled /> <span>Transit gateway attached <i>(Edit temporarily disabled)</i></span> </SpaceBetween> </SpaceBetween> </form> </Modal> ); }; export function getVpcNodes(state: any) { return [ ...getAccountOrOuVpcNodes(ouConfigNode, state), ...getAccountOrOuVpcNodes(mandatoryAccountConfigNode, state), ...getAccountOrOuVpcNodes(workloadAccountConfigNode, state), ]; } function getAccountOrOuVpcNodes(node: TypeTreeNode, state: any): TypeTreeNode<typeof c.VpcConfigType>[] { return Object.keys(node.get(state) ?? {}).flatMap(accountKey => { // prettier-ignore const vpcArrayNode = node.nested(accountKey).nested<typeof c.VpcConfigType>('vpc'); const vpcArray = vpcArrayNode.get(state) ?? []; return Object.keys(vpcArray).map(key => vpcArrayNode.nested(key)); }); }
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 WorkSpacesWeb extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: WorkSpacesWeb.Types.ClientConfiguration) config: Config & WorkSpacesWeb.Types.ClientConfiguration; /** * Associates a browser settings resource with a web portal. */ associateBrowserSettings(params: WorkSpacesWeb.Types.AssociateBrowserSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.AssociateBrowserSettingsResponse) => void): Request<WorkSpacesWeb.Types.AssociateBrowserSettingsResponse, AWSError>; /** * Associates a browser settings resource with a web portal. */ associateBrowserSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.AssociateBrowserSettingsResponse) => void): Request<WorkSpacesWeb.Types.AssociateBrowserSettingsResponse, AWSError>; /** * Associates a network settings resource with a web portal. */ associateNetworkSettings(params: WorkSpacesWeb.Types.AssociateNetworkSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.AssociateNetworkSettingsResponse) => void): Request<WorkSpacesWeb.Types.AssociateNetworkSettingsResponse, AWSError>; /** * Associates a network settings resource with a web portal. */ associateNetworkSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.AssociateNetworkSettingsResponse) => void): Request<WorkSpacesWeb.Types.AssociateNetworkSettingsResponse, AWSError>; /** * Associates a trust store with a web portal. */ associateTrustStore(params: WorkSpacesWeb.Types.AssociateTrustStoreRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.AssociateTrustStoreResponse) => void): Request<WorkSpacesWeb.Types.AssociateTrustStoreResponse, AWSError>; /** * Associates a trust store with a web portal. */ associateTrustStore(callback?: (err: AWSError, data: WorkSpacesWeb.Types.AssociateTrustStoreResponse) => void): Request<WorkSpacesWeb.Types.AssociateTrustStoreResponse, AWSError>; /** * Associates a user settings resource with a web portal. */ associateUserSettings(params: WorkSpacesWeb.Types.AssociateUserSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.AssociateUserSettingsResponse) => void): Request<WorkSpacesWeb.Types.AssociateUserSettingsResponse, AWSError>; /** * Associates a user settings resource with a web portal. */ associateUserSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.AssociateUserSettingsResponse) => void): Request<WorkSpacesWeb.Types.AssociateUserSettingsResponse, AWSError>; /** * Creates a browser settings resource that can be associated with a web portal. Once associated with a web portal, browser settings control how the browser will behave once a user starts a streaming session for the web portal. */ createBrowserSettings(params: WorkSpacesWeb.Types.CreateBrowserSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.CreateBrowserSettingsResponse) => void): Request<WorkSpacesWeb.Types.CreateBrowserSettingsResponse, AWSError>; /** * Creates a browser settings resource that can be associated with a web portal. Once associated with a web portal, browser settings control how the browser will behave once a user starts a streaming session for the web portal. */ createBrowserSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.CreateBrowserSettingsResponse) => void): Request<WorkSpacesWeb.Types.CreateBrowserSettingsResponse, AWSError>; /** * Creates an identity provider resource that is then associated with a web portal. */ createIdentityProvider(params: WorkSpacesWeb.Types.CreateIdentityProviderRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.CreateIdentityProviderResponse) => void): Request<WorkSpacesWeb.Types.CreateIdentityProviderResponse, AWSError>; /** * Creates an identity provider resource that is then associated with a web portal. */ createIdentityProvider(callback?: (err: AWSError, data: WorkSpacesWeb.Types.CreateIdentityProviderResponse) => void): Request<WorkSpacesWeb.Types.CreateIdentityProviderResponse, AWSError>; /** * Creates a network settings resource that can be associated with a web portal. Once associated with a web portal, network settings define how streaming instances will connect with your specified VPC. */ createNetworkSettings(params: WorkSpacesWeb.Types.CreateNetworkSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.CreateNetworkSettingsResponse) => void): Request<WorkSpacesWeb.Types.CreateNetworkSettingsResponse, AWSError>; /** * Creates a network settings resource that can be associated with a web portal. Once associated with a web portal, network settings define how streaming instances will connect with your specified VPC. */ createNetworkSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.CreateNetworkSettingsResponse) => void): Request<WorkSpacesWeb.Types.CreateNetworkSettingsResponse, AWSError>; /** * Creates a web portal. */ createPortal(params: WorkSpacesWeb.Types.CreatePortalRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.CreatePortalResponse) => void): Request<WorkSpacesWeb.Types.CreatePortalResponse, AWSError>; /** * Creates a web portal. */ createPortal(callback?: (err: AWSError, data: WorkSpacesWeb.Types.CreatePortalResponse) => void): Request<WorkSpacesWeb.Types.CreatePortalResponse, AWSError>; /** * Creates a trust store that can be associated with a web portal. A trust store contains certificate authority (CA) certificates. Once associated with a web portal, the browser in a streaming session will recognize certificates that have been issued using any of the CAs in the trust store. If your organization has internal websites that use certificates issued by private CAs, you should add the private CA certificate to the trust store. */ createTrustStore(params: WorkSpacesWeb.Types.CreateTrustStoreRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.CreateTrustStoreResponse) => void): Request<WorkSpacesWeb.Types.CreateTrustStoreResponse, AWSError>; /** * Creates a trust store that can be associated with a web portal. A trust store contains certificate authority (CA) certificates. Once associated with a web portal, the browser in a streaming session will recognize certificates that have been issued using any of the CAs in the trust store. If your organization has internal websites that use certificates issued by private CAs, you should add the private CA certificate to the trust store. */ createTrustStore(callback?: (err: AWSError, data: WorkSpacesWeb.Types.CreateTrustStoreResponse) => void): Request<WorkSpacesWeb.Types.CreateTrustStoreResponse, AWSError>; /** * Creates a user settings resource that can be associated with a web portal. Once associated with a web portal, user settings control how users can transfer data between a streaming session and the their local devices. */ createUserSettings(params: WorkSpacesWeb.Types.CreateUserSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.CreateUserSettingsResponse) => void): Request<WorkSpacesWeb.Types.CreateUserSettingsResponse, AWSError>; /** * Creates a user settings resource that can be associated with a web portal. Once associated with a web portal, user settings control how users can transfer data between a streaming session and the their local devices. */ createUserSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.CreateUserSettingsResponse) => void): Request<WorkSpacesWeb.Types.CreateUserSettingsResponse, AWSError>; /** * Deletes browser settings. */ deleteBrowserSettings(params: WorkSpacesWeb.Types.DeleteBrowserSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.DeleteBrowserSettingsResponse) => void): Request<WorkSpacesWeb.Types.DeleteBrowserSettingsResponse, AWSError>; /** * Deletes browser settings. */ deleteBrowserSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.DeleteBrowserSettingsResponse) => void): Request<WorkSpacesWeb.Types.DeleteBrowserSettingsResponse, AWSError>; /** * Deletes the identity provider. */ deleteIdentityProvider(params: WorkSpacesWeb.Types.DeleteIdentityProviderRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.DeleteIdentityProviderResponse) => void): Request<WorkSpacesWeb.Types.DeleteIdentityProviderResponse, AWSError>; /** * Deletes the identity provider. */ deleteIdentityProvider(callback?: (err: AWSError, data: WorkSpacesWeb.Types.DeleteIdentityProviderResponse) => void): Request<WorkSpacesWeb.Types.DeleteIdentityProviderResponse, AWSError>; /** * Deletes network settings. */ deleteNetworkSettings(params: WorkSpacesWeb.Types.DeleteNetworkSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.DeleteNetworkSettingsResponse) => void): Request<WorkSpacesWeb.Types.DeleteNetworkSettingsResponse, AWSError>; /** * Deletes network settings. */ deleteNetworkSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.DeleteNetworkSettingsResponse) => void): Request<WorkSpacesWeb.Types.DeleteNetworkSettingsResponse, AWSError>; /** * Deletes a web portal. */ deletePortal(params: WorkSpacesWeb.Types.DeletePortalRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.DeletePortalResponse) => void): Request<WorkSpacesWeb.Types.DeletePortalResponse, AWSError>; /** * Deletes a web portal. */ deletePortal(callback?: (err: AWSError, data: WorkSpacesWeb.Types.DeletePortalResponse) => void): Request<WorkSpacesWeb.Types.DeletePortalResponse, AWSError>; /** * Deletes the trust store. */ deleteTrustStore(params: WorkSpacesWeb.Types.DeleteTrustStoreRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.DeleteTrustStoreResponse) => void): Request<WorkSpacesWeb.Types.DeleteTrustStoreResponse, AWSError>; /** * Deletes the trust store. */ deleteTrustStore(callback?: (err: AWSError, data: WorkSpacesWeb.Types.DeleteTrustStoreResponse) => void): Request<WorkSpacesWeb.Types.DeleteTrustStoreResponse, AWSError>; /** * Deletes user settings. */ deleteUserSettings(params: WorkSpacesWeb.Types.DeleteUserSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.DeleteUserSettingsResponse) => void): Request<WorkSpacesWeb.Types.DeleteUserSettingsResponse, AWSError>; /** * Deletes user settings. */ deleteUserSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.DeleteUserSettingsResponse) => void): Request<WorkSpacesWeb.Types.DeleteUserSettingsResponse, AWSError>; /** * Disassociates browser settings from a web portal. */ disassociateBrowserSettings(params: WorkSpacesWeb.Types.DisassociateBrowserSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.DisassociateBrowserSettingsResponse) => void): Request<WorkSpacesWeb.Types.DisassociateBrowserSettingsResponse, AWSError>; /** * Disassociates browser settings from a web portal. */ disassociateBrowserSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.DisassociateBrowserSettingsResponse) => void): Request<WorkSpacesWeb.Types.DisassociateBrowserSettingsResponse, AWSError>; /** * Disassociates network settings from a web portal. */ disassociateNetworkSettings(params: WorkSpacesWeb.Types.DisassociateNetworkSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.DisassociateNetworkSettingsResponse) => void): Request<WorkSpacesWeb.Types.DisassociateNetworkSettingsResponse, AWSError>; /** * Disassociates network settings from a web portal. */ disassociateNetworkSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.DisassociateNetworkSettingsResponse) => void): Request<WorkSpacesWeb.Types.DisassociateNetworkSettingsResponse, AWSError>; /** * Disassociates a trust store from a web portal. */ disassociateTrustStore(params: WorkSpacesWeb.Types.DisassociateTrustStoreRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.DisassociateTrustStoreResponse) => void): Request<WorkSpacesWeb.Types.DisassociateTrustStoreResponse, AWSError>; /** * Disassociates a trust store from a web portal. */ disassociateTrustStore(callback?: (err: AWSError, data: WorkSpacesWeb.Types.DisassociateTrustStoreResponse) => void): Request<WorkSpacesWeb.Types.DisassociateTrustStoreResponse, AWSError>; /** * Disassociates user settings from a web portal. */ disassociateUserSettings(params: WorkSpacesWeb.Types.DisassociateUserSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.DisassociateUserSettingsResponse) => void): Request<WorkSpacesWeb.Types.DisassociateUserSettingsResponse, AWSError>; /** * Disassociates user settings from a web portal. */ disassociateUserSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.DisassociateUserSettingsResponse) => void): Request<WorkSpacesWeb.Types.DisassociateUserSettingsResponse, AWSError>; /** * Gets browser settings. */ getBrowserSettings(params: WorkSpacesWeb.Types.GetBrowserSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.GetBrowserSettingsResponse) => void): Request<WorkSpacesWeb.Types.GetBrowserSettingsResponse, AWSError>; /** * Gets browser settings. */ getBrowserSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.GetBrowserSettingsResponse) => void): Request<WorkSpacesWeb.Types.GetBrowserSettingsResponse, AWSError>; /** * Gets the identity provider. */ getIdentityProvider(params: WorkSpacesWeb.Types.GetIdentityProviderRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.GetIdentityProviderResponse) => void): Request<WorkSpacesWeb.Types.GetIdentityProviderResponse, AWSError>; /** * Gets the identity provider. */ getIdentityProvider(callback?: (err: AWSError, data: WorkSpacesWeb.Types.GetIdentityProviderResponse) => void): Request<WorkSpacesWeb.Types.GetIdentityProviderResponse, AWSError>; /** * Gets the network settings. */ getNetworkSettings(params: WorkSpacesWeb.Types.GetNetworkSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.GetNetworkSettingsResponse) => void): Request<WorkSpacesWeb.Types.GetNetworkSettingsResponse, AWSError>; /** * Gets the network settings. */ getNetworkSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.GetNetworkSettingsResponse) => void): Request<WorkSpacesWeb.Types.GetNetworkSettingsResponse, AWSError>; /** * Gets the web portal. */ getPortal(params: WorkSpacesWeb.Types.GetPortalRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.GetPortalResponse) => void): Request<WorkSpacesWeb.Types.GetPortalResponse, AWSError>; /** * Gets the web portal. */ getPortal(callback?: (err: AWSError, data: WorkSpacesWeb.Types.GetPortalResponse) => void): Request<WorkSpacesWeb.Types.GetPortalResponse, AWSError>; /** * Gets the service provider metadata. */ getPortalServiceProviderMetadata(params: WorkSpacesWeb.Types.GetPortalServiceProviderMetadataRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.GetPortalServiceProviderMetadataResponse) => void): Request<WorkSpacesWeb.Types.GetPortalServiceProviderMetadataResponse, AWSError>; /** * Gets the service provider metadata. */ getPortalServiceProviderMetadata(callback?: (err: AWSError, data: WorkSpacesWeb.Types.GetPortalServiceProviderMetadataResponse) => void): Request<WorkSpacesWeb.Types.GetPortalServiceProviderMetadataResponse, AWSError>; /** * Gets the trust store. */ getTrustStore(params: WorkSpacesWeb.Types.GetTrustStoreRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.GetTrustStoreResponse) => void): Request<WorkSpacesWeb.Types.GetTrustStoreResponse, AWSError>; /** * Gets the trust store. */ getTrustStore(callback?: (err: AWSError, data: WorkSpacesWeb.Types.GetTrustStoreResponse) => void): Request<WorkSpacesWeb.Types.GetTrustStoreResponse, AWSError>; /** * Gets the trust store certificate. */ getTrustStoreCertificate(params: WorkSpacesWeb.Types.GetTrustStoreCertificateRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.GetTrustStoreCertificateResponse) => void): Request<WorkSpacesWeb.Types.GetTrustStoreCertificateResponse, AWSError>; /** * Gets the trust store certificate. */ getTrustStoreCertificate(callback?: (err: AWSError, data: WorkSpacesWeb.Types.GetTrustStoreCertificateResponse) => void): Request<WorkSpacesWeb.Types.GetTrustStoreCertificateResponse, AWSError>; /** * Gets user settings. */ getUserSettings(params: WorkSpacesWeb.Types.GetUserSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.GetUserSettingsResponse) => void): Request<WorkSpacesWeb.Types.GetUserSettingsResponse, AWSError>; /** * Gets user settings. */ getUserSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.GetUserSettingsResponse) => void): Request<WorkSpacesWeb.Types.GetUserSettingsResponse, AWSError>; /** * Retrieves a list of browser settings. */ listBrowserSettings(params: WorkSpacesWeb.Types.ListBrowserSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.ListBrowserSettingsResponse) => void): Request<WorkSpacesWeb.Types.ListBrowserSettingsResponse, AWSError>; /** * Retrieves a list of browser settings. */ listBrowserSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.ListBrowserSettingsResponse) => void): Request<WorkSpacesWeb.Types.ListBrowserSettingsResponse, AWSError>; /** * Retrieves a list of identity providers for a specific web portal. */ listIdentityProviders(params: WorkSpacesWeb.Types.ListIdentityProvidersRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.ListIdentityProvidersResponse) => void): Request<WorkSpacesWeb.Types.ListIdentityProvidersResponse, AWSError>; /** * Retrieves a list of identity providers for a specific web portal. */ listIdentityProviders(callback?: (err: AWSError, data: WorkSpacesWeb.Types.ListIdentityProvidersResponse) => void): Request<WorkSpacesWeb.Types.ListIdentityProvidersResponse, AWSError>; /** * Retrieves a list of network settings. */ listNetworkSettings(params: WorkSpacesWeb.Types.ListNetworkSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.ListNetworkSettingsResponse) => void): Request<WorkSpacesWeb.Types.ListNetworkSettingsResponse, AWSError>; /** * Retrieves a list of network settings. */ listNetworkSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.ListNetworkSettingsResponse) => void): Request<WorkSpacesWeb.Types.ListNetworkSettingsResponse, AWSError>; /** * Retrieves a list or web portals. */ listPortals(params: WorkSpacesWeb.Types.ListPortalsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.ListPortalsResponse) => void): Request<WorkSpacesWeb.Types.ListPortalsResponse, AWSError>; /** * Retrieves a list or web portals. */ listPortals(callback?: (err: AWSError, data: WorkSpacesWeb.Types.ListPortalsResponse) => void): Request<WorkSpacesWeb.Types.ListPortalsResponse, AWSError>; /** * Retrieves a list of tags for a resource. */ listTagsForResource(params: WorkSpacesWeb.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.ListTagsForResourceResponse) => void): Request<WorkSpacesWeb.Types.ListTagsForResourceResponse, AWSError>; /** * Retrieves a list of tags for a resource. */ listTagsForResource(callback?: (err: AWSError, data: WorkSpacesWeb.Types.ListTagsForResourceResponse) => void): Request<WorkSpacesWeb.Types.ListTagsForResourceResponse, AWSError>; /** * Retrieves a list of trust store certificates. */ listTrustStoreCertificates(params: WorkSpacesWeb.Types.ListTrustStoreCertificatesRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.ListTrustStoreCertificatesResponse) => void): Request<WorkSpacesWeb.Types.ListTrustStoreCertificatesResponse, AWSError>; /** * Retrieves a list of trust store certificates. */ listTrustStoreCertificates(callback?: (err: AWSError, data: WorkSpacesWeb.Types.ListTrustStoreCertificatesResponse) => void): Request<WorkSpacesWeb.Types.ListTrustStoreCertificatesResponse, AWSError>; /** * Retrieves a list of trust stores. */ listTrustStores(params: WorkSpacesWeb.Types.ListTrustStoresRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.ListTrustStoresResponse) => void): Request<WorkSpacesWeb.Types.ListTrustStoresResponse, AWSError>; /** * Retrieves a list of trust stores. */ listTrustStores(callback?: (err: AWSError, data: WorkSpacesWeb.Types.ListTrustStoresResponse) => void): Request<WorkSpacesWeb.Types.ListTrustStoresResponse, AWSError>; /** * Retrieves a list of user settings. */ listUserSettings(params: WorkSpacesWeb.Types.ListUserSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.ListUserSettingsResponse) => void): Request<WorkSpacesWeb.Types.ListUserSettingsResponse, AWSError>; /** * Retrieves a list of user settings. */ listUserSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.ListUserSettingsResponse) => void): Request<WorkSpacesWeb.Types.ListUserSettingsResponse, AWSError>; /** * Adds or overwrites one or more tags for the specified resource. */ tagResource(params: WorkSpacesWeb.Types.TagResourceRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.TagResourceResponse) => void): Request<WorkSpacesWeb.Types.TagResourceResponse, AWSError>; /** * Adds or overwrites one or more tags for the specified resource. */ tagResource(callback?: (err: AWSError, data: WorkSpacesWeb.Types.TagResourceResponse) => void): Request<WorkSpacesWeb.Types.TagResourceResponse, AWSError>; /** * Removes one or more tags from the specified resource. */ untagResource(params: WorkSpacesWeb.Types.UntagResourceRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.UntagResourceResponse) => void): Request<WorkSpacesWeb.Types.UntagResourceResponse, AWSError>; /** * Removes one or more tags from the specified resource. */ untagResource(callback?: (err: AWSError, data: WorkSpacesWeb.Types.UntagResourceResponse) => void): Request<WorkSpacesWeb.Types.UntagResourceResponse, AWSError>; /** * Updates browser settings. */ updateBrowserSettings(params: WorkSpacesWeb.Types.UpdateBrowserSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.UpdateBrowserSettingsResponse) => void): Request<WorkSpacesWeb.Types.UpdateBrowserSettingsResponse, AWSError>; /** * Updates browser settings. */ updateBrowserSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.UpdateBrowserSettingsResponse) => void): Request<WorkSpacesWeb.Types.UpdateBrowserSettingsResponse, AWSError>; /** * Updates the identity provider. */ updateIdentityProvider(params: WorkSpacesWeb.Types.UpdateIdentityProviderRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.UpdateIdentityProviderResponse) => void): Request<WorkSpacesWeb.Types.UpdateIdentityProviderResponse, AWSError>; /** * Updates the identity provider. */ updateIdentityProvider(callback?: (err: AWSError, data: WorkSpacesWeb.Types.UpdateIdentityProviderResponse) => void): Request<WorkSpacesWeb.Types.UpdateIdentityProviderResponse, AWSError>; /** * Updates network settings. */ updateNetworkSettings(params: WorkSpacesWeb.Types.UpdateNetworkSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.UpdateNetworkSettingsResponse) => void): Request<WorkSpacesWeb.Types.UpdateNetworkSettingsResponse, AWSError>; /** * Updates network settings. */ updateNetworkSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.UpdateNetworkSettingsResponse) => void): Request<WorkSpacesWeb.Types.UpdateNetworkSettingsResponse, AWSError>; /** * Updates a web portal. */ updatePortal(params: WorkSpacesWeb.Types.UpdatePortalRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.UpdatePortalResponse) => void): Request<WorkSpacesWeb.Types.UpdatePortalResponse, AWSError>; /** * Updates a web portal. */ updatePortal(callback?: (err: AWSError, data: WorkSpacesWeb.Types.UpdatePortalResponse) => void): Request<WorkSpacesWeb.Types.UpdatePortalResponse, AWSError>; /** * Updates the trust store. */ updateTrustStore(params: WorkSpacesWeb.Types.UpdateTrustStoreRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.UpdateTrustStoreResponse) => void): Request<WorkSpacesWeb.Types.UpdateTrustStoreResponse, AWSError>; /** * Updates the trust store. */ updateTrustStore(callback?: (err: AWSError, data: WorkSpacesWeb.Types.UpdateTrustStoreResponse) => void): Request<WorkSpacesWeb.Types.UpdateTrustStoreResponse, AWSError>; /** * Updates the user settings. */ updateUserSettings(params: WorkSpacesWeb.Types.UpdateUserSettingsRequest, callback?: (err: AWSError, data: WorkSpacesWeb.Types.UpdateUserSettingsResponse) => void): Request<WorkSpacesWeb.Types.UpdateUserSettingsResponse, AWSError>; /** * Updates the user settings. */ updateUserSettings(callback?: (err: AWSError, data: WorkSpacesWeb.Types.UpdateUserSettingsResponse) => void): Request<WorkSpacesWeb.Types.UpdateUserSettingsResponse, AWSError>; } declare namespace WorkSpacesWeb { export type ARN = string; export type ArnList = ARN[]; export interface AssociateBrowserSettingsRequest { /** * The ARN of the browser settings. */ browserSettingsArn: ARN; /** * The ARN of the web portal. */ portalArn: ARN; } export interface AssociateBrowserSettingsResponse { /** * The ARN of the browser settings. */ browserSettingsArn: ARN; /** * The ARN of the web portal. */ portalArn: ARN; } export interface AssociateNetworkSettingsRequest { /** * The ARN of the network settings. */ networkSettingsArn: ARN; /** * The ARN of the web portal. */ portalArn: ARN; } export interface AssociateNetworkSettingsResponse { /** * The ARN of the network settings. */ networkSettingsArn: ARN; /** * The ARN of the web portal. */ portalArn: ARN; } export interface AssociateTrustStoreRequest { /** * The ARN of the web portal. */ portalArn: ARN; /** * The ARN of the trust store. */ trustStoreArn: ARN; } export interface AssociateTrustStoreResponse { /** * The ARN of the web portal. */ portalArn: ARN; /** * The ARN of the trust store. */ trustStoreArn: ARN; } export interface AssociateUserSettingsRequest { /** * The ARN of the web portal. */ portalArn: ARN; /** * The ARN of the user settings. */ userSettingsArn: ARN; } export interface AssociateUserSettingsResponse { /** * The ARN of the web portal. */ portalArn: ARN; /** * The ARN of the user settings. */ userSettingsArn: ARN; } export type BrowserPolicy = string; export interface BrowserSettings { /** * A list of web portal ARNs that this browser settings is associated with. */ associatedPortalArns?: ArnList; /** * A JSON string containing Chrome Enterprise policies that will be applied to all streaming sessions. */ browserPolicy?: BrowserPolicy; /** * The ARN of the browser settings. */ browserSettingsArn: ARN; } export type BrowserSettingsList = BrowserSettingsSummary[]; export interface BrowserSettingsSummary { /** * The ARN of the browser settings. */ browserSettingsArn?: ARN; } export type BrowserType = "Chrome"|string; export interface Certificate { /** * The body of the certificate. */ body?: CertificateAuthorityBody; /** * The entity that issued the certificate. */ issuer?: CertificatePrincipal; /** * The certificate is not valid after this date. */ notValidAfter?: Timestamp; /** * The certificate is not valid before this date. */ notValidBefore?: Timestamp; /** * The entity the certificate belongs to. */ subject?: CertificatePrincipal; /** * A hexadecimal identifier for the certificate. */ thumbprint?: CertificateThumbprint; } export type CertificateAuthorityBody = Buffer|Uint8Array|Blob|string; export type CertificateList = CertificateAuthorityBody[]; export type CertificatePrincipal = string; export interface CertificateSummary { /** * The entity that issued the certificate. */ issuer?: CertificatePrincipal; /** * The certificate is not valid after this date. */ notValidAfter?: Timestamp; /** * The certificate is not valid before this date. */ notValidBefore?: Timestamp; /** * The entity the certificate belongs to. */ subject?: CertificatePrincipal; /** * A hexadecimal identifier for the certificate. */ thumbprint?: CertificateThumbprint; } export type CertificateSummaryList = CertificateSummary[]; export type CertificateThumbprint = string; export type CertificateThumbprintList = CertificateThumbprint[]; export type ClientToken = string; export interface CreateBrowserSettingsRequest { /** * Additional encryption context of the browser settings. */ additionalEncryptionContext?: EncryptionContextMap; /** * A JSON string containing Chrome Enterprise policies that will be applied to all streaming sessions. */ browserPolicy: BrowserPolicy; /** * A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token returns the result from the original successful request. If you do not specify a client token, one is automatically generated by the AWS SDK. */ clientToken?: ClientToken; /** * The custom managed key of the browser settings. */ customerManagedKey?: keyArn; /** * The tags to add to the browser settings resource. A tag is a key-value pair. */ tags?: TagList; } export interface CreateBrowserSettingsResponse { /** * The ARN of the browser settings. */ browserSettingsArn: ARN; } export interface CreateIdentityProviderRequest { /** * A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token returns the result from the original successful request. If you do not specify a client token, one is automatically generated by the AWS SDK. */ clientToken?: ClientToken; /** * The identity provider details. The following list describes the provider detail keys for each identity provider type. For Google and Login with Amazon: client_id client_secret authorize_scopes For Facebook: client_id client_secret authorize_scopes api_version For Sign in with Apple: client_id team_id key_id private_key authorize_scopes For OIDC providers: client_id client_secret attributes_request_method oidc_issuer authorize_scopes authorize_url if not available from discovery URL specified by oidc_issuer key token_url if not available from discovery URL specified by oidc_issuer key attributes_url if not available from discovery URL specified by oidc_issuer key jwks_uri if not available from discovery URL specified by oidc_issuer key For SAML providers: MetadataFile OR MetadataURL IDPSignout optional */ identityProviderDetails: IdentityProviderDetails; /** * The identity provider name. */ identityProviderName: IdentityProviderName; /** * The identity provider type. */ identityProviderType: IdentityProviderType; /** * The ARN of the web portal. */ portalArn: ARN; } export interface CreateIdentityProviderResponse { /** * The ARN of the identity provider. */ identityProviderArn: ARN; } export interface CreateNetworkSettingsRequest { /** * A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token returns the result from the original successful request. If you do not specify a client token, one is automatically generated by the AWS SDK. */ clientToken?: ClientToken; /** * One or more security groups used to control access from streaming instances to your VPC. */ securityGroupIds: SecurityGroupIdList; /** * The subnets in which network interfaces are created to connect streaming instances to your VPC. At least two of these subnets must be in different availability zones. */ subnetIds: SubnetIdList; /** * The tags to add to the network settings resource. A tag is a key-value pair. */ tags?: TagList; /** * The VPC that streaming instances will connect to. */ vpcId: VpcId; } export interface CreateNetworkSettingsResponse { /** * The ARN of the network settings. */ networkSettingsArn: ARN; } export interface CreatePortalRequest { /** * The additional encryption context of the portal. */ additionalEncryptionContext?: EncryptionContextMap; /** * A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token returns the result from the original successful request. If you do not specify a client token, one is automatically generated by the AWS SDK. */ clientToken?: ClientToken; /** * The customer managed key of the web portal. */ customerManagedKey?: keyArn; /** * The name of the web portal. This is not visible to users who log into the web portal. */ displayName?: DisplayName; /** * The tags to add to the web portal. A tag is a key-value pair. */ tags?: TagList; } export interface CreatePortalResponse { /** * The ARN of the web portal. */ portalArn: ARN; /** * The endpoint URL of the web portal that users access in order to start streaming sessions. */ portalEndpoint: PortalEndpoint; } export interface CreateTrustStoreRequest { /** * A list of CA certificates to be added to the trust store. */ certificateList: CertificateList; /** * A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token returns the result from the original successful request. If you do not specify a client token, one is automatically generated by the AWS SDK. */ clientToken?: ClientToken; /** * The tags to add to the trust store. A tag is a key-value pair. */ tags?: TagList; } export interface CreateTrustStoreResponse { /** * The ARN of the trust store. */ trustStoreArn: ARN; } export interface CreateUserSettingsRequest { /** * A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token returns the result from the original successful request. If you do not specify a client token, one is automatically generated by the AWS SDK. */ clientToken?: ClientToken; /** * Specifies whether the user can copy text from the streaming session to the local device. */ copyAllowed: EnabledType; /** * Specifies whether the user can download files from the streaming session to the local device. */ downloadAllowed: EnabledType; /** * Specifies whether the user can paste text from the local device to the streaming session. */ pasteAllowed: EnabledType; /** * Specifies whether the user can print to the local device. */ printAllowed: EnabledType; /** * The tags to add to the user settings resource. A tag is a key-value pair. */ tags?: TagList; /** * Specifies whether the user can upload files from the local device to the streaming session. */ uploadAllowed: EnabledType; } export interface CreateUserSettingsResponse { /** * The ARN of the user settings. */ userSettingsArn: ARN; } export interface DeleteBrowserSettingsRequest { /** * The ARN of the browser settings. */ browserSettingsArn: ARN; } export interface DeleteBrowserSettingsResponse { } export interface DeleteIdentityProviderRequest { /** * The ARN of the identity provider. */ identityProviderArn: ARN; } export interface DeleteIdentityProviderResponse { } export interface DeleteNetworkSettingsRequest { /** * The ARN of the network settings. */ networkSettingsArn: ARN; } export interface DeleteNetworkSettingsResponse { } export interface DeletePortalRequest { /** * The ARN of the web portal. */ portalArn: ARN; } export interface DeletePortalResponse { } export interface DeleteTrustStoreRequest { /** * The ARN of the trust store. */ trustStoreArn: ARN; } export interface DeleteTrustStoreResponse { } export interface DeleteUserSettingsRequest { /** * The ARN of the user settings. */ userSettingsArn: ARN; } export interface DeleteUserSettingsResponse { } export interface DisassociateBrowserSettingsRequest { /** * The ARN of the web portal. */ portalArn: ARN; } export interface DisassociateBrowserSettingsResponse { } export interface DisassociateNetworkSettingsRequest { /** * The ARN of the web portal. */ portalArn: ARN; } export interface DisassociateNetworkSettingsResponse { } export interface DisassociateTrustStoreRequest { /** * The ARN of the web portal. */ portalArn: ARN; } export interface DisassociateTrustStoreResponse { } export interface DisassociateUserSettingsRequest { /** * The ARN of the web portal. */ portalArn: ARN; } export interface DisassociateUserSettingsResponse { } export type DisplayName = string; export type EnabledType = "Disabled"|"Enabled"|string; export type EncryptionContextMap = {[key: string]: StringType}; export interface GetBrowserSettingsRequest { /** * The ARN of the browser settings. */ browserSettingsArn: ARN; } export interface GetBrowserSettingsResponse { /** * The browser settings. */ browserSettings?: BrowserSettings; } export interface GetIdentityProviderRequest { /** * The ARN of the identity provider. */ identityProviderArn: ARN; } export interface GetIdentityProviderResponse { /** * The identity provider. */ identityProvider?: IdentityProvider; } export interface GetNetworkSettingsRequest { /** * The ARN of the network settings. */ networkSettingsArn: ARN; } export interface GetNetworkSettingsResponse { /** * The network settings. */ networkSettings?: NetworkSettings; } export interface GetPortalRequest { /** * The ARN of the web portal. */ portalArn: ARN; } export interface GetPortalResponse { /** * The web portal. */ portal?: Portal; } export interface GetPortalServiceProviderMetadataRequest { /** * The ARN of the web portal. */ portalArn: ARN; } export interface GetPortalServiceProviderMetadataResponse { /** * The ARN of the web portal. */ portalArn: ARN; /** * The service provider SAML metadata. */ serviceProviderSamlMetadata?: SamlMetadata; } export interface GetTrustStoreCertificateRequest { /** * The thumbprint of the trust store certificate. */ thumbprint: CertificateThumbprint; /** * The ARN of the trust store certificate. */ trustStoreArn: ARN; } export interface GetTrustStoreCertificateResponse { /** * The certificate of the trust store certificate. */ certificate?: Certificate; /** * The ARN of the trust store certificate. */ trustStoreArn?: ARN; } export interface GetTrustStoreRequest { /** * The ARN of the trust store. */ trustStoreArn: ARN; } export interface GetTrustStoreResponse { /** * The trust store. */ trustStore?: TrustStore; } export interface GetUserSettingsRequest { /** * The ARN of the user settings. */ userSettingsArn: ARN; } export interface GetUserSettingsResponse { /** * The user settings. */ userSettings?: UserSettings; } export interface IdentityProvider { /** * The ARN of the identity provider. */ identityProviderArn: ARN; /** * The identity provider details. The following list describes the provider detail keys for each identity provider type. For Google and Login with Amazon: client_id client_secret authorize_scopes For Facebook: client_id client_secret authorize_scopes api_version For Sign in with Apple: client_id team_id key_id private_key authorize_scopes For OIDC providers: client_id client_secret attributes_request_method oidc_issuer authorize_scopes authorize_url if not available from discovery URL specified by oidc_issuer key token_url if not available from discovery URL specified by oidc_issuer key attributes_url if not available from discovery URL specified by oidc_issuer key jwks_uri if not available from discovery URL specified by oidc_issuer key For SAML providers: MetadataFile OR MetadataURL IDPSignout optional */ identityProviderDetails?: IdentityProviderDetails; /** * The identity provider name. */ identityProviderName?: IdentityProviderName; /** * The identity provider type. */ identityProviderType?: IdentityProviderType; } export type IdentityProviderDetails = {[key: string]: StringType}; export type IdentityProviderList = IdentityProviderSummary[]; export type IdentityProviderName = string; export interface IdentityProviderSummary { /** * The ARN of the identity provider. */ identityProviderArn?: ARN; /** * The identity provider name. */ identityProviderName?: IdentityProviderName; /** * The identity provider type. */ identityProviderType?: IdentityProviderType; } export type IdentityProviderType = "SAML"|"Facebook"|"Google"|"LoginWithAmazon"|"SignInWithApple"|"OIDC"|string; export interface ListBrowserSettingsRequest { /** * The maximum number of results to be included in the next page. */ maxResults?: MaxResults; /** * The pagination token used to retrieve the next page of results for this operation. */ nextToken?: PaginationToken; } export interface ListBrowserSettingsResponse { /** * The browser settings. */ browserSettings?: BrowserSettingsList; /** * The pagination token used to retrieve the next page of results for this operation. */ nextToken?: PaginationToken; } export interface ListIdentityProvidersRequest { /** * The maximum number of results to be included in the next page. */ maxResults?: MaxResults; /** * The pagination token used to retrieve the next page of results for this operation. */ nextToken?: PaginationToken; /** * The ARN of the web portal. */ portalArn: ARN; } export interface ListIdentityProvidersResponse { /** * The identity providers. */ identityProviders?: IdentityProviderList; /** * The pagination token used to retrieve the next page of results for this operation. */ nextToken?: PaginationToken; } export interface ListNetworkSettingsRequest { /** * The maximum number of results to be included in the next page. */ maxResults?: MaxResults; /** * The pagination token used to retrieve the next page of results for this operation. */ nextToken?: PaginationToken; } export interface ListNetworkSettingsResponse { /** * The network settings. */ networkSettings?: NetworkSettingsList; /** * The pagination token used to retrieve the next page of results for this operation. */ nextToken?: PaginationToken; } export interface ListPortalsRequest { /** * The maximum number of results to be included in the next page. */ maxResults?: MaxResults; /** * The pagination token used to retrieve the next page of results for this operation. */ nextToken?: PaginationToken; } export interface ListPortalsResponse { /** * The pagination token used to retrieve the next page of results for this operation. */ nextToken?: PaginationToken; /** * The portals in the list. */ portals?: PortalList; } export interface ListTagsForResourceRequest { /** * The ARN of the resource. */ resourceArn: ARN; } export interface ListTagsForResourceResponse { /** * The tags of the resource. */ tags?: TagList; } export interface ListTrustStoreCertificatesRequest { /** * The maximum number of results to be included in the next page. */ maxResults?: MaxResults; /** * The pagination token used to retrieve the next page of results for this operation. */ nextToken?: PaginationToken; /** * The ARN of the trust store */ trustStoreArn: ARN; } export interface ListTrustStoreCertificatesResponse { /** * The certificate list. */ certificateList?: CertificateSummaryList; /** * The pagination token used to retrieve the next page of results for this operation.&gt; */ nextToken?: PaginationToken; /** * The ARN of the trust store. */ trustStoreArn?: ARN; } export interface ListTrustStoresRequest { /** * The maximum number of results to be included in the next page. */ maxResults?: MaxResults; /** * The pagination token used to retrieve the next page of results for this operation. */ nextToken?: PaginationToken; } export interface ListTrustStoresResponse { /** * The pagination token used to retrieve the next page of results for this operation. */ nextToken?: PaginationToken; /** * The trust stores. */ trustStores?: TrustStoreSummaryList; } export interface ListUserSettingsRequest { /** * The maximum number of results to be included in the next page. */ maxResults?: MaxResults; /** * The pagination token used to retrieve the next page of results for this operation. */ nextToken?: PaginationToken; } export interface ListUserSettingsResponse { /** * The pagination token used to retrieve the next page of results for this operation. */ nextToken?: PaginationToken; /** * The user settings. */ userSettings?: UserSettingsList; } export type MaxResults = number; export interface NetworkSettings { /** * A list of web portal ARNs that this network settings is associated with. */ associatedPortalArns?: ArnList; /** * The ARN of the network settings. */ networkSettingsArn: ARN; /** * One or more security groups used to control access from streaming instances to your VPC. */ securityGroupIds?: SecurityGroupIdList; /** * The subnets in which network interfaces are created to connect streaming instances to your VPC. At least two of these subnets must be in different availability zones. */ subnetIds?: SubnetIdList; /** * The VPC that streaming instances will connect to. */ vpcId?: VpcId; } export type NetworkSettingsList = NetworkSettingsSummary[]; export interface NetworkSettingsSummary { /** * The ARN of the network settings. */ networkSettingsArn?: ARN; /** * The VPC ID of the network settings. */ vpcId?: VpcId; } export type PaginationToken = string; export interface Portal { /** * The ARN of the browser settings that is associated with this web portal. */ browserSettingsArn?: ARN; /** * The browser that users see when using a streaming session. */ browserType?: BrowserType; /** * The creation date of the web portal. */ creationDate?: Timestamp; /** * The name of the web portal. */ displayName?: DisplayName; /** * The ARN of the network settings that is associated with the web portal. */ networkSettingsArn?: ARN; /** * The ARN of the web portal. */ portalArn?: ARN; /** * The endpoint URL of the web portal that users access in order to start streaming sessions. */ portalEndpoint?: PortalEndpoint; /** * The status of the web portal. */ portalStatus?: PortalStatus; /** * The renderer that is used in streaming sessions. */ rendererType?: RendererType; /** * A message that explains why the web portal is in its current status. */ statusReason?: StatusReason; /** * The ARN of the trust store that is associated with the web portal. */ trustStoreArn?: ARN; /** * The ARN of the trust store that is associated with the web portal. */ userSettingsArn?: ARN; } export type PortalEndpoint = string; export type PortalList = PortalSummary[]; export type PortalStatus = "Incomplete"|"Pending"|"Active"|string; export interface PortalSummary { /** * The ARN of the browser settings that is associated with the web portal. */ browserSettingsArn?: ARN; /** * The browser type of the web portal. */ browserType?: BrowserType; /** * The creation date of the web portal. */ creationDate?: Timestamp; /** * The name of the web portal. */ displayName?: DisplayName; /** * The ARN of the network settings that is associated with the web portal. */ networkSettingsArn?: ARN; /** * The ARN of the web portal. */ portalArn?: ARN; /** * The endpoint URL of the web portal that users access in order to start streaming sessions. */ portalEndpoint?: PortalEndpoint; /** * The status of the web portal. */ portalStatus?: PortalStatus; /** * The renderer that is used in streaming sessions. */ rendererType?: RendererType; /** * The ARN of the trust that is associated with this web portal. */ trustStoreArn?: ARN; /** * The ARN of the user settings that is associated with the web portal. */ userSettingsArn?: ARN; } export type RendererType = "AppStream"|string; export type SamlMetadata = string; export type SecurityGroupId = string; export type SecurityGroupIdList = SecurityGroupId[]; export type StatusReason = string; export type StringType = string; export type SubnetId = string; export type SubnetIdList = SubnetId[]; export interface Tag { /** * The key of the tag. */ Key: TagKey; /** * The value of the tag */ Value: TagValue; } export type TagKey = string; export type TagKeyList = TagKey[]; export type TagList = Tag[]; export interface TagResourceRequest { /** * A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token returns the result from the original successful request. If you do not specify a client token, one is automatically generated by the AWS SDK. */ clientToken?: ClientToken; /** * The ARN of the resource. */ resourceArn: ARN; /** * The tags of the resource. */ tags: TagList; } export interface TagResourceResponse { } export type TagValue = string; export type Timestamp = Date; export interface TrustStore { /** * A list of web portal ARNs that this trust store is associated with. */ associatedPortalArns?: ArnList; /** * The ARN of the trust store. */ trustStoreArn?: ARN; } export interface TrustStoreSummary { /** * The ARN of the trust store. */ trustStoreArn?: ARN; } export type TrustStoreSummaryList = TrustStoreSummary[]; export interface UntagResourceRequest { /** * The ARN of the resource. */ resourceArn: ARN; /** * The list of tag keys to remove from the resource. */ tagKeys: TagKeyList; } export interface UntagResourceResponse { } export interface UpdateBrowserSettingsRequest { /** * A JSON string containing Chrome Enterprise policies that will be applied to all streaming sessions. */ browserPolicy?: BrowserPolicy; /** * The ARN of the browser settings. */ browserSettingsArn: ARN; /** * A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token return the result from the original successful request. If you do not specify a client token, one is automatically generated by the AWS SDK. */ clientToken?: ClientToken; } export interface UpdateBrowserSettingsResponse { /** * The browser settings. */ browserSettings: BrowserSettings; } export interface UpdateIdentityProviderRequest { /** * A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token return the result from the original successful request. If you do not specify a client token, one is automatically generated by the AWS SDK. */ clientToken?: ClientToken; /** * The ARN of the identity provider. */ identityProviderArn: ARN; /** * The details of the identity provider. */ identityProviderDetails?: IdentityProviderDetails; /** * The name of the identity provider. */ identityProviderName?: IdentityProviderName; /** * The type of the identity provider. */ identityProviderType?: IdentityProviderType; } export interface UpdateIdentityProviderResponse { /** * The identity provider. */ identityProvider: IdentityProvider; } export interface UpdateNetworkSettingsRequest { /** * A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token return the result from the original successful request. If you do not specify a client token, one is automatically generated by the AWS SDK. */ clientToken?: ClientToken; /** * The ARN of the network settings. */ networkSettingsArn: ARN; /** * One or more security groups used to control access from streaming instances to your VPC. */ securityGroupIds?: SecurityGroupIdList; /** * The subnets in which network interfaces are created to connect streaming instances to your VPC. At least two of these subnets must be in different availability zones. */ subnetIds?: SubnetIdList; /** * The VPC that streaming instances will connect to. */ vpcId?: VpcId; } export interface UpdateNetworkSettingsResponse { /** * The network settings. */ networkSettings: NetworkSettings; } export interface UpdatePortalRequest { /** * The name of the web portal. This is not visible to users who log into the web portal. */ displayName?: DisplayName; /** * The ARN of the web portal. */ portalArn: ARN; } export interface UpdatePortalResponse { /** * The web portal. */ portal?: Portal; } export interface UpdateTrustStoreRequest { /** * A list of CA certificates to add to the trust store. */ certificatesToAdd?: CertificateList; /** * A list of CA certificates to delete from a trust store. */ certificatesToDelete?: CertificateThumbprintList; /** * A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token return the result from the original successful request. If you do not specify a client token, one is automatically generated by the AWS SDK. */ clientToken?: ClientToken; /** * The ARN of the trust store. */ trustStoreArn: ARN; } export interface UpdateTrustStoreResponse { /** * The ARN of the trust store. */ trustStoreArn: ARN; } export interface UpdateUserSettingsRequest { /** * A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Idempotency ensures that an API request completes only once. With an idempotent request, if the original request completes successfully, subsequent retries with the same client token return the result from the original successful request. If you do not specify a client token, one is automatically generated by the AWS SDK. */ clientToken?: ClientToken; /** * Specifies whether the user can copy text from the streaming session to the local device. */ copyAllowed?: EnabledType; /** * Specifies whether the user can download files from the streaming session to the local device. */ downloadAllowed?: EnabledType; /** * Specifies whether the user can paste text from the local device to the streaming session. */ pasteAllowed?: EnabledType; /** * Specifies whether the user can print to the local device. */ printAllowed?: EnabledType; /** * Specifies whether the user can upload files from the local device to the streaming session. */ uploadAllowed?: EnabledType; /** * The ARN of the user settings. */ userSettingsArn: ARN; } export interface UpdateUserSettingsResponse { /** * The user settings. */ userSettings: UserSettings; } export interface UserSettings { /** * A list of web portal ARNs that this user settings is associated with. */ associatedPortalArns?: ArnList; /** * Specifies whether the user can copy text from the streaming session to the local device. */ copyAllowed?: EnabledType; /** * Specifies whether the user can download files from the streaming session to the local device. */ downloadAllowed?: EnabledType; /** * Specifies whether the user can paste text from the local device to the streaming session. */ pasteAllowed?: EnabledType; /** * Specifies whether the user can print to the local device. */ printAllowed?: EnabledType; /** * Specifies whether the user can upload files from the local device to the streaming session. */ uploadAllowed?: EnabledType; /** * The ARN of the user settings. */ userSettingsArn: ARN; } export type UserSettingsList = UserSettingsSummary[]; export interface UserSettingsSummary { /** * Specifies whether the user can copy text from the streaming session to the local device. */ copyAllowed?: EnabledType; /** * Specifies whether the user can download files from the streaming session to the local device. */ downloadAllowed?: EnabledType; /** * Specifies whether the user can paste text from the local device to the streaming session. */ pasteAllowed?: EnabledType; /** * Specifies whether the user can print to the local device. */ printAllowed?: EnabledType; /** * Specifies whether the user can upload files from the local device to the streaming session. */ uploadAllowed?: EnabledType; /** * The ARN of the user settings. */ userSettingsArn?: ARN; } export type VpcId = string; export type keyArn = 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 = "2020-07-08"|"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 WorkSpacesWeb client. */ export import Types = WorkSpacesWeb; } export = WorkSpacesWeb;
the_stack
import * as Slider from 'rc-slider'; import * as React from 'react'; import * as CSSModules from 'react-css-modules'; import * as DateTimePicker from 'react-datetime'; import * as TetherComponent from 'react-tether'; import {DateTime} from 'vega-lite/build/src/datetime'; import {FieldRangePredicate} from 'vega-lite/build/src/predicate'; import {TimeUnit} from 'vega-lite/build/src/timeunit'; import {FILTER_MODIFY_EXTENT, FILTER_MODIFY_MAX_BOUND, FILTER_MODIFY_MIN_BOUND, FilterAction} from '../../actions'; import {ActionHandler} from '../../actions/redux-action'; import {convertToDateTimeObject, convertToTimestamp} from '../../models/shelf/filter'; import * as styles from './range-filter-shelf.scss'; export interface RangeFilterShelfProps extends ActionHandler<FilterAction> { domain: number[] | DateTime[]; index: number; filter: FieldRangePredicate; renderDateTimePicker: boolean; } export interface RangeFilterShelfState { minDateTimePickerOpen: boolean; maxDateTimePickerOpen: boolean; } export class RangeFilterShelfBase extends React.PureComponent<RangeFilterShelfProps, RangeFilterShelfState> { constructor(props: RangeFilterShelfProps) { super(props); this.state = ({ minDateTimePickerOpen: false, maxDateTimePickerOpen: false }); this.filterModifyExtent = this.filterModifyExtent.bind(this); this.filterModifyMaxBound = this.filterModifyMaxBound.bind(this); this.filterModifyMinBound = this.filterModifyMinBound.bind(this); this.toggleMinDateTimePicker = this.toggleMinDateTimePicker.bind(this); this.toggleMaxDateTimePicker = this.toggleMaxDateTimePicker.bind(this); } public render() { const {filter, domain, renderDateTimePicker} = this.props; const createSliderWithTooltip = Slider.createSliderWithTooltip; const Range = createSliderWithTooltip(Slider.Range); let minInput, maxInput, currMin, currMax, lowerBound, upperBound; if (renderDateTimePicker) { // when render date time picker, it must be an temporal filter, thus the range must be DateTime[]. minInput = this.renderDateTimePicker(new Date(convertToTimestamp(filter.range[0] as DateTime)), 'min'); maxInput = this.renderDateTimePicker(new Date(convertToTimestamp(filter.range[1] as DateTime)), 'max'); currMin = convertToTimestamp(filter.range[0] as DateTime); currMax = convertToTimestamp(filter.range[1] as DateTime); lowerBound = Math.floor(convertToTimestamp(domain[0] as DateTime)); upperBound = Math.ceil(convertToTimestamp(domain[1] as DateTime)); } else { minInput = this.renderNumberInput('min'); maxInput = this.renderNumberInput('max'); currMin = filter.range[0]; currMax = filter.range[1]; // Math.floor/ceil because the slider requires the the difference between max and min // must be a multiple of step (which is 1 by default) lowerBound = Math.floor(Number(domain[0])); upperBound = Math.ceil(Number(domain[1])); } return ( <div styleName='range-filter-pane'> <div> <div styleName='bound'> {minInput} </div> <div styleName='bound'> {maxInput} </div> </div> <Range allowCross={false} defaultValue={[currMin, currMax]} min={lowerBound} max={upperBound} onAfterChange={this.filterModifyExtent.bind(this)} tipFormatter={this.getFormat(renderDateTimePicker, filter.timeUnit)} step={this.getStep(filter.timeUnit)} /> </div> ); } protected filterModifyExtent(input: number[]) { // filterModifyExtent is only triggered by slider, so input must be number[]. let range: DateTime[] | number[]; if (this.props.renderDateTimePicker) { range = [convertToDateTimeObject(input[0]), convertToDateTimeObject(input[1])]; } else { range = input; } if (range[0] > range[1]) { window.alert('Invalid bound'); return; } const {handleAction, index} = this.props; handleAction({ type: FILTER_MODIFY_EXTENT, payload: { index, range } }); } protected filterModifyMaxBound(e: any) { let maxBound; if (e.hasOwnProperty('target')) { maxBound = Number(e.target.value); } else { maxBound = e; } const {handleAction, index} = this.props; if (this.props.renderDateTimePicker) { maxBound = convertToDateTimeObject(maxBound); } const minBound = this.props.filter.range[0]; if (maxBound < minBound) { window.alert('Maximum bound cannot be smaller than minimum bound'); return; } handleAction({ type: FILTER_MODIFY_MAX_BOUND, payload: { index, maxBound } }); } protected filterModifyMinBound(e: any) { let minBound; if (e.hasOwnProperty('target')) { minBound = Number(e.target.value); } else { minBound = e; } const {handleAction, index, renderDateTimePicker} = this.props; if (renderDateTimePicker) { minBound = convertToDateTimeObject(minBound); } const range = this.props.filter.range; const maxBound = range[1]; if (minBound > maxBound) { window.alert('Minimum bound cannot be greater than maximum bound'); return; } handleAction({ type: FILTER_MODIFY_MIN_BOUND, payload: { index, minBound } }); } private renderNumberInput(bound: 'min' | 'max') { const {filter} = this.props; let onChangeAction, value; if (bound === 'min') { onChangeAction = this.filterModifyMinBound; value = filter.range[0]; } else if (bound === 'max') { onChangeAction = this.filterModifyMaxBound; value = filter.range[1]; } return ( <div> {bound}: <a onClick={this.focusInput.bind(this, `${filter.field}_${bound}`)}><i className="fa fa-pencil"/></a> <input id={`${filter.field}_${bound}`} type='number' value={value.toString()} onChange={onChangeAction} /> </div> ); } private renderDateTimePicker(date: Date, bound: 'min' | 'max') { let onChangeAction, dateTimePickerOpen, dataTimePickerOpenAction; if (bound === 'min') { onChangeAction = this.filterModifyMinBound; dateTimePickerOpen = this.state.minDateTimePickerOpen; dataTimePickerOpenAction = this.toggleMinDateTimePicker; } else if (bound === 'max') { onChangeAction = this.filterModifyMaxBound; dateTimePickerOpen = this.state.maxDateTimePickerOpen; dataTimePickerOpenAction = this.toggleMaxDateTimePicker; } return ( <div> <TetherComponent attachment='bottom center' > <div styleName='bound'> {bound}: <a onClick={dataTimePickerOpenAction}><i className="fa fa-pencil"/></a> {date.toString()} </div> {dateTimePickerOpen && <div styleName='date-time-picker-wrapper'> <DateTimePicker defaultValue={date} timeFormat={this.showTime(this.props.filter.timeUnit)} open={false} onChange={onChangeAction} disableOnClickOutside={false} /> </div> } </TetherComponent> </div> ); } private focusInput(id: string) { document.getElementById(id).focus(); } private toggleMinDateTimePicker() { this.setState({ minDateTimePickerOpen: !this.state.minDateTimePickerOpen }); } private toggleMaxDateTimePicker() { this.setState({ maxDateTimePickerOpen: !this.state.maxDateTimePickerOpen }); } /** * returns whether to show the time component in the date time picker */ private showTime(timeUnit: TimeUnit): boolean { switch (timeUnit) { case undefined: case TimeUnit.YEAR: case TimeUnit.MONTH: case TimeUnit.DAY: case TimeUnit.DATE: case TimeUnit.HOURS: case TimeUnit.MINUTES: case TimeUnit.SECONDS: case TimeUnit.MILLISECONDS: return true; case TimeUnit.YEARMONTHDATE: // hide time component as we do not care about it return false; default: throw new Error(timeUnit + ' is not supported'); } } /** * Returns a function to format how the number is displayed in range filter for * the given time unit. */ private getFormat(renderDateTime: boolean, timeUnit: TimeUnit) { if (!timeUnit) { if (renderDateTime) { // temporal filter without time unit // TODO: https://github.com/vega/voyager/issues/443: use the time formatter Vega derives from D3 return (value: number) => { return new Date(value).toString(); }; } else { // quantitative filter return; } } switch (timeUnit) { case TimeUnit.YEAR: case TimeUnit.MONTH: case TimeUnit.DAY: case TimeUnit.DATE: case TimeUnit.HOURS: case TimeUnit.MINUTES: case TimeUnit.SECONDS: case TimeUnit.MILLISECONDS: // do not need to format these time units. return; case TimeUnit.YEARMONTHDATE: // TODO: https://github.com/vega/voyager/issues/443: use the time formatter Vega derives from D3 return (value: number) => { return new Date(value).toString(); }; default: throw new Error(timeUnit + ' is not supported'); } } /** * Returns the range filter step for the given time unit. */ private getStep(timeUnit: TimeUnit) { switch (timeUnit) { case undefined: case TimeUnit.YEAR: case TimeUnit.MONTH: case TimeUnit.DAY: case TimeUnit.DATE: case TimeUnit.HOURS: case TimeUnit.MINUTES: case TimeUnit.SECONDS: case TimeUnit.MILLISECONDS: return 1; case TimeUnit.YEARMONTHDATE: return 24 * 60 * 60 * 1000; // step is one day in timestamp default: throw new Error(timeUnit + ' is not supported'); } } } export const RangeFilterShelf = CSSModules(RangeFilterShelfBase, styles);
the_stack
import { $$log, $$hex, assert } from "../utils/debug"; import { copyRange } from "../utils/arrays"; import { Game } from "../types"; import { romhandler } from "../romhandler"; import { scenes } from "./scenes"; import { getRegSetAddress, getRegSetUpperAndLower } from "../utils/MIPS"; import { S2 } from "../audio/S2"; import { MBF0 } from "../audio/MBF0"; import { SBF0 } from "../audio/SBF0"; import { T3 } from "../audio/T3"; import { FXD0 } from "../audio/FXD0"; import { isDebug } from "../debug"; import { makeDivisibleBy } from "../utils/number"; interface IOffsetInfo { upper: number; lower: number; ovl?: number; } interface IOffsetObj { type: "S2" | "T3" | "MBF0" | "SBF0" | "FXD0" | "Pointer"; byteLength?: number; offsets: IOffsetInfo[]; } let _bufferCache: (ArrayBuffer | null)[] | null; let _parsedCache: (S2 | T3 | MBF0 | SBF0 | FXD0 | null)[] | null; type AudioOffsetInfo = { [game in Game]: readonly IOffsetObj[] }; const _audioOffsets: AudioOffsetInfo = { [Game.MP1_USA]: [ // Length 0x7B3DF0 // 15396A0 { type: "S2", // byteLength: 0x23F520, offsets: [ { upper: 0x00061746, lower: 0x0006174A }, { ovl: 0x6E, upper: 0xE62, lower: 0xE66 }, // ROM: 0x2DA3D2 ] }, // 1778BC0 { type: "S2", // byteLength: 0xB9F20, offsets: [ { upper: 0x0001AF2A, lower: 0x0001AF2E }, { upper: 0x0006174E, lower: 0x00061752 }, { upper: 0x0006177E, lower: 0x00061782 }, { ovl: 0x6E, upper: 0xE6A, lower: 0xE6E }, // ROM: 0x2DA3DA { ovl: 0x6E, upper: 0xE92, lower: 0xE96 }, // ROM: 0x2DA402 ] }, // 1832AE0 { type: "T3", byteLength: 0x385980, offsets: [ { upper: 0x0001AF32, lower: 0x0001AF36 }, { upper: 0x0006172E, lower: 0x00061732 }, { upper: 0x00061786, lower: 0x0006178A }, { ovl: 0x6E, upper: 0xE4E, lower: 0xE52 }, // ROM: 0x2DA3BE { ovl: 0x6E, upper: 0xE9A, lower: 0xE9E }, // ROM: 0x2DA40A ] }, // 1BB8460 { type: "T3", byteLength: 0x134800, offsets: [ { upper: 0x0001AF0E, lower: 0x0001AF12 }, { upper: 0x00061762, lower: 0x00061766 }, { ovl: 0x6E, upper: 0xE7A, lower: 0xE7E }, // ROM: 0x2DA3EA ] }, // 1CECC60 { type: "FXD0", byteLength: 0x830, offsets: [ { upper: 0x0001AF5A, lower: 0x0001AF5E }, ] }, // 1CED490, 0xffffffffs EOF { type: "Pointer", byteLength: 0, offsets: [ { upper: 0x0001AF66, lower: 0x0001AF6A }, ] }, ], [Game.MP1_JPN]: [ // Length ? ], [Game.MP1_PAL]: [ // Length ? ], [Game.MP2_USA]: [ // Length 0x6DAB50 // 0x1750450 { type: "MBF0", // byteLength: 0x1B9C40, offsets: [ { upper: 0x0001D342, lower: 0x0001D346 }, { upper: 0x0007A9EE, lower: 0x0007A9F2 }, { upper: 0x0007AA12, lower: 0x0007AA16 }, ] }, // 0x190A090 { type: "SBF0", byteLength: 0x3B5380, offsets: [ { upper: 0x0007A9FA, lower: 0x0007A9FE }, ] }, // 0x1CBF410 { type: "SBF0", byteLength: 0x16B150, offsets: [ { upper: 0x0001D34E, lower: 0x0001D352 }, { upper: 0x0007AA1E, lower: 0x0007AA22 }, ] }, // 0x1E2A560 { type: "FXD0", byteLength: 0xA40, offsets: [ { upper: 0x0001D382, lower: 0x0001D386 }, ] }, ], [Game.MP2_JPN]: [ // Length ? ], [Game.MP2_PAL]: [ // Length ? ], [Game.MP3_USA]: [ // Length 0x67be40 // 0x1881C40 { type: "MBF0", // byteLength: 0x1D4C30, offsets: [ { upper: 0x0000F26A, lower: 0x0000F26E }, { upper: 0x0004BEF2, lower: 0x0004BEF6 }, ] }, // 0x1A56870 { type: "SBF0", byteLength: 0x4A67D0, offsets: [ { upper: 0x0000F276, lower: 0x0000F27A }, { upper: 0x0004BEFE, lower: 0x0004BF02 }, ] }, // 0x1EFD040 { type: "FXD0", byteLength: 0xA40, offsets: [ { upper: 0x0000F29E, lower: 0x0000F2A2 }, ] }, // E0F 0x1EFDA80 ], [Game.MP3_JPN]: [ // Length ? ], [Game.MP3_PAL]: [ // Length ? ], } export const audio = { getROMOffset(subsection = 0) { const infos = this.getPatchInfo(); if (!infos || !infos.length) return null; let patchInfo = infos[subsection]; if (!patchInfo) return null; let romPatchInfo = patchInfo.offsets[0]; let upperReadOffset = romPatchInfo.upper; let lowerReadOffset = romPatchInfo.lower; let upper, lower; if (typeof romPatchInfo.ovl === "number") { const sceneView = scenes.getDataView(romPatchInfo.ovl); upper = sceneView.getUint16(upperReadOffset); lower = sceneView.getUint16(lowerReadOffset); } else { const romView = romhandler.getDataView(); upper = romView.getUint16(upperReadOffset); lower = romView.getUint16(lowerReadOffset); } const offset = getRegSetAddress(upper, lower); $$log(`Audio.getROMOffset -> ${$$hex(offset)}`); if (isDebug()) { // Assert that the rest of the patch offsets are valid. patchInfo.offsets.forEach((offsetInfo, oIndex) => { let anotherUpperReadOffset = offsetInfo.upper; let anotherLowerReadOffset = offsetInfo.lower; let anotherUpper, anotherLower; if (typeof offsetInfo.ovl === "number") { const sceneView = scenes.getDataView(offsetInfo.ovl); anotherUpper = sceneView.getUint16(anotherUpperReadOffset); anotherLower = sceneView.getUint16(anotherLowerReadOffset); } else { const romView = romhandler.getDataView(); anotherUpper = romView.getUint16(anotherUpperReadOffset); anotherLower = romView.getUint16(anotherLowerReadOffset); } const anotherOffset = getRegSetAddress(anotherUpper, anotherLower); if (anotherOffset !== offset) throw new Error(`AudioFS.getROMOffset patch offset ${subsection}/${oIndex} seems wrong: offset: ${$$hex(offset)} vs ${$$hex(anotherOffset)} reading upper: ${$$hex(anotherUpperReadOffset)}, lower: ${$$hex(anotherLowerReadOffset)}`); }); } return offset; }, setROMOffset(newOffset: number, outBuffer: ArrayBuffer) { $$log(`Audio.setROMOffset(${$$hex(newOffset)})`); let infos = this.getPatchInfo(); let currentOffset = newOffset; for (let i = 0; i < infos.length; i++) { const info = infos[i]; const [upper, lower] = getRegSetUpperAndLower(currentOffset); for (let j = 0; j < info.offsets.length; j++) { const patchOffset = info.offsets[j]; let patchROMUpper = patchOffset.upper; let patchROMLower = patchOffset.lower; if (typeof patchOffset.ovl === "number") { const sceneView = scenes.getDataView(patchOffset.ovl); sceneView.setUint16(patchROMUpper, upper); sceneView.setUint16(patchROMLower, lower); } else { const romView = new DataView(outBuffer); romView.setUint16(patchROMUpper, upper); romView.setUint16(patchROMLower, lower); } } switch (info.type) { case "T3": case "SBF0": case "FXD0": assert(typeof info.byteLength === "number"); assert(info.byteLength % 16 === 0); currentOffset += info.byteLength; break; case "S2": assert(!!_parsedCache![i]); const s2 = _parsedCache![i] as S2; currentOffset += s2.getByteLength(); break; case "MBF0": assert(!!_parsedCache![i]); const mbf0 = _parsedCache![i] as MBF0; currentOffset += mbf0.getByteLength(); break; case "Pointer": break; default: throw new Error("Unhandled audio subsection type: " + info.type); } } }, getPatchInfo() { return _audioOffsets[romhandler.getROMGame()!]; }, read(index: number) { throw new Error("audio.read not implemented"); }, write(index: number, value: any) { throw new Error("audio.write not implemented"); }, getSequenceTableCount(): number { let count = 0; for (let i = 0; i < _parsedCache!.length; i++) { const cacheEntry = _parsedCache![i]; if (cacheEntry && "midis" in cacheEntry) count++; } return count; }, getSequenceTable(index: number): S2 | MBF0 | null { if (!_parsedCache) return null; let curIndex = -1; for (let i = 0; i < _parsedCache.length; i++) { const cacheEntry = _parsedCache[i]; if (cacheEntry && "midis" in cacheEntry) { curIndex++; if (curIndex === index) { return cacheEntry; } } } return null; }, getSoundTableCount(): number { let count = 0; for (let i = 0; i < _parsedCache!.length; i++) { const cacheEntry = _parsedCache![i]; if (cacheEntry && "sounds" in cacheEntry) count++; } return count; }, getSoundTable(index: number): T3 | SBF0 | null { if (!_parsedCache) return null; let curIndex = -1; for (let i = 0; i < _parsedCache.length; i++) { const cacheEntry = _parsedCache[i]; if (cacheEntry && "sounds" in cacheEntry) { curIndex++; if (curIndex === index) { return cacheEntry; } } } return null; }, clearCache(): void { _bufferCache = null; _parsedCache = null; }, extract(): void { const buffer = romhandler.getROMBuffer()!; let offset = this.getROMOffset(); if (offset === null) return; const infos = this.getPatchInfo(); _bufferCache = new Array(infos.length); _parsedCache = new Array(infos.length); for (let i = 0; i < infos.length; i++) { const info = infos[i]; switch (info.type) { case "S2": const s2Offset = this.getROMOffset(i)!; const s2 = _parsedCache[i] = new S2(romhandler.getDataView(s2Offset)); _bufferCache[i] = buffer.slice(s2Offset, s2Offset + s2.getByteLength()); break; case "T3": assert(typeof info.byteLength === "number"); const t3Offset = this.getROMOffset(i)!; _bufferCache[i] = buffer.slice(t3Offset, t3Offset + info.byteLength); _parsedCache[i] = new T3(romhandler.getDataView(t3Offset)); break; case "MBF0": const mbf0Offset = this.getROMOffset(i)!; const mbf0 = _parsedCache[i] = new MBF0(romhandler.getDataView(mbf0Offset)); _bufferCache[i] = buffer.slice(mbf0Offset, mbf0Offset + mbf0.getByteLength()); break; case "SBF0": assert(typeof info.byteLength === "number"); const sbf0Offset = this.getROMOffset(i)!; _bufferCache[i] = buffer.slice(sbf0Offset, sbf0Offset + info.byteLength); _parsedCache[i] = new SBF0(romhandler.getDataView(sbf0Offset)); break; case "FXD0": assert(typeof info.byteLength === "number"); const fxd0Offset = this.getROMOffset(i)!; _bufferCache[i] = buffer.slice(fxd0Offset, fxd0Offset + info.byteLength); _parsedCache[i] = new FXD0(romhandler.getDataView(fxd0Offset)); break; case "Pointer": _bufferCache[i] = _parsedCache[i] = null; break; default: throw new Error("Unhandled audio subsection type: " + info.type); } } // Finds audio offsets relative to overlay binaries // const infos = getPatchInfo(); // const sceneCount = scenes.count(); // for (let i = 0; i < infos.length; i++) { // const info = infos[i]; // info.offsets.forEach((oft) => { // let found = false; // for (let j = 0; j < sceneCount; j++) { // const info = scenes.getInfo(j); // if (oft.upper > info.rom_start && oft.upper < info.rom_end) { // console.log(`Found: { ovl: ${$$hex(j)}, upper: ${$$hex(oft.upper - info.rom_start)}, lower: ${$$hex(oft.lower - info.rom_start)} }, // ROM: ${$$hex(oft.upper)}`) // found = true; // } // } // if (!found) { // console.log(`Didn't find: { upper: ${$$hex(oft.upper)}, lower: ${$$hex(oft.lower)} }`); // } // }); // } }, extractAsync(): Promise<void> { return new Promise((resolve, reject) => { this.extract(); resolve(); }); }, pack(buffer: ArrayBuffer, offset: number = 0): number { const infos = this.getPatchInfo(); if (!infos || !infos.length || !_bufferCache) { throw new Error("Unable to write audio section."); } let currentOffset = offset; for (let i = 0; i < infos.length; i++) { const info = infos[i]; switch (info.type) { case "T3": case "SBF0": case "FXD0": assert(typeof info.byteLength === "number"); copyRange(buffer, _bufferCache[i]!, currentOffset, 0, _bufferCache[i]!.byteLength); currentOffset += info.byteLength; break; case "S2": const s2 = _parsedCache![i] as S2; currentOffset += s2.pack(buffer, currentOffset); currentOffset = makeDivisibleBy(currentOffset, 16); break; case "MBF0": const mbf0 = _parsedCache![i] as MBF0; currentOffset += mbf0.pack(buffer, currentOffset); currentOffset = makeDivisibleBy(currentOffset, 16); break; case "Pointer": break; default: throw new Error("Unhandled audio subsection type: " + info.type); } } const byteLengthWritten = currentOffset - offset; assert(byteLengthWritten % 16 === 0); return byteLengthWritten; }, // Gets the full byte length of the audio section of the ROM. getByteLength() { const infos = this.getPatchInfo(); if (!infos || !infos.length) { throw new Error("Unable to determine audio section length."); } let byteLength = 0; for (let i = 0; i < infos.length; i++) { const info = infos[i]; switch (info.type) { case "T3": case "SBF0": case "FXD0": assert(typeof info.byteLength === "number"); byteLength += info.byteLength; break; case "S2": const s2 = _parsedCache![i] as S2; byteLength += s2.getByteLength(); break; case "MBF0": const mbf0 = _parsedCache![i] as MBF0; byteLength += mbf0.getByteLength(); break; case "Pointer": break; default: throw new Error("Unhandled audio subsection type: " + info.type); } } return byteLength; } };
the_stack
import { Bundle, Messages } from '../i18n/i18n'; import { Destroyable } from '../core/Destroyable'; import { Evented, EventType, EventObject } from '../core/Evented'; import Map from '../shim/Map'; import WeakMap from '../shim/WeakMap'; import { RegistryHandler } from './RegistryHandler'; /** * Generic constructor type */ export type Constructor<T> = new (...args: any[]) => T; /** * Typed target event */ export interface TypedTargetEvent<T extends EventTarget, Y extends EventType = EventType> extends EventObject<Y> { target: T; } /* These are the event handlers. */ export type EventHandlerResult = boolean | void; export interface EventHandler { (event?: Event): EventHandlerResult; } export interface FocusEventHandler { (event?: FocusEvent): EventHandlerResult; } export interface KeyboardEventHandler { (event?: KeyboardEvent): EventHandlerResult; } export interface MouseEventHandler { (event?: MouseEvent): EventHandlerResult; } /** * Cannot extend the global due to TS error: `All declarations of 'target' must have identical modifiers.` */ export interface DojoEvent<T extends EventTarget = EventTarget> extends Event { target: T; } declare global { interface MouseEvent<T extends EventTarget = EventTarget> { target: T; } interface PointerEvent<T extends EventTarget = EventTarget> { target: T; } interface TouchEvent<T extends EventTarget = EventTarget> { target: T; } interface KeyboardEvent<T extends EventTarget = EventTarget> { target: T; } interface FocusEvent<T extends EventTarget = EventTarget> { target: T; } interface UIEvent<T extends EventTarget = EventTarget> { target: T; } interface WheelEvent<T extends EventTarget = EventTarget> { target: T; } } export type BlurEventHandler = FocusEventHandler; export type ChangeEventHandler = EventHandler; export type ClickEventHandler = MouseEventHandler; export type DoubleClickEventHandler = MouseEventHandler; export type InputEventHandler = EventHandler; export type KeyDownEventHandler = KeyboardEventHandler; export type KeyPressEventHandler = KeyboardEventHandler; export type KeyUpEventHandler = KeyboardEventHandler; export type LoadEventHandler = EventHandler; export type MouseDownEventHandler = MouseEventHandler; export type MouseEnterEventHandler = MouseEventHandler; export type MouseLeaveEventHandler = MouseEventHandler; export type MouseMoveEventHandler = MouseEventHandler; export type MouseOutEventHandler = MouseEventHandler; export type MouseOverEventHandler = MouseEventHandler; export type MouseUpEventHandler = MouseEventHandler; export type MouseWheelEventHandler = (event?: MouseWheelEvent | WheelEvent) => EventHandlerResult; export type ScrollEventHandler = (event?: UIEvent) => EventHandlerResult; export type SubmitEventHandler = EventHandler; export interface TransitionStrategy { enter(element: Element, enterAnimation: string, enterAnimationActive?: SupportedClassName): void; exit(element: Element, exitAnimation: string, exitAnimationActive?: SupportedClassName): void; } export interface ProjectorOptions { readonly transitions?: TransitionStrategy; styleApplyer?(domNode: HTMLElement, styleName: string, value: string): void; } export interface ProjectionOptions extends ProjectorOptions { namespace?: string; merge: boolean; sync: boolean; mergeElement?: Element; rootNode: Element; depth: number; projectorInstance: DefaultWidgetBaseInterface; } export interface Projection { readonly domNode: Element; } export type SupportedClassName = string | null | undefined | boolean; export type ClassNames = { [key: string]: string; }; export interface Theme { [key: string]: { [key: string]: string; }; } export interface Variant { root: string; } export interface NamedVariant { name: string; value: Variant; } export interface ThemeWithVariant { theme: ThemeWithVariants; variant: NamedVariant; } export interface ThemeWithVariants { theme: Theme; variants: { default: Variant; [key: string]: Variant; }; } export interface Classes { [widgetKey: string]: { [classKey: string]: SupportedClassName[]; }; } export type DeferredVirtualProperties = (inserted: boolean) => VNodeProperties; export type NodeOperationPredicate = () => boolean; export type DiffType = 'none' | 'dom' | 'vdom'; export interface On { [index: string]: <T extends Event>(event?: T) => void | undefined; } export interface DomOptions { node: Element | Text; props?: VNodeProperties; attrs?: { [index: string]: string | undefined }; on?: On; diffType?: DiffType; onAttach?: () => void; onUpdate?: () => void; onDetach?: () => void; } export interface VDomOptions { props?: VNodeProperties; attrs?: { [index: string]: string | undefined }; on?: On; } export interface AriaAttributes { /** Identifies the currently active element when DOM focus is on a composite widget, textbox, group, or application. */ 'aria-activedescendant'?: string; /** Indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the aria-relevant attribute. */ 'aria-atomic'?: 'false' | 'true'; /** * Indicates whether inputting text could trigger display of one or more predictions of the user's intended value for an input and specifies how predictions would be * presented if they are made. */ 'aria-autocomplete'?: 'none' | 'inline' | 'list' | 'both'; /** Indicates an element is being modified and that assistive technologies MAY want to wait until the modifications are complete before exposing them to the user. */ 'aria-busy'?: 'false' | 'true'; /** * Indicates the current "checked" state of checkboxes, radio buttons, and other widgets. * @see aria-pressed @see aria-selected. */ 'aria-checked'?: 'false' | 'mixed' | 'true'; /** * Defines the total number of columns in a table, grid, or treegrid. * @see aria-colindex. */ 'aria-colcount'?: string; /** * Defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid. * @see aria-colcount @see aria-colspan. */ 'aria-colindex'?: string; /** * Defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid. * @see aria-colindex @see aria-rowspan. */ 'aria-colspan'?: string; /** * Identifies the element (or elements) whose contents or presence are controlled by the current element. * @see aria-owns. */ 'aria-controls'?: string; /** Indicates the element that represents the current item within a container or set of related elements. */ 'aria-current'?: 'false' | 'true' | 'page' | 'step' | 'location' | 'date' | 'time'; /** * Identifies the element (or elements) that describes the object. * @see aria-labelledby */ 'aria-describedby'?: string; /** * Identifies the element that provides a detailed, extended description for the object. * @see aria-describedby. */ 'aria-details'?: string; /** * Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable. * @see aria-hidden @see aria-readonly. */ 'aria-disabled'?: 'false' | 'true'; /** * Indicates what functions can be performed when a dragged object is released on the drop target. * @deprecated in ARIA 1.1 */ 'aria-dropeffect'?: 'none' | 'copy' | 'execute' | 'link' | 'move' | 'popup'; /** * Identifies the element that provides an error message for the object. * @see aria-invalid @see aria-describedby. */ 'aria-errormessage'?: string; /** Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed. */ 'aria-expanded'?: 'false' | 'true'; /** * Identifies the next element (or elements) in an alternate reading order of content which, at the user's discretion, * allows assistive technology to override the general default of reading in document source order. */ 'aria-flowto'?: string; /** * Indicates an element's "grabbed" state in a drag-and-drop operation. * @deprecated in ARIA 1.1 */ 'aria-grabbed'?: 'false' | 'true'; /** Indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element. */ 'aria-haspopup'?: 'false' | 'true' | 'menu' | 'listbox' | 'tree' | 'grid' | 'dialog'; /** * Indicates whether the element is exposed to an accessibility API. * @see aria-disabled. */ 'aria-hidden'?: 'false' | 'true'; /** * Indicates the entered value does not conform to the format expected by the application. * @see aria-errormessage. */ 'aria-invalid'?: 'false' | 'true' | 'grammar' | 'spelling'; /** Indicates keyboard shortcuts that an author has implemented to activate or give focus to an element. */ 'aria-keyshortcuts'?: string; /** * Defines a string value that labels the current element. * @see aria-labelledby. */ 'aria-label'?: string; /** * Identifies the element (or elements) that labels the current element. * @see aria-describedby. */ 'aria-labelledby'?: string; /** Defines the hierarchical level of an element within a structure. */ 'aria-level'?: string; /** Indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region. */ 'aria-live'?: 'off' | 'assertive' | 'polite'; /** Indicates whether an element is modal when displayed. */ 'aria-modal'?: 'false' | 'true'; /** Indicates whether a text box accepts multiple lines of input or only a single line. */ 'aria-multiline'?: 'false' | 'true'; /** Indicates that the user may select more than one item from the current selectable descendants. */ 'aria-multiselectable'?: 'false' | 'true'; /** Indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous. */ 'aria-orientation'?: 'horizontal' | 'vertical'; /** * Identifies an element (or elements) in order to define a visual, functional, or contextual parent/child relationship * between DOM elements where the DOM hierarchy cannot be used to represent the relationship. * @see aria-controls. */ 'aria-owns'?: string; /** * Defines a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value. * A hint could be a sample value or a brief description of the expected format. */ 'aria-placeholder'?: string; /** * Defines an element's number or position in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. * @see aria-setsize. */ 'aria-posinset'?: string; /** * Indicates the current "pressed" state of toggle buttons. * @see aria-checked @see aria-selected. */ 'aria-pressed'?: 'false' | 'mixed' | 'true'; /** * Indicates that the element is not editable, but is otherwise operable. * @see aria-disabled. */ 'aria-readonly'?: 'false' | 'true'; /** * Indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified. * @see aria-atomic. */ 'aria-relevant'?: 'additions' | 'additions text' | 'all' | 'removals' | 'text'; /** Indicates that user input is required on the element before a form may be submitted. */ 'aria-required'?: 'false' | 'true'; /** Defines a human-readable, author-localized description for the role of an element. */ 'aria-roledescription'?: string; /** * Defines the total number of rows in a table, grid, or treegrid. * @see aria-rowindex. */ 'aria-rowcount'?: string; /** * Defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid. * @see aria-rowcount @see aria-rowspan. */ 'aria-rowindex'?: string; /** * Defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid. * @see aria-rowindex @see aria-colspan. */ 'aria-rowspan'?: string; /** * Indicates the current "selected" state of various widgets. * @see aria-checked @see aria-pressed. */ 'aria-selected'?: 'false' | 'true'; /** * Defines the number of items in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. * @see aria-posinset. */ 'aria-setsize'?: string; /** Indicates if items in a table or grid are sorted in ascending or descending order. */ 'aria-sort'?: 'none' | 'ascending' | 'descending' | 'other'; /** Defines the maximum allowed value for a range widget. */ 'aria-valuemax'?: string; /** Defines the minimum allowed value for a range widget. */ 'aria-valuemin'?: string; /** * Defines the current value for a range widget. * @see aria-valuetext. */ 'aria-valuenow'?: string; /** Defines the human readable text alternative of aria-valuenow for a range widget. */ 'aria-valuetext'?: string; } export interface VNodePropertiesWithoutIndex<T extends EventTarget = EventTarget> extends AriaAttributes { enterAnimation?: SupportedClassName; exitAnimation?: SupportedClassName; enterAnimationActive?: SupportedClassName; exitAnimationActive?: SupportedClassName; /** * Used to uniquely identify a DOM node among siblings. * A key is required when there are more children with the same selector and these children are added or removed dynamically. * NOTE: this does not have to be a string or number, a [[Component]] Object for instance is also possible. */ readonly key?: string | number; /** * An array of supported class names to be added to classList on a DOM node */ readonly classes?: SupportedClassName | SupportedClassName[]; /** * An object literal like `{height:'100px'}` which allows styles to be changed dynamically. All values must be strings. */ readonly styles?: Partial<CSSStyleDeclaration>; // Pointer Events onpointermove?(ev: PointerEvent<T>): boolean | void; onpointerdown?(ev: PointerEvent<T>): boolean | void; onpointerup?(ev: PointerEvent<T>): boolean | void; onpointerover?(ev: PointerEvent<T>): boolean | void; onpointerout?(ev: PointerEvent<T>): boolean | void; onpointerenter?(ev: PointerEvent<T>): boolean | void; onpointerleave?(ev: PointerEvent<T>): boolean | void; onpointercancel?(ev: PointerEvent<T>): boolean | void; // For Pointer Event Polyfill see: https://github.com/jquery/PEP readonly 'touch-action'?: string; // From Element ontouchcancel?(ev: TouchEvent<T>): boolean | void; ontouchend?(ev: TouchEvent<T>): boolean | void; ontouchmove?(ev: TouchEvent<T>): boolean | void; ontouchstart?(ev: TouchEvent<T>): boolean | void; // From HTMLFormElement readonly action?: string; readonly encoding?: string; readonly enctype?: string; readonly method?: string; readonly name?: string; readonly target?: string; // From HTMLElement onblur?(ev: FocusEvent<T>): boolean | void; onchange?(ev: DojoEvent<T>): boolean | void; onclick?(ev: MouseEvent<T>): boolean | void; ondblclick?(ev: MouseEvent<T>): boolean | void; onfocus?(ev: FocusEvent<T>): boolean | void; oninput?(ev: DojoEvent<T>): boolean | void; onkeydown?(ev: KeyboardEvent<T>): boolean | void; onkeypress?(ev: KeyboardEvent<T>): boolean | void; onkeyup?(ev: KeyboardEvent<T>): boolean | void; onload?(ev: DojoEvent<T>): boolean | void; onmousedown?(ev: MouseEvent<T>): boolean | void; onmouseenter?(ev: MouseEvent<T>): boolean | void; onmouseleave?(ev: MouseEvent<T>): boolean | void; onmousemove?(ev: MouseEvent<T>): boolean | void; onmouseout?(ev: MouseEvent<T>): boolean | void; onmouseover?(ev: MouseEvent<T>): boolean | void; onmouseup?(ev: MouseEvent<T>): boolean | void; onmousewheel?(ev: WheelEvent<T>): boolean | void; onscroll?(ev: UIEvent<T>): boolean | void; onsubmit?(ev: DojoEvent<T>): boolean | void; readonly spellcheck?: boolean; readonly tabIndex?: number; readonly disabled?: boolean; readonly title?: string; readonly accessKey?: string; readonly id?: string; // From HTMLInputElement readonly type?: string; readonly autocomplete?: string; readonly checked?: boolean; readonly placeholder?: string; readonly readOnly?: boolean; readonly src?: string; readonly value?: string; // From HTMLImageElement readonly alt?: string; readonly srcset?: string; /** * Puts a non-interactive string of html inside the DOM node. * * Note: if you use innerHTML, cannot protect you from XSS vulnerabilities and you must make sure that the innerHTML value is safe. */ readonly innerHTML?: string; /** * determines if the node should be focused */ readonly focus?: boolean | NodeOperationPredicate; /** * determines if the element needs to be clicked */ readonly click?: boolean | NodeOperationPredicate; /** * determines if the node should be scrolled to */ readonly scrollIntoView?: boolean | NodeOperationPredicate; /** * determines if the node should be blurred */ readonly blur?: boolean | NodeOperationPredicate; } type NonUndefined<A> = A extends undefined ? never : A; type FunctionKeys<T extends object> = { [K in keyof T]-?: NonUndefined<T[K]> extends Function ? K : never }[keyof T]; export interface VNodeProperties<T extends EventTarget = EventTarget> extends VNodePropertiesWithoutIndex<T> { oneventoptions?: { passive: FunctionKeys<VNodePropertiesWithoutIndex>[] }; /** * Everything that is not explicitly listed (properties and attributes that are either uncommon or custom). */ readonly [index: string]: any; } export interface SVGAttributes extends VNodeProperties<SVGElement> { 'accent-height'?: string; accumulate?: 'none' | 'sum'; additive?: 'replace' | 'sum'; 'alignment-baseline'?: | 'auto' | 'baseline' | 'before-edge' | 'text-before-edge' | 'middle' | 'central' | 'after-edge' | 'text-after-edge' | 'ideographic' | 'alphabetic' | 'hanging' | 'mathematical' | 'inherit'; allowReorder?: 'no' | 'yes'; alphabetic?: string; amplitude?: string; 'arabic-form'?: 'initial' | 'medial' | 'terminal' | 'isolated'; ascent?: string; attributeName?: string; attributeType?: string; autoReverse?: 'true' | 'false'; azimuth?: string; baseFrequency?: string; 'baseline-shift'?: string; baseProfile?: string; bbox?: string; begin?: string; bias?: string; by?: string; calcMode?: string; 'cap-height'?: string; clip?: string; 'clip-path'?: string; clipPathUnits?: string; 'clip-rule'?: string; 'color-interpolation'?: string; 'color-interpolation-filters'?: 'auto' | 'sRGB' | 'linearRGB' | 'inherit'; 'color-profile'?: string; 'color-rendering'?: string; contentScriptType?: string; contentStyleType?: string; cursor?: string; cx?: string; cy?: string; d?: string; decelerate?: string; descent?: string; diffuseConstant?: string; direction?: string; display?: string; divisor?: string; 'dominant-baseline'?: string; dur?: string; dx?: string; dy?: string; edgeMode?: string; elevation?: string; 'enable-background'?: string; end?: string; exponent?: string; externalResourcesRequired?: 'true' | 'false'; fill?: string; 'fill-opacity'?: string; 'fill-rule'?: 'nonzero' | 'evenodd' | 'inherit'; filter?: string; filterRes?: string; filterUnits?: string; 'flood-color'?: string; 'flood-opacity'?: string; focusable?: 'true' | 'false' | 'auto'; 'font-family'?: string; 'font-size'?: string; 'font-size-adjust'?: string; 'font-stretch'?: string; 'font-style'?: string; 'font-variant'?: string; 'font-weight'?: string; format?: string; from?: string; fx?: string; fy?: string; g1?: string; g2?: string; 'glyph-name'?: string; 'glyph-orientation-horizontal'?: string; 'glyph-orientation-vertical'?: string; glyphRef?: string; gradientTransform?: string; gradientUnits?: string; hanging?: string; height?: string; 'horiz-adv-x'?: string; 'horiz-origin-x'?: string; href?: string; ideographic?: string; 'image-rendering'?: string; in2?: string; in?: string; intercept?: string; k1?: string; k2?: string; k3?: string; k4?: string; k?: string; kernelMatrix?: string; kernelUnitLength?: string; kerning?: string; keyPoints?: string; keySplines?: string; keyTimes?: string; lengthAdjust?: string; 'letter-spacing'?: string; 'lighting-color'?: string; limitingConeAngle?: string; local?: string; 'marker-end'?: string; markerHeight?: string; 'marker-mid'?: string; 'marker-start'?: string; markerUnits?: string; markerWidth?: string; mask?: string; maskContentUnits?: string; maskUnits?: string; mathematical?: string; mode?: string; numOctaves?: string; offset?: string; opacity?: string; operator?: string; order?: string; orient?: string; orientation?: string; origin?: string; overflow?: string; 'overline-position'?: string; 'overline-thickness'?: string; 'paint-order'?: string; 'panose-1'?: string; path?: string; pathLength?: string; patternContentUnits?: string; patternTransform?: string; patternUnits?: string; 'pointer-events'?: string; points?: string; pointsAtX?: string; pointsAtY?: string; pointsAtZ?: string; preserveAlpha?: 'true' | 'false'; preserveAspectRatio?: string; primitiveUnits?: string; r?: string; radius?: string; refX?: string; refY?: string; 'rendering-intent'?: string; repeatCount?: string; repeatDur?: string; requiredExtensions?: string; requiredFeatures?: string; restart?: string; result?: string; rotate?: string; rx?: string; ry?: string; scale?: string; seed?: string; 'shape-rendering'?: string; slope?: string; spacing?: string; specularConstant?: string; specularExponent?: string; speed?: string; spreadMethod?: string; startOffset?: string; stdDeviation?: string; stemh?: string; stemv?: string; stitchTiles?: string; 'stop-color'?: string; 'stop-opacity'?: string; 'strikethrough-position'?: string; 'strikethrough-thickness'?: string; string?: string; stroke?: string; 'stroke-dasharray'?: string; 'stroke-dashoffset'?: string; 'stroke-linecap'?: 'butt' | 'round' | 'square' | 'inherit'; 'stroke-linejoin'?: 'miter' | 'round' | 'bevel' | 'inherit'; 'stroke-miterlimit'?: string; 'stroke-opacity'?: string; 'stroke-width'?: string; surfaceScale?: string; systemLanguage?: string; tableValues?: string; targetX?: string; targetY?: string; 'text-anchor'?: string; 'text-decoration'?: string; textLength?: string; 'text-rendering'?: string; to?: string; transform?: string; u1?: string; u2?: string; 'underline-position'?: string; 'underline-thickness'?: string; unicode?: string; 'unicode-bidi'?: string; 'unicode-range'?: string; 'units-per-em'?: string; 'v-alphabetic'?: string; values?: string; 'vector-effect'?: string; version?: string; 'vert-adv-y'?: string; 'vert-origin-x'?: string; 'vert-origin-y'?: string; 'v-hanging'?: string; 'v-ideographic'?: string; viewBox?: string; viewTarget?: string; visibility?: string; 'v-mathematical'?: string; width?: string; widths?: string; 'word-spacing'?: string; 'writing-mode'?: string; x1?: string; x2?: string; x?: string; xChannelSelector?: string; 'x-height'?: string; 'xlink:actuate'?: string; 'xlink:arcrole'?: string; 'xlink:href'?: string; 'xlink:role'?: string; 'xlink:show'?: string; 'xlink:title'?: string; 'xlink:type'?: string; 'xml:base'?: string; 'xml:lang'?: string; xmlns?: string; xmlnsXlink?: string; 'xml:space'?: string; y1?: string; y2?: string; y?: string; yChannelSelector?: string; z?: string; zoomAndPan?: string; } export interface AnchorAttributes extends VNodeProperties<HTMLAnchorElement> { download?: string; href?: string; hreflang?: string; ping?: string; rel?: string; target?: string; type?: string; media?: string; } export interface AreaAttributes extends VNodeProperties<HTMLAreaElement> { alt?: string; coords?: string; download?: string; href?: string; media?: string; hreflang?: string; ping?: string; rel?: string; shape?: string; target?: string; } export interface AudioAttributes extends VNodeProperties<HTMLAudioElement> { autoplay?: boolean; controls?: boolean; crossOrigin?: 'anonymous' | 'use-credentials'; loop?: boolean; mediaGroup?: string; muted?: boolean; preload?: 'none' | 'metadata' | 'auto' | ''; src?: string; } export interface BaseAttributes extends VNodeProperties<HTMLBaseElement> { href?: string; target?: string; } export interface BlockquoteAttributes extends VNodeProperties<HTMLQuoteElement> { cite?: string; } export interface ButtonAttributes extends VNodeProperties<HTMLButtonElement> { autofocus?: boolean; disabled?: boolean; form?: string; formAction?: string; formEncType?: string; formMethod?: string; formNoValidate?: boolean; formTarget?: string; name?: string; type?: 'submit' | 'reset' | 'button' | 'menu'; } export interface CanvasAttributes extends VNodeProperties<HTMLCanvasElement> { height?: number | string; width?: number | string; } export interface ColAttributes extends VNodeProperties<HTMLTableColElement> { span?: number; width?: number | string; } export interface ColgroupAttributes extends VNodeProperties { span?: number; } export interface DetailsAttributes extends VNodeProperties<HTMLDetailsElement> { open?: boolean; } export interface DelAttributes extends VNodeProperties { cite?: string; dateTime?: string; } export interface DialogAttributes extends VNodeProperties<HTMLDialogElement> { open?: boolean; } export interface EmbedAttributes extends VNodeProperties<HTMLEmbedElement> { height?: number | string; src?: string; type?: string; width?: number | string; } export interface FieldsetAttributes extends VNodeProperties<HTMLFieldSetElement> { disabled?: boolean; form?: string; name?: string; } export interface FormAttributes extends VNodeProperties<HTMLFormElement> { acceptCharset?: string; action?: string; autoComplete?: string; encType?: string; method?: string; name?: string; noValidate?: boolean; target?: string; } export interface HtmlAttributes extends VNodeProperties<HTMLHtmlElement> { manifest?: string; } export interface IFrameAttributes extends VNodeProperties<HTMLIFrameElement> { allow?: string; allowFullScreen?: boolean; allowTransparency?: boolean; frameBorder?: number | string; height?: number | string; marginHeight?: number; marginWidth?: number; name?: string; referrerPolicy?: string; sandbox?: string; scrolling?: string; seamless?: boolean; src?: string; srcDoc?: string; width?: number | string; } export interface ImgAttributes extends VNodeProperties<HTMLImageElement> { alt?: string; crossOrigin?: 'anonymous' | 'use-credentials' | ''; decoding?: 'async' | 'auto' | 'sync'; height?: number | string; loading?: 'eager' | 'lazy'; referrerPolicy?: 'no-referrer' | 'origin' | 'unsafe-url'; sizes?: string; src?: string; srcSet?: string; useMap?: string; width?: number | string; } export interface InsAttributes extends VNodeProperties { cite?: string; dateTime?: string; } export interface InputAttributes extends VNodeProperties<HTMLInputElement> { accept?: string; alt?: string; autoComplete?: string; autofocus?: boolean; capture?: boolean | string; checked?: boolean; crossOrigin?: string; disabled?: boolean; form?: string; formAction?: string; formEncType?: string; formMethod?: string; formNoValidate?: boolean; formTarget?: string; height?: number | string; list?: string; max?: number | string; maxLength?: number; min?: number | string; minLength?: number; multiple?: boolean; name?: string; pattern?: string; placeholder?: string; readOnly?: boolean; required?: boolean; size?: number; src?: string; step?: number | string; type?: string; width?: number | string; } interface KeygenAttributes extends VNodeProperties { autofocus?: boolean; challenge?: string; disabled?: boolean; form?: string; keyType?: string; keyParams?: string; name?: string; } interface LabelAttributes extends VNodeProperties<HTMLLabelElement> { for?: string; form?: string; } interface LinkAttributes extends VNodeProperties<HTMLLinkElement> { as?: string; crossOrigin?: string; href?: string; hrefLang?: string; integrity?: string; media?: string; rel?: string; sizes?: string; type?: string; charSet?: string; } interface MapAttributes extends VNodeProperties<HTMLMapElement> { name?: string; } interface MenuAttributes extends VNodeProperties<HTMLMenuElement> { type?: string; } interface MetaAttributes extends VNodeProperties<HTMLMetaElement> { charSet?: string; content?: string; httpEquiv?: string; name?: string; } interface MeterAttributes extends VNodeProperties<HTMLMeterElement> { form?: string; high?: number; low?: number; max?: number | string; min?: number | string; optimum?: number; } interface ObjectAttributes extends VNodeProperties<HTMLObjectElement> { classID?: string; data?: string; form?: string; height?: number | string; name?: string; type?: string; useMap?: string; width?: number | string; wmode?: string; } interface OlAttributes extends VNodeProperties<HTMLOListElement> { reversed?: boolean; start?: number; type?: '1' | 'a' | 'A' | 'i' | 'I'; } interface OptgroupAttributes extends VNodeProperties<HTMLOptGroupElement> { disabled?: boolean; label?: string; } interface OptionAttributes extends VNodeProperties<HTMLOptionElement> { disabled?: boolean; label?: string; selected?: boolean; } interface OutputAttributes extends VNodeProperties<HTMLOutputElement> { form?: string; for?: string; name?: string; } interface ParamAttributes extends VNodeProperties<HTMLParamElement> { name?: string; } interface ProgressAttributes extends VNodeProperties<HTMLProgressElement> { max?: number | string; } interface QuoteAttributes extends VNodeProperties<HTMLQuoteElement> { cite?: string; } interface SlotAttributes extends VNodeProperties<HTMLSlotElement> { name?: string; } interface SelectAttributes extends VNodeProperties<HTMLSelectElement> { autoComplete?: string; autofocus?: boolean; disabled?: boolean; form?: string; multiple?: boolean; name?: string; required?: boolean; size?: number; } interface SourceAttributes extends VNodeProperties<HTMLSourceElement> { media?: string; sizes?: string; src?: string; srcSet?: string; type?: string; } interface StyleAttributes extends VNodeProperties<HTMLStyleElement> { media?: string; nonce?: string; type?: string; } interface TableAttributes extends VNodeProperties<HTMLTableElement> { cellPadding?: number | string; cellSpacing?: number | string; summary?: string; } interface TextareaAttributes extends VNodeProperties<HTMLTextAreaElement> { autoComplete?: string; autofocus?: boolean; cols?: number; dirName?: string; disabled?: boolean; form?: string; maxLength?: number; minLength?: number; name?: string; placeholder?: string; readOnly?: boolean; required?: boolean; rows?: number; wrap?: string; } interface TdAttributes extends VNodeProperties<HTMLTableDataCellElement> { align?: 'left' | 'center' | 'right' | 'justify' | 'char'; colSpan?: number; headers?: string; rowSpan?: number; scope?: string; abbr?: string; valign?: 'top' | 'middle' | 'bottom' | 'baseline'; } interface ThAttributes extends VNodeProperties<HTMLTableHeaderCellElement> { align?: 'left' | 'center' | 'right' | 'justify' | 'char'; colSpan?: number; headers?: string; rowSpan?: number; scope?: string; abbr?: string; } interface TimeAttributes extends VNodeProperties<HTMLTimeElement> { dateTime?: string; } interface TrackAttributes extends VNodeProperties<HTMLTrackElement> { default?: boolean; kind?: string; label?: string; src?: string; srcLang?: string; } export interface VideoAttributes extends VNodeProperties<HTMLVideoElement> { autoPlay?: boolean; controls?: boolean; crossOrigin?: 'anonymous' | 'use-credentials'; loop?: boolean; mediaGroup?: string; muted?: boolean; playsInline?: boolean; preload?: 'none' | 'metadata' | 'auto' | ''; src?: string; height?: number | string; width?: number | string; } /** * Type of the `WidgetRegistry` label */ export type RegistryLabel = string | symbol; export type InjectorPayload = () => any; /** * Factory that returns an injector function */ export type InjectorFactory = (invalidator: () => void) => InjectorPayload; /** * The injector item created for a registered Injector factory */ export interface InjectorItem<T = any> { injector: () => T; invalidator: Evented; } /** * Base widget properties */ export interface WidgetProperties { /** * The key for a widget. Used to uniquely identify child widgets for * rendering and instance management */ key?: string | number; } /** * Widget properties that require a key */ export interface KeyedWidgetProperties extends WidgetProperties { /** * The key for a widget. Used to uniquely identify child widgets for * rendering and instance management */ key: string | number; } /** * Wrapper for v */ export interface VNode { /** * Specified children */ children?: DNode[]; /** * VNode properties */ properties: VNodeProperties; /** * VNode attributes */ attributes?: { [index: string]: string | undefined }; /** * VNode events */ events?: On; /** * Deferred callback for VNode properties */ deferredPropertiesCallback?: DeferredVirtualProperties; /** * The tag of the VNode */ tag: string; /** * The type of node */ type: string; /** * Text node string */ text?: string; /** * Indicates the type of diff for the VNode */ diffType?: DiffType; } export interface DomVNode extends VNode { domNode: Text | Element; onAttach?: () => void; onUpdate?: () => void; onDetach?: () => void; } export interface ESMDefaultWidgetBase<T extends WidgetBaseTypes> { default: Constructor<T> | WNodeFactory<T>; __esModule?: boolean; } export type WidgetBaseConstructorFunction<W extends WidgetBaseTypes = DefaultWidgetBaseInterface> = () => Promise< Constructor<W> | WNodeFactory<W> >; export type ESMDefaultWidgetBaseFunction<W extends WidgetBaseTypes = DefaultWidgetBaseInterface> = () => Promise< ESMDefaultWidgetBase<W> >; export type LazyWidget<W extends WidgetBaseTypes = DefaultWidgetBaseInterface> = | WidgetBaseConstructorFunction<W> | ESMDefaultWidgetBaseFunction<W>; export type LazyDefine<W extends WidgetBaseTypes = DefaultWidgetBaseInterface> = { label: string; registryItem: LazyWidget<W>; }; export interface MiddlewareMap< Middleware extends () => { api: {}; properties: {} } = () => { api: {}; properties: {} } > { [index: string]: Middleware; } export type MiddlewareApiMap<U extends MiddlewareMap<any>> = { [P in keyof U]: ReturnType<U[P]>['api'] }; export type MiddlewareApi<T extends MiddlewareResultFactory<any, any, any, any>> = ReturnType<ReturnType<T>['api']>; export type WrappedProperties<T> = { [P in keyof T]: T[P] extends ((...args: any[]) => any) | Constructor<any> | undefined ? T[P] & { unwrap: () => T[P] } : T[P] }; export interface Callback<Props, Children, Middleware, ReturnValue> { ( options: { id: string; middleware: MiddlewareApiMap<Middleware>; properties: () => WrappedProperties<Readonly<Props>>; children: () => Children extends any[] ? Children : [Children]; } ): ReturnValue; middlewares?: any; } export interface MiddlewareResult<Props, Children, Middleware, ReturnValue> { api: ReturnValue; properties: Props; callback: Callback<Props, Children, Middleware, ReturnValue>; middlewares: Middleware; } export interface DefaultMiddlewareResult extends MiddlewareResult<any, any, any, any> {} export interface MiddlewareResultFactory<Props, Children, Middleware, ReturnValue> { (): MiddlewareResult<Props, Children, Middleware, ReturnValue>; withType: <Api extends ReturnValue, CustomProps = Props>() => MiddlewareResultFactory< CustomProps, Children, Middleware, Api >; } export interface DefaultChildrenWNodeFactory<W extends WNodeFactoryTypes> { (properties: W['properties'], children?: W['children'] extends any[] ? W['children'] : [W['children']]): WNode<W>; new (): { __properties__: W['properties'] & { __children__?: DNode | DNode[] | (DNode | DNode[])[] }; }; properties: W['properties']; children: W['children']; type: 'default'; } export interface WNodeFactory<W extends WNodeFactoryTypes> { ( properties: W['properties'], children: W['children'] extends [any] ? W['children'][0][] : W['children'] extends any[] ? W['children'] : [W['children']] ): WNode<W>; new (): { __properties__: W['properties'] & { __children__: W['children'] }; }; properties: W['properties']; children: W['children']; type: 'required'; } export interface OptionalWNodeFactory<W extends WNodeFactoryTypes> { ( properties: W['properties'], children?: W['children'] extends [any] ? W['children'][0][] : W['children'] extends any[] ? W['children'] : [W['children']] ): WNode<W>; new (): { __properties__: W['properties'] & { __children__?: W['children'] }; }; properties: W['properties']; children: W['children']; type: 'optional'; } export interface WNodeFactoryTypes<P = any, C = any> { readonly properties: P; readonly children: C; } export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never; /** * Wrapper for `w` */ export interface WNode<W extends WidgetBaseTypes = any> { /** * Constructor to create a widget or string constructor label */ widgetConstructor: Constructor<W> | RegistryLabel | LazyDefine<W> | Callback<any, any, any, RenderResult>; /** * Properties to set against a widget instance */ properties: W['properties']; /** * DNode children */ children: DNode[]; /** * The type of node */ type: string; } /** * union type for all possible return types from render */ export type DNode<W extends WidgetBaseTypes = any> = VNode | WNode<W> | undefined | null | string | boolean | number; /** * Property Change record for specific property diff functions */ export interface PropertyChangeRecord { changed: boolean; value: any; } export interface DiffPropertyFunction { (previousProperty: any, newProperty: any): PropertyChangeRecord; } export interface DiffPropertyReaction { (previousProperties: any, newProperties: any): void; } /** * WidgetBase constructor type */ export type WidgetBaseConstructor<P extends WidgetProperties = WidgetProperties, C extends DNode = DNode> = Constructor< WidgetBaseInterface<P, C> >; export interface DefaultWidgetBaseInterface extends WidgetBaseInterface<WidgetProperties, DNode> {} export interface WidgetBaseTypes<P = any, C extends DNode = DNode> { /** * Widget properties */ readonly properties: P; /** * Returns the widget's children */ readonly children: (C | null)[]; } /** * The interface for WidgetBase */ export interface WidgetBaseInterface<P = WidgetProperties, C extends DNode = DNode> extends WidgetBaseTypes<P, C> { /** * Sets the properties for the widget. Responsible for calling the diffing functions for the properties against the * previous properties. Runs though any registered specific property diff functions collecting the results and then * runs the remainder through the catch all diff function. The aggregate of the two sets of the results is then * set as the widget's properties * * @param properties The new widget properties */ __setProperties__(properties: P & { [index: string]: any }): void; /** * Sets the widget's children */ __setChildren__(children: (C | null)[]): void; /** * Main internal function for dealing with widget rendering */ __render__(): RenderResult; /** * property used for typing with tsx */ __properties__: this['properties'] & { __children__?: DNode | (DNode | DNode[])[] }; } /** * Meta Base type */ export interface MetaBase extends Destroyable {} /** * Meta Base type */ export interface WidgetMetaBase extends MetaBase { has(key: string | number): boolean; afterRender(): void; } /** * Meta Base constructor type */ export interface WidgetMetaConstructor<T extends MetaBase> { new (properties: WidgetMetaProperties): T; } export interface NodeHandlerInterface extends Evented { get(key: string | number): Element | undefined; has(key: string | number): boolean; add(element: Element, key: string): void; addRoot(element: Element, key: string): void; addProjector(element: Element, properties: VNodeProperties): void; clear(): void; } /** * Properties passed to meta Base constructors */ export interface WidgetMetaProperties { invalidate: () => void; nodeHandler: NodeHandlerInterface; bind: WidgetBaseInterface; } export type RenderResult = DNode | DNode[]; export interface Render { (): DNode | DNode[]; } /** * Interface for beforeRender function */ export interface BeforeRender { (renderFunc: Render, properties: WidgetProperties, children: DNode[]): Render | undefined; } /** * Interface for afterRender function */ export interface AfterRender { (dNode: DNode | DNode[]): DNode | DNode[]; } /** * Interface for beforeProperties function */ export interface BeforeProperties<P = any> { (properties: P): P; } export interface LocaleData { /** * The locale for the widget. If not specified, then the root locale (as determined by `@dojo/i18n`) is assumed. * If specified, the widget's node will have a `lang` property set to the locale. */ locale?: string; /** * An optional flag indicating the widget's text direction. If `true`, then the underlying node's `dir` * property is set to "rtl". If it is `false`, then the `dir` property is set to "ltr". Otherwise, the property * is not set. */ rtl?: boolean; } export interface FocusProperties { /** Function to determine if the widget should focus */ focus?: () => boolean; } export interface I18nProperties extends LocaleData { /** * An optional override for the bundle passed to the `localizeBundle`. If the override contains a `messages` object, * then it will completely replace the underlying bundle. Otherwise, a new bundle will be created with the additional * locale loaders. */ i18nBundle?: Bundle<Messages> | Map<Bundle<Messages>, Bundle<Messages>>; } export type LocalizedMessages<T extends Messages> = { /** * Indicates whether the messages are placeholders while waiting for the actual localized messages to load. * This is always `false` if the associated bundle does not list any supported locales. */ readonly isPlaceholder: boolean; /** * Formats an ICU-formatted message template for the represented bundle. * * @param key * The message key. * * @param options * The values to pass to the formatter. * * @return * The formatted string. */ format(key: keyof T, options?: any): string; /** * The localized messages if available, or either the default messages or a blank bundle depending on the * call signature for `localizeBundle`. */ readonly messages: T; }; export type Invalidator = () => void;
the_stack
"use strict"; import dynamicProto from "@microsoft/dynamicproto-js"; import { IAppInsightsCore } from "../JavaScriptSDK.Interfaces/IAppInsightsCore" import { IConfiguration } from "../JavaScriptSDK.Interfaces/IConfiguration"; import { IDiagnosticLogger } from "../JavaScriptSDK.Interfaces/IDiagnosticLogger"; import { IPlugin, ITelemetryPlugin } from "../JavaScriptSDK.Interfaces/ITelemetryPlugin"; import { ITelemetryItem } from "../JavaScriptSDK.Interfaces/ITelemetryItem"; import { IProcessTelemetryContext, IProcessTelemetryUnloadContext, IProcessTelemetryUpdateContext } from "../JavaScriptSDK.Interfaces/IProcessTelemetryContext"; import { ITelemetryPluginChain } from "../JavaScriptSDK.Interfaces/ITelemetryPluginChain"; import { createProcessTelemetryContext, createProcessTelemetryUnloadContext, createProcessTelemetryUpdateContext } from "./ProcessTelemetryContext"; import { arrForEach, isArray, isFunction, isNullOrUndefined, proxyFunctionAs, setValue } from "./HelperFuncs"; import { strExtensionConfig } from "./Constants"; import { createUnloadHandlerContainer, IUnloadHandlerContainer, UnloadHandler } from "./UnloadHandlerContainer"; import { IInstrumentHook } from "../JavaScriptSDK.Interfaces/IInstrumentHooks"; import { ITelemetryUnloadState } from "../JavaScriptSDK.Interfaces/ITelemetryUnloadState"; import { TelemetryUnloadReason } from "../JavaScriptSDK.Enums/TelemetryUnloadReason"; import { ITelemetryUpdateState } from "../JavaScriptSDK.Interfaces/ITelemetryUpdateState"; import { TelemetryUpdateReason } from "../JavaScriptSDK.Enums/TelemetryUpdateReason"; import { strDoTeardown, strIsInitialized, strSetNextPlugin } from "./InternalConstants"; let strGetPlugin = "getPlugin"; /** * BaseTelemetryPlugin provides a basic implementation of the ITelemetryPlugin interface so that plugins * can avoid implementation the same set of boiler plate code as well as provide a base * implementation so that new default implementations can be added without breaking all plugins. */ export abstract class BaseTelemetryPlugin implements ITelemetryPlugin { public identifier: string; public version?: string; /** * Holds the core instance that was used during initialization */ public core: IAppInsightsCore; priority: number; /** * Call back for telemetry processing before it it is sent * @param env - This is the current event being reported * @param itemCtx - This is the context for the current request, ITelemetryPlugin instances * can optionally use this to access the current core instance or define / pass additional information * to later plugins (vs appending items to the telemetry item) */ public processNext: (env: ITelemetryItem, itemCtx: IProcessTelemetryContext) => void; /** * Set next extension for telemetry processing */ public setNextPlugin: (next: ITelemetryPlugin | ITelemetryPluginChain) => void; /** * Returns the current diagnostic logger that can be used to log issues, if no logger is currently * assigned a new default one will be created and returned. */ public diagLog: (itemCtx?:IProcessTelemetryContext) => IDiagnosticLogger; /** * Returns whether the plugin has been initialized */ public isInitialized: () => boolean; /** * Helper to return the current IProcessTelemetryContext, if the passed argument exists this just * returns that value (helps with minification for callers), otherwise it will return the configured * context or a temporary one. * @param currentCtx - [Optional] The current execution context */ protected _getTelCtx: (currentCtx?:IProcessTelemetryContext) => IProcessTelemetryContext; /** * Internal helper to allow setting of the internal initialized setting for inherited instances and unit testing */ protected setInitialized: (isInitialized: boolean) => void; /** * Teardown / Unload hook to allow implementations to perform some additional unload operations before the BaseTelemetryPlugin * finishes it's removal. * @param unloadCtx - This is the context that should be used during unloading. * @param unloadState - The details / state of the unload process, it holds details like whether it should be unloaded synchronously or asynchronously and the reason for the unload. * @param asyncCallback - An optional callback that the plugin must call if it returns true to inform the caller that it has completed any async unload/teardown operations. * @returns boolean - true if the plugin has or will call asyncCallback, this allows the plugin to perform any asynchronous operations. */ protected _doTeardown?: (unloadCtx?: IProcessTelemetryUnloadContext, unloadState?: ITelemetryUnloadState, asyncCallback?: () => void) => void | boolean; /** * Extension hook to allow implementations to perform some additional update operations before the BaseTelemetryPlugin finishes it's removal * @param updateCtx - This is the context that should be used during updating. * @param updateState - The details / state of the update process, it holds details like the current and previous configuration. * @param asyncCallback - An optional callback that the plugin must call if it returns true to inform the caller that it has completed any async update operations. * @returns boolean - true if the plugin has or will call asyncCallback, this allows the plugin to perform any asynchronous operations. */ protected _doUpdate?: (updateCtx?: IProcessTelemetryUpdateContext, updateState?: ITelemetryUpdateState, asyncCallback?: () => void) => void | boolean; constructor() { let _self = this; // Setting _self here as it's used outside of the dynamicProto as well // NOTE!: DON'T set default values here, instead set them in the _initDefaults() function as it is also called during teardown() let _isinitialized: boolean; let _rootCtx: IProcessTelemetryContext; // Used as the root context, holding the current config and initialized core let _nextPlugin: ITelemetryPlugin | ITelemetryPluginChain; // Used for backward compatibility where plugins don't call the main pipeline let _unloadHandlerContainer: IUnloadHandlerContainer; let _hooks: IInstrumentHook[]; _initDefaults(); dynamicProto(BaseTelemetryPlugin, _self, (_self) => { _self.initialize = (config: IConfiguration, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?:ITelemetryPluginChain): void => { _setDefaults(config, core, pluginChain); _isinitialized = true; } _self.teardown = (unloadCtx?: IProcessTelemetryUnloadContext, unloadState?: ITelemetryUnloadState) => { // If this plugin has already been torn down (not operational) or is not initialized (core is not set) // or the core being used for unload was not the same core used for initialization. let core = _self.core; if (!core || (unloadCtx && core !== unloadCtx.core())) { // Do Nothing as either the plugin is not initialized or was not initialized by the current core return; } let result: void | boolean; let unloadDone = false; let theUnloadCtx = unloadCtx || createProcessTelemetryUnloadContext(null, core, _nextPlugin && _nextPlugin[strGetPlugin] ? _nextPlugin[strGetPlugin]() : _nextPlugin); let theUnloadState: ITelemetryUnloadState = unloadState || { reason: TelemetryUnloadReason.ManualTeardown, isAsync: false }; function _unloadCallback() { if (!unloadDone) { unloadDone = true; _unloadHandlerContainer.run(theUnloadCtx, unloadState); // Remove all instrumentation hooks arrForEach(_hooks, (fn) => { fn.rm(); }); _hooks = []; if (result === true) { theUnloadCtx.processNext(theUnloadState); } _initDefaults(); } } if (!_self[strDoTeardown] || _self[strDoTeardown](theUnloadCtx, theUnloadState, _unloadCallback) !== true) { _unloadCallback(); } else { // Tell the caller that we will be calling processNext() result = true; } return result; }; _self.update = (updateCtx: IProcessTelemetryUpdateContext, updateState: ITelemetryUpdateState) => { // If this plugin has already been torn down (not operational) or is not initialized (core is not set) // or the core being used for unload was not the same core used for initialization. let core = _self.core; if (!core || (updateCtx && core !== updateCtx.core())) { // Do Nothing return; } let result: void | boolean; let updateDone = false; let theUpdateCtx = updateCtx || createProcessTelemetryUpdateContext(null, core, _nextPlugin && _nextPlugin[strGetPlugin] ? _nextPlugin[strGetPlugin]() : _nextPlugin); let theUpdateState: ITelemetryUpdateState = updateState || { reason: TelemetryUpdateReason.Unknown }; function _updateCallback() { if (!updateDone) { updateDone = true; _setDefaults(theUpdateCtx.getCfg(), theUpdateCtx.core(), theUpdateCtx.getNext()); } } if (!_self._doUpdate || _self._doUpdate(theUpdateCtx, theUpdateState, _updateCallback) !== true) { _updateCallback(); } else { result = true; } return result; }; _self._addHook = (hooks: IInstrumentHook | IInstrumentHook[]) => { if (hooks) { if (isArray(hooks)) { _hooks = _hooks.concat(hooks); } else { _hooks.push(hooks); } } }; proxyFunctionAs(_self, "_addUnloadCb", () => _unloadHandlerContainer, "add"); }); // These are added after the dynamicProto so that are not moved to the prototype _self.diagLog = (itemCtx:IProcessTelemetryContext): IDiagnosticLogger => { return _getTelCtx(itemCtx).diagLog(); } _self[strIsInitialized] = () => { return _isinitialized; } _self.setInitialized = (isInitialized: boolean):void => { _isinitialized = isInitialized; } // _self.getNextPlugin = () => DO NOT IMPLEMENT // Sub-classes of this base class *should* not be relying on this value and instead // should use processNext() function. If you require access to the plugin use the // IProcessTelemetryContext.getNext().getPlugin() while in the pipeline, Note getNext() may return null. _self[strSetNextPlugin] = (next: ITelemetryPlugin | ITelemetryPluginChain) => { _nextPlugin = next; }; _self.processNext = (env: ITelemetryItem, itemCtx: IProcessTelemetryContext) => { if (itemCtx) { // Normal core execution sequence itemCtx.processNext(env); } else if (_nextPlugin && isFunction(_nextPlugin.processTelemetry)) { // Looks like backward compatibility or out of band processing. And as it looks // like a ITelemetryPlugin or ITelemetryPluginChain, just call processTelemetry _nextPlugin.processTelemetry(env, null); } }; _self._getTelCtx = _getTelCtx; function _getTelCtx(currentCtx:IProcessTelemetryContext = null) { let itemCtx:IProcessTelemetryContext = currentCtx; if (!itemCtx) { let rootCtx = _rootCtx || createProcessTelemetryContext(null, {}, _self.core); // tslint:disable-next-line: prefer-conditional-expression if (_nextPlugin && _nextPlugin[strGetPlugin]) { // Looks like a chain object itemCtx = rootCtx.createNew(null, _nextPlugin[strGetPlugin]); } else { itemCtx = rootCtx.createNew(null, _nextPlugin as ITelemetryPlugin); } } return itemCtx; } function _setDefaults(config: IConfiguration, core: IAppInsightsCore, pluginChain: ITelemetryPluginChain) { if (config) { // Make sure the extensionConfig exists setValue(config, strExtensionConfig, [], null, isNullOrUndefined); } if (!pluginChain && core) { // Get the first plugin from the core pluginChain = core.getProcessTelContext().getNext(); } let nextPlugin: IPlugin = _nextPlugin as IPlugin; if (_nextPlugin && _nextPlugin[strGetPlugin]) { // If it looks like a proxy/chain then get the plugin nextPlugin = _nextPlugin[strGetPlugin](); } // Support legacy plugins where core was defined as a property _self.core = core; _rootCtx = createProcessTelemetryContext(pluginChain, config, core, nextPlugin); } function _initDefaults() { _isinitialized = false; _self.core = null; _rootCtx = null; _nextPlugin = null; _hooks = []; _unloadHandlerContainer = createUnloadHandlerContainer(); } } public initialize(config: IConfiguration, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?:ITelemetryPluginChain): void { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } /** * Tear down the plugin and remove any hooked value, the plugin should be removed so that it is no longer initialized and * therefore could be re-initialized after being torn down. The plugin should ensure that once this has been called any further * processTelemetry calls are ignored and it just calls the processNext() with the provided context. * @param unloadCtx - This is the context that should be used during unloading. * @param unloadState - The details / state of the unload process, it holds details like whether it should be unloaded synchronously or asynchronously and the reason for the unload. * @returns boolean - true if the plugin has or will call processNext(), this for backward compatibility as previously teardown was synchronous and returned nothing. */ public teardown(unloadCtx?: IProcessTelemetryUnloadContext, unloadState?: ITelemetryUnloadState): void | boolean { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging return false; } public abstract processTelemetry(env: ITelemetryItem, itemCtx?: IProcessTelemetryContext): void; /** * The the plugin should re-evaluate configuration and update any cached configuration settings. * @param updateCtx - This is the context that should be used during updating. * @param updateState - The details / state of the update process, it holds details like the current and previous configuration. * @returns boolean - true if the plugin has or will call updateCtx.processNext(), this allows the plugin to perform any asynchronous operations. */ public update(updateCtx: IProcessTelemetryUpdateContext, updateState: ITelemetryUpdateState): void | boolean{ // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } /** * Add an unload handler that will be called when the SDK is being unloaded * @param handler - the handler */ protected _addUnloadCb(handler: UnloadHandler): void { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } /** * Add this hook so that it is automatically removed during unloading * @param hooks - The single hook or an array of IInstrumentHook objects */ protected _addHook(hooks: IInstrumentHook | IInstrumentHook[]): void { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormFax { interface Header extends DevKit.Controls.IHeader { /** Enter the user or team who is assigned to manage the record. This field is updated every time the record is assigned to a different user. */ OwnerId: DevKit.Controls.Lookup; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.Controls.OptionSet; /** Enter the expected due date and time. */ ScheduledEnd: DevKit.Controls.DateTime; /** Shows whether the fax activity is open, completed, or canceled. Completed and canceled fax activities are read-only and can't be edited. */ StateCode: DevKit.Controls.OptionSet; } interface tab_SUMMARY_TAB_Sections { general_information: DevKit.Controls.Section; Letter_description: DevKit.Controls.Section; Letter_details: DevKit.Controls.Section; tab_2_section_2: DevKit.Controls.Section; } interface tab_SUMMARY_TAB extends DevKit.Controls.ITab { Section: tab_SUMMARY_TAB_Sections; } interface Tabs { SUMMARY_TAB: tab_SUMMARY_TAB; } interface Body { Tab: Tabs; /** Type the number of minutes spent creating and sending the fax. The duration is used in reporting. */ ActualDurationMinutes: DevKit.Controls.Integer; /** Type additional information to describe the fax, such as the primary message or the products and services featured. */ Description: DevKit.Controls.String; /** Select the direction of the fax as incoming or outbound. */ DirectionCode: DevKit.Controls.Boolean; /** Type the recipient's fax number. */ FaxNumber: DevKit.Controls.String; /** Enter the account, contact, lead, queue, or user who sent the fax. */ from: DevKit.Controls.Lookup; /** Unique identifier of the object with which the fax activity is associated. */ RegardingObjectId: DevKit.Controls.Lookup; /** Type a short description about the objective or primary topic of the fax. */ Subject: DevKit.Controls.String; /** Enter the account, contact, lead, queue, or user recipients for the fax. */ to: DevKit.Controls.Lookup; } } class FormFax extends DevKit.IForm { /** * DynamicsCrm.DevKit form Fax * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Fax */ Body: DevKit.FormFax.Body; /** The Header section of form Fax */ Header: DevKit.FormFax.Header; } class FaxApi { /** * DynamicsCrm.DevKit FaxApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the fax activity. */ ActivityId: DevKit.WebApi.GuidValue; /** Type the number of minutes spent creating and sending the fax. The duration is used in reporting. */ ActualDurationMinutes: DevKit.WebApi.IntegerValue; /** Enter the actual end date and time of the fax. By default, it displays the date and time when the activity was completed or canceled, but can be edited to capture the actual time to create and send the fax. */ ActualEnd_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the actual start date and time for the fax. By default, it displays the date and time when the activity was created, but can be edited to capture the actual time to create and send the fax. */ ActualStart_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Type the billing code for the fax to make sure the fax is charged to the correct sender or customer account. */ BillingCode: DevKit.WebApi.StringValue; /** Type a category to identify the fax type, such as sales offer or press release, to tie the fax to a business group or function. */ Category: DevKit.WebApi.StringValue; /** Type the name of the cover page to use when sending the fax. */ CoverPageName: DevKit.WebApi.StringValue; /** Shows who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Type additional information to describe the fax, such as the primary message or the products and services featured. */ Description: DevKit.WebApi.StringValue; /** Select the direction of the fax as incoming or outbound. */ DirectionCode: DevKit.WebApi.BooleanValue; /** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Type the recipient's fax number. */ FaxNumber: DevKit.WebApi.StringValue; /** Unique identifier of the data import or data migration that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Information regarding whether the fax activity was billed as part of resolving a case. */ IsBilled: DevKit.WebApi.BooleanValue; /** Information regarding whether the activity is a regular activity type or event type. */ IsRegularActivity: DevKit.WebApi.BooleanValueReadonly; /** Indication of whether the fax activity was created by a workflow rule. */ IsWorkflowCreated: DevKit.WebApi.BooleanValue; /** Contains the date and time stamp of the last on hold time. */ LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows who last updated the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Type the number of pages included in the fax. */ NumberOfPages: DevKit.WebApi.IntegerValue; /** Shows how long, in minutes, that the record was on hold. */ OnHoldTime: DevKit.WebApi.IntegerValueReadonly; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier of the business unit that owns the fax activity. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team that owns the fax activity. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user that owns the fax activity. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.WebApi.OptionSetValue; /** Shows the ID of the process. */ ProcessId: DevKit.WebApi.GuidValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_account_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_bookableresourcebooking_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_bookableresourcebookingheader_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_bulkoperation_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_campaign_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_campaignactivity_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_contact_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_contract_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_entitlement_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_entitlementtemplate_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_incident_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_invoice_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_knowledgearticle_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_knowledgebaserecord_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_lead_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_agreement_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_agreementbookingdate_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_agreementbookingincident_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_agreementbookingproduct_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_agreementbookingservice_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_agreementbookingservicetask_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_agreementbookingsetup_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_agreementinvoicedate_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_agreementinvoiceproduct_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_agreementinvoicesetup_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_bookingalertstatus_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_bookingrule_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_bookingtimestamp_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_customerasset_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_fieldservicesetting_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_incidenttypecharacteristic_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_incidenttypeproduct_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_incidenttypeservice_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_inventoryadjustment_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_inventoryadjustmentproduct_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_inventoryjournal_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_inventorytransfer_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_payment_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_paymentdetail_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_paymentmethod_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_paymentterm_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_playbookinstance_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_postalbum_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_postalcode_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_processnotes_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_productinventory_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_projectteam_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_purchaseorder_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_purchaseorderbill_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_purchaseorderproduct_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_purchaseorderreceipt_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_purchaseorderreceiptproduct_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_purchaseordersubstatus_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_quotebookingincident_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_quotebookingproduct_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_quotebookingservice_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_quotebookingservicetask_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_resourceterritory_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_rma_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_rmaproduct_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_rmareceipt_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_rmareceiptproduct_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_rmasubstatus_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_rtv_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_rtvproduct_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_rtvsubstatus_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_shipvia_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_systemuserschedulersetting_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_timegroup_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_timegroupdetail_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_timeoffrequest_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_warehouse_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_workorder_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_workordercharacteristic_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_workorderincident_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_workorderproduct_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_workorderresourcerestriction_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_workorderservice_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_msdyn_workorderservicetask_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_opportunity_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_quote_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_salesorder_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_site_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_uii_action_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_uii_hostedapplication_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_uii_nonhostedapplication_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_uii_option_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_uii_savedsession_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_uii_workflow_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_uii_workflowstep_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the fax activity is associated. */ regardingobjectid_uii_workflow_workflowstep_mapping_fax: DevKit.WebApi.LookupValue; /** Shows the expected duration of the fax activity, in minutes. */ ScheduledDurationMinutes: DevKit.WebApi.IntegerValueReadonly; /** Enter the expected due date and time. */ ScheduledEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Enter the expected due date and time. */ ScheduledStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Unique identifier for an associated service. */ ServiceId: DevKit.WebApi.LookupValue; /** Choose the service level agreement (SLA) that you want to apply to the fax record. */ SLAId: DevKit.WebApi.LookupValue; /** Last SLA that was applied to this fax. This field is for internal use only. */ SLAInvokedId: DevKit.WebApi.LookupValueReadonly; SLAName: DevKit.WebApi.StringValueReadonly; /** Shows the date and time by which the activities are sorted. */ SortDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows the ID of the stage. */ StageId: DevKit.WebApi.GuidValue; /** Shows whether the fax activity is open, completed, or canceled. Completed and canceled fax activities are read-only and can't be edited. */ StateCode: DevKit.WebApi.OptionSetValue; /** Select the fax's status. */ StatusCode: DevKit.WebApi.OptionSetValue; /** Type a subcategory to identify the fax type to relate the activity to a specific product, sales region, business group, or other function. */ Subcategory: DevKit.WebApi.StringValue; /** Type a short description about the objective or primary topic of the fax. */ Subject: DevKit.WebApi.StringValue; /** For internal use only. */ SubscriptionId: DevKit.WebApi.GuidValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** For internal use only. */ TraversedPath: DevKit.WebApi.StringValue; /** Type the Transmitting Subscriber ID (TSID) associated with a send action. This is typically a combination of the recipient's fax or phone number and company name. */ Tsid: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version number of the fax. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; /** The array of object that can cast object to ActivityPartyApi class */ ActivityParties: Array<any>; } } declare namespace OptionSet { namespace Fax { enum PriorityCode { /** 2 */ High, /** 0 */ Low, /** 1 */ Normal } enum StateCode { /** 2 */ Canceled, /** 1 */ Completed, /** 0 */ Open } enum StatusCode { /** 5 */ Canceled, /** 2 */ Completed, /** 1 */ Open, /** 4 */ Received, /** 3 */ Sent } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Fax'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
* The parser for Human2Regex * @packageDocumentation */ import { EmbeddedActionsParser, IOrAlt, IToken } from "chevrotain"; import * as T from "./tokens"; import { CountSubStatementCST, UsingFlags, MatchSubStatementType, MatchSubStatementValue, MatchSubStatementCST, UsingStatementCST, RegularExpressionCST, StatementCST, RepeatStatementCST, MatchStatementValue, MatchStatementCST, GroupStatementCST, RegexDialect, BackrefStatementCST, GeneratorContext, IfPatternStatementCST, IfIdentStatementCST } from "./generator"; import { first, usefulConditional, CommonError } from "./utilities"; /** * The options for the Parser */ export class Human2RegexParserOptions { /** * Constructor for Human2RegexParserOptions * * @param skip_validations If true, the lexer will skip validations (~25% faster) */ constructor(public skip_validations: boolean = false) { /* empty */ } } class TokenAndValue<T> { constructor(public token: IToken, public value: T) { /* empty */ } } class TokensAndValue<T> { constructor(public tokens: IToken[], public value: T) { /* empty */ } } /** * Tokenization result */ export class ParseResult { /** * Constructor for the TokenizeResult * * @param tokens The token stream * @param errors A list of lexing errors */ public constructor(private regexp_cst: RegularExpressionCST, public errors: CommonError[]) { /* empty */ } /** * Validate that this is both valid and can be generated in the specified language * * @remarks There is no guarantee toRegex or toRegExp will work unless validate returns no errors * * @param language the regex dialect we're validating * @returns A list of errors * @public */ public validate(language: RegexDialect): CommonError[] { return this.regexp_cst.validate(language, new GeneratorContext()).map(CommonError.fromSemanticError); } /** * Generate a regular expression string based on the parse result * * @remarks There is no guarantee toRegex will work unless validate returns no errors * * @param language the regex dialect we're generating * @returns a regular expression string * @public */ public toRegex(language: RegexDialect): string { return this.regexp_cst.toRegex(language); } /** * Generate a RegExp object based on the parse result * * @remarks There is no guarantee toRegExp will work unless validate returns no errors * * @param language the regex dialect we're generating * @returns a RegExp object * @public */ public toRegExp(language: RegexDialect): RegExp { return new RegExp(this.regexp_cst.toRegex(language)); } } /** * The Parser class * * @remarks Only 1 parser instance allowed due to performance reasons */ export class Human2RegexParser extends EmbeddedActionsParser { private static already_init = false; private regexp: (idxInCallingRule?: number, ...args: unknown[]) => RegularExpressionCST; /** * Parses the token stream * * @param tokens Tokens to parse * @returns a parse result which contains the token stream and error list * @public */ public parse(tokens: IToken[]): ParseResult { this.input = tokens; return new ParseResult(this.regexp(), this.errors.map(CommonError.fromParseError)); } constructor(private options: Human2RegexParserOptions = new Human2RegexParserOptions()) { super(T.AllTokens, { recoveryEnabled: false, maxLookahead: 2, skipValidations: options.skip_validations }); if (Human2RegexParser.already_init) { throw new Error("Only 1 instance of Human2RegexParser allowed"); } Human2RegexParser.already_init = true; const $ = this; /** * IN REGARDS TO KEEPING TOKENS: * We don't really need to keep each token, only the first and last tokens * This is due to the fact we calculate the difference between those tokens * However, sometimes we have optional starts and ends * Each optional near the start and end MUST be recorded because they may be the first/last token * ex) "optional match 3..." the start token is "optional", but "match 3..."'s start token is "match" * */ // number rules let nss_rules: IOrAlt<TokenAndValue<number>>[] | null = null; const NumberSubStatement = $.RULE("NumberSubStatement", () => { return $.OR(nss_rules || (nss_rules = [ { ALT: () => new TokenAndValue($.CONSUME(T.Zero), 0) }, { ALT: () => new TokenAndValue($.CONSUME(T.One), 1) }, { ALT: () => new TokenAndValue($.CONSUME(T.Two), 2) }, { ALT: () => new TokenAndValue($.CONSUME(T.Three), 3) }, { ALT: () => new TokenAndValue($.CONSUME(T.Four), 4) }, { ALT: () => new TokenAndValue($.CONSUME(T.Five), 5) }, { ALT: () => new TokenAndValue($.CONSUME(T.Six), 6) }, { ALT: () => new TokenAndValue($.CONSUME(T.Seven), 7) }, { ALT: () => new TokenAndValue($.CONSUME(T.Eight), 8) }, { ALT: () => new TokenAndValue($.CONSUME(T.Nine), 9) }, { ALT: () => new TokenAndValue($.CONSUME(T.Ten), 10) }, { ALT: () => { const tok = $.CONSUME(T.NumberLiteral); return new TokenAndValue(tok, parseInt(tok.image)); }} ])); }); // 1, 1..2, between 1 and/to 2 inclusively/exclusively const CountSubStatement = $.RULE("CountSubStatement", () => { return $.OR([ // between 1 to 4 { ALT: () => { const tokens: IToken[] = []; tokens.push($.CONSUME(T.Between)); const from = $.SUBRULE4(NumberSubStatement); $.OR3([ { ALT: () => $.CONSUME2(T.To) }, { ALT: () => $.CONSUME(T.And) } ]); const to = $.SUBRULE5(NumberSubStatement); tokens.push(to.token); $.OPTION4(() => tokens.push($.CONSUME3(T.Times))); const opt = $.OPTION5(() => { return $.OR4([ { ALT: () => { tokens.push($.CONSUME(T.Inclusive)); return "inclusive"; }}, { ALT: () => { tokens.push($.CONSUME(T.Exclusive)); return "exclusive"; }} ]); }); return new CountSubStatementCST(tokens, from.value, to.value, opt as "inclusive" | "exclusive" | null); }}, // from 1 to 4 { ALT: () => { const tokens: IToken[] = []; $.OPTION2(() => tokens.push($.CONSUME(T.From))); const from = $.SUBRULE2(NumberSubStatement); const to = $.OR2([ { ALT: () => new TokenAndValue($.CONSUME(T.OrMore), [ null, "+" ]) }, { ALT: () => { $.CONSUME(T.To); const val = $.SUBRULE3(NumberSubStatement); let token = val.token; const opt = $.OPTION7(() => { return $.OR5([ { ALT: () => { token = $.CONSUME2(T.Inclusive); return "inclusive"; }}, { ALT: () => { token = $.CONSUME2(T.Exclusive); return "exclusive"; }} ]); }); return new TokenAndValue(token, [ val.value, opt ]); }} ]); tokens.push(to.token); $.OPTION3(() => tokens.push($.CONSUME2(T.Times))); return new CountSubStatementCST(tokens, from.value, to.value ? to.value[0] : null, to.value ? to.value[1] : null); }}, // exactly 2 { ALT: () => { const tokens: IToken[] = []; $.OPTION(() => tokens.push($.CONSUME(T.Exactly))); const from = $.SUBRULE(NumberSubStatement); tokens.push(from.token); $.OPTION6(() => tokens.push($.CONSUME(T.Times))); return new CountSubStatementCST(tokens, from.value); }} ]); }); // match sub rules let mss_rules: IOrAlt<{tokens: IToken[], statement: MatchSubStatementValue}>[] | null = null; const MatchSubStatement = $.RULE("MatchSubStatement", () => { let count: CountSubStatementCST | null = null; let invert: boolean = false; const values: MatchSubStatementValue[] = []; let from: string | null = null; let value: string | null = null; let to: string | null = null; let type: MatchSubStatementType = MatchSubStatementType.Anything; let tokens: IToken[] = []; count = $.OPTION(() => { const css = $.SUBRULE(CountSubStatement); if (usefulConditional(css.tokens, "due to how chevrotain works, the first run produces a null value")) { tokens.push(first(css.tokens)); } return css; }); invert = $.OPTION2(() => { tokens.push($.CONSUME(T.Not)); return true; }); $.AT_LEAST_ONE_SEP({ SEP: T.Or, DEF: () => { $.OPTION3(() => $.CONSUME(T.A)); const result = $.OR(mss_rules || (mss_rules = [ // range [a-z] { ALT: () => { const token0 = $.OPTION4(() => $.CONSUME(T.From)); const token1 = $.CONSUME2(T.StringLiteral); from = token1.image; $.CONSUME(T.To); const token2 = $.CONSUME3(T.StringLiteral); to = token2.image; type = MatchSubStatementType.Between; if (usefulConditional(token0, "Bug in type definition. Option should return <T|undefined>, but it doesn't")) { return { tokens: [ token0, token2 ], statement: new MatchSubStatementValue(type, from, to) }; } return { tokens: [ token1, token2 ], statement: new MatchSubStatementValue(type, from, to) }; }}, // range [a-z] { ALT: () => { const token1 = $.CONSUME(T.Between); from = $.CONSUME4(T.StringLiteral).image; $.CONSUME(T.And); const token2 = $.CONSUME5(T.StringLiteral); to = token2.image; type = MatchSubStatementType.Between; return { tokens: [ token1, token2 ], statement: new MatchSubStatementValue(type, from, to) }; }}, // exact string { ALT: () => { const token = $.CONSUME(T.StringLiteral); value = token.image; type = MatchSubStatementType.SingleString; return { tokens: [ token ], statement: new MatchSubStatementValue(type, value) }; }}, //unicode { ALT: () => { const token1 = $.CONSUME(T.Unicode); const token2 = $.CONSUME6(T.StringLiteral); value = token2.image; type = MatchSubStatementType.Unicode; return { tokens: [ token1, token2 ], statement: new MatchSubStatementValue(type, value) }; }}, { ALT: () => { const token = $.CONSUME(T.Anything); type = MatchSubStatementType.Anything; return { tokens: [ token ], statement: new MatchSubStatementValue(type) }; }}, { ALT: () => { const token = $.CONSUME(T.Boundary); type = MatchSubStatementType.Boundary; return { tokens: [ token ], statement: new MatchSubStatementValue(type) }; }}, { ALT: () => { const token = $.CONSUME(T.Word); type = MatchSubStatementType.Word; return { tokens: [ token ], statement: new MatchSubStatementValue(type) }; }}, { ALT: () => { const token = $.CONSUME(T.Digit); type = MatchSubStatementType.Digit; return { tokens: [ token ], statement: new MatchSubStatementValue(type) }; }}, { ALT: () => { const token = $.CONSUME(T.Character); type = MatchSubStatementType.Character; return { tokens: [ token ], statement: new MatchSubStatementValue(type) }; }}, { ALT: () => { const token = $.CONSUME(T.Letter); type = MatchSubStatementType.Letter; return { tokens: [ token ], statement: new MatchSubStatementValue(type) }; }}, { ALT: () => { const token = $.CONSUME(T.Decimal); type = MatchSubStatementType.Decimal; return { tokens: [ token ], statement: new MatchSubStatementValue(type) }; }}, { ALT: () => { const token = $.CONSUME(T.Integer); type = MatchSubStatementType.Integer; return { tokens: [ token ], statement: new MatchSubStatementValue(type) }; }}, { ALT: () => { const token = $.CONSUME(T.Whitespace); type = MatchSubStatementType.Whitespace; return { tokens: [ token ], statement: new MatchSubStatementValue(type) }; }}, { ALT: () => { const token = $.CONSUME(T.Number); type = MatchSubStatementType.Number; return { tokens: [ token ], statement: new MatchSubStatementValue(type) }; }}, { ALT: () => { const token = $.CONSUME(T.Tab); type = MatchSubStatementType.Tab; return { tokens: [ token ], statement: new MatchSubStatementValue(type) }; }}, { ALT: () => { const token = $.CONSUME(T.Linefeed); type = MatchSubStatementType.Linefeed; return { tokens: [ token ], statement: new MatchSubStatementValue(type) }; }}, { ALT: () => { const token = $.CONSUME(T.Newline); type = MatchSubStatementType.Newline; return { tokens: [ token ], statement: new MatchSubStatementValue(type) }; }}, { ALT: () => { const token = $.CONSUME(T.CarriageReturn); type = MatchSubStatementType.CarriageReturn; return { tokens: [ token ], statement: new MatchSubStatementValue(type) }; }}, ])); tokens = tokens.concat(result.tokens); values.push(result.statement); } }); return new MatchSubStatementCST(tokens, count, invert, values); }); // optionally match "+" then 1+ words const MatchStatement = $.RULE("MatchStatement", () => { let optional = false; let completely_optional = false; const msv: MatchStatementValue[] = []; const tokens: IToken[] = []; $.OPTION(() => { tokens.push($.CONSUME(T.Optional)); completely_optional = true; }); tokens.push($.CONSUME(T.Match)); $.OPTION4(() => { $.CONSUME3(T.Optional); optional = true; }); msv.push(new MatchStatementValue(optional, $.SUBRULE(MatchSubStatement))); $.MANY(() => { $.OR([ { ALT: () => { $.OPTION2(() => $.CONSUME2(T.And)); $.CONSUME(T.Then); }}, { ALT: () => $.CONSUME(T.And) }, ]); optional = false; $.OPTION3(() => { $.CONSUME2(T.Optional); optional = true; }); msv.push(new MatchStatementValue(optional, $.SUBRULE2(MatchSubStatement))); }); tokens.push($.CONSUME(T.EndOfLine)); return new MatchStatementCST(tokens, completely_optional, msv); }); // using global matching let us_rules: IOrAlt<UsingFlags>[] | null = null; const UsingStatement = $.RULE("UsingStatement", () => { const usings: UsingFlags[] = []; const tokens = [ $.CONSUME(T.Using) ]; $.AT_LEAST_ONE_SEP({ SEP: T.And, DEF: () => { usings.push($.OR(us_rules || (us_rules = [ { ALT: () => { $.CONSUME(T.Multiline); return UsingFlags.Multiline; }}, { ALT: () => { $.CONSUME(T.Global); return UsingFlags.Global; }}, { ALT: () => { $.CONSUME(T.CaseInsensitive); return UsingFlags.Insensitive; }}, { ALT: () => { $.CONSUME(T.CaseSensitive); return UsingFlags.Sensitive; }}, { ALT: () => { $.CONSUME(T.Exact); return UsingFlags.Exact; }} ]))); $.OPTION(() => $.CONSUME(T.Matching)); } }); tokens.push($.CONSUME(T.EndOfLine)); return new TokensAndValue(tokens, usings); }); // group rules const GroupStatement = $.RULE("GroupStatement", () => { const tokens: IToken[] = []; let optional = false; let name: string | null = null; const statement: StatementCST[] = []; // position of optional must be OR'd because // otherwise it could appear twice // ex) optional? create an optional? group $.OPTION4(() => { tokens.push($.OR3([ { ALT: () => { optional = true; const first_token = $.CONSUME(T.Optional); $.CONSUME(T.Create); $.CONSUME(T.A); return first_token; }}, { ALT: () => { const first_token = $.CONSUME2(T.Create); $.CONSUME2(T.A); $.OPTION2(() => { $.CONSUME2(T.Optional); optional = true; }); return first_token; }}, { ALT: () => { optional = true; return $.CONSUME3(T.Optional); }} ])); }); tokens.push($.CONSUME(T.Group)); $.OPTION5(() => { name = $.OR([ { ALT: () => { $.CONSUME(T.Called); const n = $.CONSUME(T.Identifier).image; $.OPTION(() => $.CONSUME(T.Is)); return n; }}, { ALT: () => { const n = $.CONSUME2(T.Identifier).image; $.CONSUME2(T.Is); return n; }}, ]); }); // Note: Technically not the end token, // BUT this is way more useful than the Outdent for error reporting tokens.push($.CONSUME2(T.EndOfLine)); $.CONSUME(T.Indent); $.AT_LEAST_ONE(() => { statement.push($.SUBRULE(Statement)); }); $.CONSUME(T.Outdent); return new GroupStatementCST(tokens, optional, name, statement); }); // repeat rules const RepeatStatement = $.RULE("RepeatStatement", () => { const tokens: IToken[] = []; let optional = false; let count: CountSubStatementCST | null = null; const statements: StatementCST[] = []; $.OPTION3(() => { tokens.push($.CONSUME(T.Optional)); optional = true; }); tokens.push($.CONSUME(T.Repeat)); $.OPTION(() => count = $.SUBRULE(CountSubStatement)); $.CONSUME3(T.EndOfLine); $.CONSUME(T.Indent); $.AT_LEAST_ONE(() => { statements.push($.SUBRULE(Statement)); }); tokens.push($.CONSUME(T.Outdent)); return new RepeatStatementCST(tokens, optional, count, statements); }); const BackrefStatement = $.RULE("BackrefStatement", () => { const tokens: IToken[] = []; let optional = false; let count: CountSubStatementCST | null = null; $.OPTION5(() => { tokens.push($.CONSUME(T.Optional)); optional = true; }); tokens.push($.CONSUME(T.Rerun)); $.OPTION6(() => count = $.SUBRULE(CountSubStatement)); $.OPTION7(() => { $.OPTION(() => $.CONSUME(T.The)); $.CONSUME(T.Group); $.OPTION2(() => $.CONSUME(T.Called)); }); const name = $.CONSUME(T.Identifier).image; tokens.push($.CONSUME4(T.EndOfLine)); return new BackrefStatementCST(tokens, optional, count, name); }); const IfStatement = $.RULE("IfStatement", () => { const tokens: IToken[] = []; const msv: MatchStatementValue[] = []; let optional = false; const true_statements: StatementCST[] = []; const false_statements: StatementCST[] = []; let name: string = ""; tokens.push($.CONSUME(T.If)); $.OR2([ {ALT: () => { name = $.CONSUME(T.Identifier).image; }}, {ALT: () => { $.CONSUME(T.Match); $.OPTION4(() => { $.CONSUME3(T.Optional); optional = true; }); msv.push(new MatchStatementValue(optional, $.SUBRULE(MatchSubStatement))); $.MANY(() => { $.OR([ { ALT: () => { $.OPTION2(() => $.CONSUME2(T.And)); $.CONSUME(T.Then); }}, { ALT: () => $.CONSUME(T.And) }, ]); optional = false; $.OPTION3(() => { $.CONSUME2(T.Optional); optional = true; }); msv.push(new MatchStatementValue(optional, $.SUBRULE2(MatchSubStatement))); }); }} ]); tokens.push($.CONSUME3(T.EndOfLine)); $.CONSUME2(T.Indent); $.AT_LEAST_ONE2(() => { true_statements.push($.SUBRULE(Statement)); }); $.CONSUME2(T.Outdent); $.OPTION(() => { $.CONSUME(T.Else); $.CONSUME4(T.EndOfLine); $.CONSUME3(T.Indent); $.AT_LEAST_ONE3(() => { false_statements.push($.SUBRULE2(Statement)); }); $.CONSUME3(T.Outdent); }); if (name === "") { return new IfPatternStatementCST(tokens, msv, true_statements, false_statements); } else { return new IfIdentStatementCST(tokens, name, true_statements, false_statements); } }); // statement super class const Statement = $.RULE("Statement", () => { return $.OR([ { ALT: () => $.SUBRULE(MatchStatement) }, { ALT: () => $.SUBRULE(GroupStatement) }, { ALT: () => $.SUBRULE(RepeatStatement) }, { ALT: () => $.SUBRULE(BackrefStatement) }, { ALT: () => $.SUBRULE(IfStatement) } ]); }); // full regex const Regex = $.RULE("Regex", () => { let tokens: IToken[] = []; let usings: UsingFlags[] = []; const statements: StatementCST[] = []; $.MANY(() => { const using = $.SUBRULE(UsingStatement); tokens = tokens.concat(using.tokens); usings = usings.concat(using.value); }); $.MANY2(() => statements.push($.SUBRULE(Statement)) ); return new RegularExpressionCST([], new UsingStatementCST(tokens, usings), statements); }); this.performSelfAnalysis(); this.regexp = Regex; } /** * Sets the options for this parser * * @param options options for the parser * @see Human2RegexParserOptions * @public */ public setOptions(options: Human2RegexParserOptions): void { throw new Error("skip_validations is not valid to change once we've already initialized"); } }
the_stack
import type { BabelFileResult, PluginObj } from "@babel/core"; import * as babel from "@babel/standalone"; import type { ExportDeclaration, Expression, ExpressionStatement, Identifier, ImportDeclaration, Program, SpreadElement, Statement, StringLiteral, } from "@babel/types"; import type { SyntaxNode, Tree } from "@lezer/common"; import { Either, isLeft, left, right } from "@nota-lang/nota-common/dist/either.js"; import { assert, unreachable } from "@nota-lang/nota-common"; import _ from "lodash"; import type React from "react"; import * as t from "./babel-polyfill.js"; import { INTRINSIC_ELEMENTS } from "./intrinsic-elements.js"; //@ts-ignore import * as terms from "./nota.grammar.terms.js"; //@ts-ignore import COMPONENTS from "./components.js"; export let matches = (node: SyntaxNode, term: number): boolean => node.type.id == term; let matchesNewline = (node: SyntaxNode): boolean => matches(node, terms.NotaNewline); /*|| matches(node, terms.Multinewline)*/ export class Translator { input: string; imports: Set<ImportDeclaration> = new Set(); exports: Set<ExportDeclaration> = new Set(); constructor(input: string) { this.input = input; } text(cursor: SyntaxNode): string { return this.input.slice(cursor.from, cursor.to); } translateTextbody(node: SyntaxNode): Expression { assert(matches(node, terms.TextBody)); let tokens = node.getChildren(terms.TextToken); // Remove whitespace on the last line let last = _.last(tokens); if (last && matches(last.firstChild!, terms.Text)) { let s = this.text(last); if (s.match(/^[\s]*$/)) { tokens.pop(); } } // Remove leading whitespace let lineStarts = tokens .map((_t, i) => i) .filter(i => { let lineStart = i > 0 && matchesNewline(tokens[i - 1].firstChild!); return lineStart && matches(tokens[i].firstChild!, terms.Text); }); let minLeadingWhitespace = lineStarts.length > 0 ? lineStarts .map(i => { let s = this.text(tokens[i]); return s.match(/^( )*/)![0].length; }) .reduce((a, b) => Math.min(a, b)) : 0; let output: Either<Expression, Array<Statement>>[] = []; tokens.forEach((token, i) => { if (lineStarts.includes(i)) { let stripped = this.text(token).slice(minLeadingWhitespace); if (stripped.length > 0) { output.push(left(processText(stripped))); } } else if (matchesNewline(token.firstChild!) && (i == 0 || i == tokens.length - 1)) { // pass } else { output.push(this.translateToken(token)); } }); let array: (Expression | SpreadElement)[] = []; let curArray = array; output.forEach(result => { if (isLeft(result)) { curArray.push(result.value); } else { let newArray: (Expression | SpreadElement)[] = []; let body = t.blockStatement([ ...result.value, t.returnStatement(t.arrayExpression(newArray)), ]); let fn = t.spreadElement(t.callExpression(t.arrowFunctionExpression([], body), [])); curArray.push(fn); curArray = newArray; } }); return t.arrayExpression(array); } translateToken(node: SyntaxNode): TranslatedToken { assert(matches(node, terms.TextToken)); let child = node.firstChild!; if (matches(child, terms.Command)) { return this.translateCommand(child); } else if (matches(child, terms.Text)) { return left(processText(this.text(child))); } else if (matches(child, terms.NotaNewline)) { return left(t.stringLiteral("\n")); } /*else if (matches(child, terms.Multinewline)) { return left(t.stringLiteral("\n\n")); }*/ else { throw `Unhandled child type ${child.name}`; } } translateCommand(node: SyntaxNode): TranslatedToken { assert(matches(node, terms.Command)); let child = node.firstChild!; if (matches(child, terms.PctCommand)) { return right(this.translatePctcommand(child)); } else if (matches(child, terms.HashCommand)) { return left(this.translateHashcommand(child)); } else if (matches(child, terms.AtCommand)) { return left(this.translateAtcommand(child)); } else { unreachable(); } } translateCommandName(node: SyntaxNode): Expression { assert(matches(node, terms.CommandName)); if (node.getChild(terms.VariableName)) { let nameStr = this.text(node.getChild(terms.VariableName)!); return t.identifier(nameStr); } else if (node.getChild(terms.Number)) { let n = parseInt(this.text(node.getChild(terms.Number)!)); return t.memberExpression(argumentsId, t.numericLiteral(n)); } else if (node.getChild(terms.NotaExpression)) { return this.translateJs(node.getChild(terms.NotaExpression)!); } else { unreachable(); } } translateArgText(node: SyntaxNode): Expression { assert(matches(node, terms.ArgText)); let child = node.firstChild!; if (matches(child, terms.TextBody)) { return this.translateTextbody(child); } else if (matches(child, terms.VerbatimText)) { return t.arrayExpression([t.stringLiteral(this.text(child))]); } else { throw `Unknown ArgText ${child.name}`; } } translateIdent(node: SyntaxNode): Identifier { assert(matches(node, terms.VariableName)); return t.identifier(this.text(node)); } translateAtcommand(node: SyntaxNode): Expression { assert(matches(node, terms.AtCommand)); let nameNode, nameExpr; if ((nameNode = node.getChild(terms.CommandName))) { nameExpr = this.translateCommandName(nameNode); if (nameExpr.type == "Identifier" && INTRINSIC_ELEMENTS.has(nameExpr.name)) { nameExpr = t.stringLiteral(nameExpr.name); } } else { return t.arrayExpression( node.getChildren(terms.ArgText).map(arg => this.translateArgText(arg)) ); } let codeArgs: [Expression, Expression][] = node.getChildren(terms.ArgCodeNamed).map(node => { let ident = node.getChild(terms.VariableName)!; let js = node.getChild(terms.NotaExpression); return [this.translateIdent(ident), js ? this.translateJs(js) : t.booleanLiteral(true)]; }); let textArgs = node .getChildren(terms.ArgText) .map(arg => t.spreadElement(this.translateArgText(arg))); return toReact(nameExpr, codeArgs, textArgs); } translateArg(arg: SyntaxNode): Expression { if (matches(arg, terms.ArgCodeAnon)) { return this.translateJs(arg.getChild(terms.NotaExpression)!); } else if (matches(arg, terms.ArgText)) { return this.translateArgText(arg); } else { unreachable(); } } translateHashcommand(node: SyntaxNode): Expression { assert(matches(node, terms.HashCommand)); let name = node.getChild(terms.CommandName)!; let nameExpr = this.translateCommandName(name); let args = collectArgs(name.nextSibling).map(arg => this.translateArg(arg)); return args.length == 0 ? nameExpr : t.callExpression(nameExpr, args); } translatePctcommand(node: SyntaxNode): Array<Statement> { assert(matches(node, terms.PctCommand)); let stmts = parse(this.replaceNotaCalls(node.getChild(terms.NotaStatement)!)); return stmts.filter(stmt => { if (stmt.type == "ImportDeclaration") { this.imports.add(stmt); return false; } else if (stmt.type == "ExportNamedDeclaration") { this.exports.add(stmt); return false; } else { return true; } }); } translateJs(node: SyntaxNode): Expression { assert(matches(node, terms.NotaExpression)); return parseExpr(this.replaceNotaCalls(node)); } replaceNotaCalls(node: SyntaxNode): string { let cursor = node.cursor(); let replacements: [number, number, string][] = []; while (node.from <= cursor.from && cursor.to <= node.to) { if (matches(cursor.node, terms.AtCommand)) { let expr = this.translateAtcommand(cursor.node); let result = babel.transformFromAst( t.program([t.expressionStatement(expr)]), undefined, {} ) as any as BabelFileResult; let code = result.code!.slice(0, -1); replacements.push([cursor.from - node.from, cursor.to - node.from, code]); if (!cursor.next(false)) { break; } } else if (!cursor.next()) { break; } } let code = this.text(node); replacements = _.sortBy(replacements, [0]); let expanded = ""; let i = 0; replacements.forEach(([from, to, expr]) => { expanded += code.slice(i, from); expanded += expr; i = to; }); expanded += code.slice(i); return expanded; } } let fragment = t.identifier("Fragment"); let createEl = t.identifier("el"); let argumentsId = t.identifier("args"); let toReact = ( name: Expression, props: ([Expression, Expression] | SpreadElement)[], children: (Expression | SpreadElement)[] ): Expression => { let args: (Expression | SpreadElement)[] = [ name, t.objectExpression(props.map(p => (p instanceof Array ? t.objectProperty(p[0], p[1]) : p))), ]; return t.callExpression(createEl, args.concat(children)); }; export type TranslatedFunction = ( _symbols: { [key: string]: any }, _imports: { [path: string]: any } ) => React.ReactElement; export interface Translation { js: string; imports: Set<string>; } export let optimizePlugin = (): PluginObj => ({ visitor: { ArrayExpression(path) { // [...[e1, e2]] => [e1, e2] path.node.elements = path.node.elements .map(el => { if (el && el.type == "SpreadElement" && el.argument.type == "ArrayExpression") { return el.argument.elements; } else { return [el]; } }) .flat(); }, ObjectExpression(path) { let props = path.node.properties; /// {...e} => e if (props.length == 1 && props[0].type == "SpreadElement") { path.replaceWith(props[0].argument); } }, CallExpression(path) { let expr = path.node; if ( expr.arguments.length == 0 && expr.arguments.length == 0 && expr.callee.type == "ArrowFunctionExpression" && expr.callee.body.type == "BlockStatement" && expr.callee.body.body.length == 1 && expr.callee.body.body[0].type == "ReturnStatement" && expr.callee.body.body[0].argument ) { // `(() => { return e; })()` => `e` path.replaceWith(expr.callee.body.body[0].argument); path.visit(); } else { path.node.arguments = path.node.arguments .map(arg => { // f(...[x, y]) => f(x, y) if (arg.type == "SpreadElement" && arg.argument.type == "ArrayExpression") { return arg.argument.elements.map(el => el!); } else { return [arg]; } }) .flat(); } }, }, }); let parse = (code: string): Statement[] => { let result = babel.transform(code, { ast: true, }) as any as BabelFileResult; return result.ast!.program.body; }; export let parseExpr = (code: string): Expression => { let s = parse(`(${code});`)[0] as ExpressionStatement; return s.expression; }; export let lambda = (body: Expression) => t.arrowFunctionExpression([t.restElement(argumentsId)], body); export let translateAst = (input: string, tree: Tree): Program => { let node = tree.topNode; assert(matches(node, terms.Document)); let translator = new Translator(input); let docBody = translator.translateTextbody(node.getChild(terms.TextBody)!); let docProps = t.identifier("docProps"); let doc = toReact( t.identifier("Document"), [t.spreadElement(docProps)], [t.spreadElement(docBody)] ); let prelude: { [k: string]: string } = COMPONENTS; let usedPrelude: Set<string> = new Set(); t.traverse(doc, node => { if (node.type == "Identifier" && node.name in prelude) { usedPrelude.add(node.name); } }); let preludeImports: { [k: string]: string[] } = {}; for (let k of usedPrelude) { let path = prelude[k]; if (!(path in preludeImports)) { preludeImports[path] = []; } preludeImports[path].push(k); } let createElLong = t.identifier("createElement"); let observer = t.identifier("observer"); let program: Statement[] = [ t.importDeclaration( [t.importSpecifier(createEl, createElLong), t.importSpecifier(fragment, fragment)], t.stringLiteral("react") ), t.importDeclaration([t.importSpecifier(observer, observer)], t.stringLiteral("mobx-react")), t.importDeclaration( Object.keys(preludeImports).map(mod => t.importSpecifier(t.identifier(mod), t.identifier(mod)) ), t.stringLiteral("@nota-lang/nota-components") ), ..._.toPairs(preludeImports).map(([mod, ks]) => t.variableDeclaration("const", [ t.variableDeclarator( t.objectPattern(ks.map(k => t.objectProperty(t.identifier(k), t.identifier(k), true))), t.identifier(mod) ), ]) ), // ..._.toPairs(preludeImports).map(([path, ks]) => // t.importDeclaration( // ks.map(k => t.importSpecifier(t.identifier(k), t.identifier(k))), // t.stringLiteral(path) // ), // ), ...Array.from(translator.imports), ...Array.from(translator.exports), t.exportDefaultDeclaration( t.callExpression(observer, [t.arrowFunctionExpression([docProps], doc)]) ), ]; return t.program(program); }; export let translate = (input: string, tree: Tree): string => { let program = translateAst(input, tree); let result = babel.transformFromAst(program, undefined, { plugins: [optimizePlugin], }) as any as BabelFileResult; let js = result.code!; return js; }; type TranslatedToken = Either<Expression, Array<Statement>>; let processText = (text: string): StringLiteral => { return t.stringLiteral( text .replace(/\\%/g, "%") .replace(/\\\[/g, "[") .replace(/\\\]/g, "]") .replace(/\\@/g, "@") .replace(/\\#/g, "#") .replace(/---/g, "—") ); }; let collectArgs = (arg: SyntaxNode | null): SyntaxNode[] => { let args = []; while (arg != null) { args.push(arg); arg = arg.nextSibling; } return args; };
the_stack
import * as THREE from "three"; import CameraControl from "./CameraControl"; import Motion from "./Motion"; import View3DError from "~/View3DError"; import Camera from "~/core/camera/Camera"; import { getElement } from "~/utils"; import { EVENTS, MOUSE_BUTTON } from "~/consts/event"; import { CURSOR } from "~/consts/css"; import * as DEFAULT from "~/consts/default"; import * as ERROR from "~/consts/error"; import { ValueOf } from "~/types/internal"; /** * Model's translation control that supports both mouse & touch * @category Controls */ class TranslateControl implements CameraControl { // Options private _useGrabCursor: boolean; private _scaleToElement: boolean; private _userScale: THREE.Vector2; // Internal values private _targetEl: HTMLElement | null = null; private _enabled: boolean = false; // Sometimes, touchstart for second finger doesn't triggered. // This flag checks whether that happened private _touchInitialized: boolean = false; private _xMotion: Motion; private _yMotion: Motion; private _prevPos: THREE.Vector2 = new THREE.Vector2(0, 0); private _screenSize: THREE.Vector2 = new THREE.Vector2(0, 0); /** * Control's current target element to attach event listeners * @readonly */ public get element() { return this._targetEl; } /** * Scale factor for translation * @type THREE.Vector2 * @see https://threejs.org/docs/#api/en/math/Vector2 * @example * import { TranslateControl } from "@egjs/view3d"; * const translateControl = new TranslateControl(); * translateControl.scale.set(2, 2); */ public get scale() { return this._userScale; } /** * Whether to apply CSS style `cursor: grab` on the target element or not * @default true * @example * import { TranslateControl } from "@egjs/view3d"; * const translateControl = new TranslateControl(); * translateControl.useGrabCursor = true; */ public get useGrabCursor() { return this._useGrabCursor; } /** * Scale control to fit element size. * When this is true, camera's pivot change will correspond same amount you've dragged. * @default true * @example * import View3D, { TranslateControl } from "@egjs/view3d"; * const view3d = new View3D("#view3d-canvas"); * const translateControl = new TranslateControl(); * translateControl.scaleToElement = true; * view3d.controller.add(translateControl); * view3d.resize(); */ public get scaleToElement() { return this._scaleToElement; } /** * Whether this control is enabled or not * @readonly */ public get enabled() { return this._enabled; } public set scale(val: THREE.Vector2) { this._userScale.copy(val); } public set useGrabCursor(val: boolean) { if (!val) { this._setCursor(""); this._useGrabCursor = false; } else { this._useGrabCursor = true; this._setCursor(CURSOR.GRAB); } } public set scaleToElement(val: boolean) { this._scaleToElement = val; } /** * Create new TranslateControl instance * @param {object} options Options * @param {HTMLElement | null} [options.element] Target element. * @param {function} [options.easing=(x: number) => 1 - Math.pow(1 - x, 3)] Motion's easing function. * @param {THREE.Vector2} [options.scale=new THREE.Vector2(1, 1)] Scale factor for translation. * @param {boolean} [options.useGrabCursor=true] Whether to apply CSS style `cursor: grab` on the target element or not. * @param {boolean} [options.scaleToElement=true] Whether to scale control to fit element size. * @tutorial Adding Controls */ constructor({ element = DEFAULT.NULL_ELEMENT, easing = DEFAULT.EASING, scale = new THREE.Vector2(1, 1), useGrabCursor = true, scaleToElement = true, } = {}) { const targetEl = getElement(element); if (targetEl) { this.setElement(targetEl); } this._xMotion = new Motion({ duration: 0, range: DEFAULT.INFINITE_RANGE, easing }); this._yMotion = new Motion({ duration: 0, range: DEFAULT.INFINITE_RANGE, easing }); this._userScale = scale; this._useGrabCursor = useGrabCursor; this._scaleToElement = scaleToElement; } /** * Destroy the instance and remove all event listeners attached * This also will reset CSS cursor to intial * @returns {void} Nothing */ public destroy(): void { this.disable(); } /** * Update control by given deltaTime * @param deltaTime Number of milisec to update * @returns {void} Nothing */ public update(camera: Camera, deltaTime: number): void { const screenSize = this._screenSize; const delta = new THREE.Vector2( this._xMotion.update(deltaTime), this._yMotion.update(deltaTime), ); const viewXDir = new THREE.Vector3(1, 0, 0).applyQuaternion(camera.threeCamera.quaternion); const viewYDir = new THREE.Vector3(0, 1, 0).applyQuaternion(camera.threeCamera.quaternion); if (this._scaleToElement) { const screenScale = new THREE.Vector2(camera.renderWidth, camera.renderHeight).divide(screenSize); delta.multiply(screenScale); } camera.pivot.add(viewXDir.multiplyScalar(delta.x)); camera.pivot.add(viewYDir.multiplyScalar(delta.y)); } /** * Resize control to match target size * This method is only meaningful when {@link RotateControl#scaleToElementSize scaleToElementSize} is enabled * @param size {@link https://threejs.org/docs/#api/en/math/Vector2 THREE.Vector2} instance of width(x), height(y) */ public resize(size: THREE.Vector2) { const screenSize = this._screenSize; screenSize.copy(size); } /** * Enable this input and add event listeners * @returns {void} Nothing */ public enable(): void { if (this._enabled) return; if (!this._targetEl) { throw new View3DError(ERROR.MESSAGES.ADD_CONTROL_FIRST, ERROR.CODES.ADD_CONTROL_FIRST); } const targetEl = this._targetEl; targetEl.addEventListener(EVENTS.MOUSE_DOWN, this._onMouseDown, false); targetEl.addEventListener(EVENTS.TOUCH_START, this._onTouchStart, false); targetEl.addEventListener(EVENTS.TOUCH_MOVE, this._onTouchMove, false); targetEl.addEventListener(EVENTS.TOUCH_END, this._onTouchEnd, false); targetEl.addEventListener(EVENTS.CONTEXT_MENU, this._onContextMenu, false); this._enabled = true; this._setCursor(CURSOR.GRAB); } /** * Disable this input and remove all event handlers * @returns {void} Nothing */ public disable(): void { if (!this._enabled || !this._targetEl) return; const targetEl = this._targetEl; targetEl.removeEventListener(EVENTS.MOUSE_DOWN, this._onMouseDown, false); window.removeEventListener(EVENTS.MOUSE_MOVE, this._onMouseMove, false); window.removeEventListener(EVENTS.MOUSE_UP, this._onMouseUp, false); targetEl.removeEventListener(EVENTS.TOUCH_START, this._onTouchStart, false); targetEl.removeEventListener(EVENTS.TOUCH_MOVE, this._onTouchMove, false); targetEl.removeEventListener(EVENTS.TOUCH_END, this._onTouchEnd, false); targetEl.removeEventListener(EVENTS.CONTEXT_MENU, this._onContextMenu, false); this._setCursor(""); this._enabled = false; } /** * Synchronize this control's state to given camera position * @param camera Camera to match state * @returns {void} Nothing */ public sync(camera: Camera): void { this._xMotion.reset(0); this._yMotion.reset(0); } /** * Set target element to attach event listener * @param element target element * @returns {void} Nothing */ public setElement(element: HTMLElement): void { this._targetEl = element; this.resize(new THREE.Vector2(element.offsetWidth, element.offsetHeight)); } private _setCursor(val: ValueOf<typeof CURSOR> | "") { const targetEl = this._targetEl; if (!this._useGrabCursor || !targetEl || !this._enabled) return; targetEl.style.cursor = val; } private _onMouseDown = (evt: MouseEvent) => { if (evt.button !== MOUSE_BUTTON.RIGHT) return; const targetEl = this._targetEl!; evt.preventDefault(); targetEl.focus ? targetEl.focus() : window.focus(); this._prevPos.set(evt.clientX, evt.clientY); window.addEventListener(EVENTS.MOUSE_MOVE, this._onMouseMove, false); window.addEventListener(EVENTS.MOUSE_UP, this._onMouseUp, false); this._setCursor(CURSOR.GRABBING); } private _onMouseMove = (evt: MouseEvent) => { evt.preventDefault(); const prevPos = this._prevPos; const delta = new THREE.Vector2(evt.clientX, evt.clientY) .sub(prevPos) .multiply(this._userScale); // X value is negated to match cursor direction this._xMotion.setEndDelta(-delta.x); this._yMotion.setEndDelta(delta.y); prevPos.set(evt.clientX, evt.clientY); } private _onMouseUp = () => { this._prevPos.set(0, 0); window.removeEventListener(EVENTS.MOUSE_MOVE, this._onMouseMove, false); window.removeEventListener(EVENTS.MOUSE_UP, this._onMouseUp, false); this._setCursor(CURSOR.GRAB); } private _onTouchStart = (evt: TouchEvent) => { // Only the two finger motion should be considered if (evt.touches.length !== 2) return; evt.preventDefault(); this._prevPos.copy(this._getTouchesMiddle(evt.touches)); this._touchInitialized = true; } private _onTouchMove = (evt: TouchEvent) => { // Only the two finger motion should be considered if (evt.touches.length !== 2) return; if (evt.cancelable !== false) { evt.preventDefault(); } evt.stopPropagation(); const prevPos = this._prevPos; const middlePoint = this._getTouchesMiddle(evt.touches); if (!this._touchInitialized) { prevPos.copy(middlePoint); this._touchInitialized = true; return; } const delta = new THREE.Vector2() .subVectors(middlePoint, prevPos) .multiply(this._userScale); // X value is negated to match cursor direction this._xMotion.setEndDelta(-delta.x); this._yMotion.setEndDelta(delta.y); prevPos.copy(middlePoint); } private _onTouchEnd = (evt: TouchEvent) => { // Only the two finger motion should be considered if (evt.touches.length !== 2) { this._touchInitialized = false; return; } // Three fingers to two fingers this._prevPos.copy(this._getTouchesMiddle(evt.touches)); this._touchInitialized = true; } private _getTouchesMiddle(touches: TouchEvent["touches"]): THREE.Vector2 { return new THREE.Vector2( touches[0].clientX + touches[1].clientX, touches[0].clientY + touches[1].clientY, ).multiplyScalar(0.5); } private _onContextMenu = (evt: MouseEvent) => { evt.preventDefault(); } } export default TranslateControl;
the_stack
declare var describe: any; import { folderBasedTest, testParseToken } from './TestHelpers'; import { expect } from 'chai'; import { ParsingContext } from '../dist/compiler/ParsingContext'; import { printAST } from '../dist/utils/astPrinter'; import { nodeSystem } from '../dist/support/NodeSystem'; import { printErrors } from '../dist/utils/errorPrinter'; describe('Parser', () => { const phases = function (txt: string, fileName: string) { const parsingContext = new ParsingContext(nodeSystem); parsingContext.paths.push(nodeSystem.resolvePath(__dirname, '../stdlib')); const moduleName = parsingContext.getModuleFQNForFile(fileName); parsingContext.invalidateModule(moduleName); return { document: parsingContext.getParsingPhaseForContent(fileName, moduleName, txt), parsingContext, }; }; describe('Failing examples', () => { folderBasedTest( '**/parser-error/*.lys', phases, async (result, e) => { if (!e && result && result.parsingContext.messageCollector.errors.length == 0) { throw new Error('The test did not fail'); } if (!result && e) { throw e; } if (!result) throw new Error('No result'); return printErrors(result.parsingContext, true); }, '.txt', true ); }); let testCount = 0; function getFileName() { return `tests/parser_tests_${testCount++}.lys`; } describe('Basic sanity tests', function () { function test(literals: any, ...placeholders: any[]) { let result = ''; // interleave the literals with the placeholders for (let i = 0; i < placeholders.length; i++) { result += literals[i]; result += placeholders[i]; } // add the last literal result += literals[literals.length - 1]; testParseToken(result, getFileName(),async () => void 0, phases); } function testEquivalence(a: string, b: string) { let aDocument: ReturnType<typeof phases> | null = null; testParseToken( a, getFileName(), async (doc, err) => { if (err) throw err; if (!doc) throw new Error('No result'); aDocument = doc; }, phases ); testParseToken( b, getFileName(), async (doc, err) => { if (err) throw err; if (!doc) throw new Error('No result'); expect(printAST(aDocument!.document)).to.eq(printAST(doc.document)); }, phases ); } describe('suffix', () => { test` var a = 1 var a = 0x1 var a = 0.123 var a = 0.1E-12 var a = 1_u32 var a = 0xfefaU `; }); describe('index', () => { test` var a = a[1] var a = a[a[0] + 2] var a = { x[1] = 3 } `; }); describe('operator precedence', () => { testEquivalence(`val z = (HEAP_BASE + AL_MASK) & ~AL_MASK`, `val z = (HEAP_BASE + AL_MASK) & (~AL_MASK)`); testEquivalence(`val z = newPtr > pagesBefore << 16`, `val z = newPtr > (pagesBefore << 16)`); testEquivalence( `var x = if (a) 1 else match b { else -> 1 }`, `var x = ( if(a) (1) else (match (b) { else -> 1 }) )` ); testEquivalence( `var x = a | b ^ c & d | e || f && g || h && y && j & 5`, `var x = (a | (b ^ (c & d)) | e) || (f && g) || (h && y && (j & 5))` ); testEquivalence(`var x = a[-1]`, `var x = (a)[-1]`); testEquivalence(`var x = a.b.c.d[-1]`, `var x = (a.b.c.d)[-1]`); testEquivalence(`var x = a.b.c.d()[-1]`, `var x = (a.b.c.d())[-1]`); testEquivalence(`var x = a.b.c().d()[-1]`, `var x = ((((a).b).c()).d())[-1]`); testEquivalence(`var x = {a[1] = -1}`, `var x = {((a)[1]) = (-1)}`); testEquivalence(`var x = a ~= b !== c == b === c`, `var x = ((((a ~= b) !== c) == b) === c)`); testEquivalence(`var x = a as int`, `var x = (a) as int`); testEquivalence(`var x = a - -1`, `var x = (a) - (-(1))`); testEquivalence(`var x = a is int`, `var x = (a) is int`); testEquivalence(`var x = -1 as int`, `var x = (-1) as int`); testEquivalence(`var x = -1 is int`, `var x = (-(1)) is int`); testEquivalence(`var x = -a as int`, `var x = (-a) as int`); testEquivalence(`var x = -a as int`, `var x = (-(a)) as int`); testEquivalence(`var x = ~a as int`, `var x = (~a) as int`); testEquivalence(`var x = ~a is int`, `var x = (~(a)) is int`); testEquivalence(`var x = 123 + a as int`, `var x = 123 + (a as int)`); testEquivalence(`var x = 123 + a is int`, `var x = 123 + (a is int)`); testEquivalence(`var x = 1 + 2`, `var x = (1 + 2)`); testEquivalence(`var x = 1 + 2 * 3`, `var x = (1 + (2 * 3))`); testEquivalence(`var x = 1 + 2 * 3 - 4`, `var x = (1 + (2 * 3)) - 4`); testEquivalence(`var x = 1 + 2 * 3 - 4 / 5`, `var x = (1 + (2 * 3)) - (4 / 5)`); testEquivalence(`var x = 1 + 2 * 3 - 4 / 5`, `var x = (1 + (2 * 3)) - (4 / 5)`); testEquivalence(`var x = -test.a().b()`, `var x = -((test.a()).b())`); testEquivalence(`var x = -test.a() - 3`, `var x = (-(test.a())) - 3`); testEquivalence(`var x = ~test.a() - 3`, `var x = (~(test.a())) - 3`); testEquivalence(`var x = ~test - 3`, `var x = (~test) - 3`); testEquivalence(`var x = 1 - -test - 3`, `var x = (1 - (-test)) - 3`); testEquivalence(`var x = a.b.c.d.e + 1 * 3`, `var x = (a.b.c.d.e + (1 * 3))`); testEquivalence( `var x = color.r * (2^16) | color.g * (2^8) | color.b`, `var x = (((color.r) * (2^16)) | ((color.g) * (2^8)) | (color.b))` ); testEquivalence( `var x = r * (2^16) | g * (2^8) | b `, `var x = ((r * (2^16)) | (g * (2^8)) | b) ` ); testEquivalence( `fun main(color: Color): i32 = color.r * 0x10000 | color.g * 0x100 | color.b`, `fun main(color: Color): i32 = (color.r * 0x10000) | (color.g * 0x100) | (color.b)` ); }); describe('imports', () => { test` import module import module2 import module::submodule import github::menduz::aureum `; test` import module as X import module2 as Y import module::submodule as Z import github::menduz::aureum as W `; }); describe('loop', () => { test` fun a(): void = { continue } `; test` fun b(): void = { break } `; test` fun c(): void = { loop { continue } } `; test` fun d(): void = { loop { break } } `; test` fun e(): void = { loop { continue break } } `; test` fun f(): void = { loop { break continue } } `; test` fun g(): void = { loop continue } `; test` fun h(): void = { loop break } `; test` fun i(): void = { var x = 1 loop { x = { if (x == 1) continue x + 1 } } } `; test` fun j(e: i32): void = { var x = 1 loop { x = { match e { case 1 -> { if (x >= 1) { match x { case 1 -> { continue 4 } else -> { break 3 } } } } else -> continue } x + 1 } } } `; }); describe('namespaces', () => { test` type void = %stack { lowLevel="void" asd="asd" ddd=0x12313 } type void = %stack {} type void = %stack { } type void = %stack{ } type void = %stack{ a=false } `; test`type Enum = %struct{a: i32}`; test`type Enum = %struct{}`; test`type Enum = %struct{a,b,c}`; test`type Enum = %struct{a:i32,b: string}`; test` type Enum = %struct{a: i32} type Enum = %struct{} type Enum = %struct{a,b,c} type Enum = %struct{a:i32,b: string} `; test` type Enum type Enum= %struct{} type Enum = %struct{} type Enum = %struct{} impl Enum { } // a type Enum =%struct{} impl Enum {} type Enum impl Enum {} type Enum impl Enum { // } // b type Enum impl Enum{ // } // c type Enum impl Enum { } // d `; test` impl Enum { val test = 1 } `; test` type AA = BB | CC type BB type CC `; test` impl Enum { val test = 1 } fun as(self: Test): X = { x() as X } `; test` impl Enum { val test = 1 private fun x(): int = test fun as(self: Test): X = { x() as X } } `; }); describe('operator definition', () => { test` fun as(x: i32, y: boolean): void = {} fun is(x: i32, y: boolean): void = {} fun +(x: i32, y: boolean): void = {} fun -(x: i32, y: boolean): void = {} fun >>(x: i32, y: boolean): void = {} fun <<(x: i32, y: boolean): void = {} fun ==(x: i32, y: boolean): void = {} fun !=(x: i32, y: boolean): void = {} fun +(x: i32, y: boolean): void = {} fun *(x: i32, y: boolean): void = {} fun **(x: i32, y: boolean): void = {} fun /(x: i32, y: boolean): void = {} fun %(x: i32, y: boolean): void = {} fun >(x: i32, y: boolean): void = {} fun <(x: i32, y: boolean): void = {} fun >=(x: i32, y: boolean): void = {} fun <=(x: i32, y: boolean): void = {} fun ~=(x: i32, y: boolean): void = {} `; }); describe('code blocks', () => { test` fun main(): void = {} `; test` fun main(): i32 = { var a: i32 = 1 var a = 2 val a = 3 val a: i32 = 4 a = 5 a } `; }); describe('WasmExpression', () => { test` private fun test(): void = %wasm {} `; test` fun malloc(size: i32): i32 = %wasm { (local $address i32) (local.set $address (global.get freeblock)) (global.set $freeblock (i32.add (local.get $address) (local.get $size) ) ) (local.get $address) } `; test` fun malloc(size: i32): i32 = %wasm { (local $address i32) } `; test` fun -(lhs: i64): i64 = %wasm { (i64.mul (get_local $lhs) (i64.const -1)) } `; test` fun strAdd(a: i32, b: i32): i32 = %wasm { (local $sum i32) (local $aSize i32) (local $newStr i32) (return (local.set $aSize (i32.load8_u a)) (local.set $sum (i32.sub (i32.add (local.get $aSize) (i32.load8_u b) ) (i32.const 1) ) ) (local.set $newStr (call malloc (i32.add (local.get $sum) (i32.const 1) ) ) ) (i32.store8 (local.get $newStr) (local.get $sum) ) (call string_copy (local.get $a) (local.get $newStr)) (call string_copy (local.get $b) (i32.sub (i32.add (local.get $newStr) (local.get $aSize) ) (i32.const 1) ) ) (local.get $newStr) ) } `; test` private fun test(): void = %wasm { } private fun test(): void = %wasm { } private fun test(): void =%wasm{} var freeblock = 0 fun malloc(size: i32): i32 = %wasm { (local $address i32) (local.set $address (global.get freeblock)) (global.set $freeblock (i32.add (local.get $address) (local.get $size) ) ) (local.get $address) } fun strAdd(a: i32, b: i32): i32 = %wasm { (local $sum i32) (local $aSize i32) (local $newStr i32) (return (local.set $aSize (i32.load8_u a)) (local.set $sum (i32.sub (i32.add (local.get $aSize) (i32.load8_u b) ) (i32.const 1) ) ) (local.set $newStr (call malloc (i32.add (local.get $sum) (i32.const 1) ) ) ) (i32.store8 (local.get $newStr) (local.get $sum) ) (call string_copy (local.get $a) (local.get $newStr)) (call string_copy (local.get $b) (i32.sub (i32.add (local.get $newStr) (local.get $aSize) ) (i32.const 1) ) ) (local.get $newStr) ) } `; }); describe('Types', () => { test` // 8 bit type byte // 16 bit type short type ushort // 32 bit type int32 type float type uint32 // 64 bit type int64 type double type uint64 `; test` // 8 bit type byte // 16 bit type short type ushort // 32 bit private type int32 type float private type uint32 // 64 bit type int64 type double type uint64 `; test` enum Boolean { True False } enum colors { Red Green Blue } `; test` enum Maybe { None Some(a: T) } `; test` enum Maybe { Some(a: T, b: X, c: asd) } `; test` struct Some(a: T, b: X, c: asd) `; test` // 8 bit type byte // 16 bit type short enum ushort { asd } // 32 bit private type int32 type float private enum uint32 {} // 64 bit type int64 type double type uint64e `; test` trait ref { fun eq(): void = ??? // asd fun ==(): void = ??? } trait asd{} `; test` trait ref { fun eq(): void fun ==(): void } `; test` impl a for b {} `; test` impl Aasd for Basd { fun a() = 1 } `; }); describe('Effects', () => { test` effect byte {} private effect byte {} effect byte {} `; test` private effect byte {} `; test` type void = %injected type i32 = %stack { lowLevelType="i32" byteSize=4 } effect state { get(): i32 put(x: i32): void } `; test` type void = %injected type i32 = %stack { lowLevelType="i32" byteSize=4 } effect state<T> { get(): T put(x: T): void } `; test` effect total {} fun sqr(x: i32): <total> i32 = x * x fun sqr(x: i32): <total|_> i32 = x * x fun sqr(x: i32): <total> i32 = x * x fun sqr(x: i32): <> i32 = x * x fun sqr(x: i32): i32 = x * x `; }); describe('Literals', () => { function testLiteral(text: string) { testParseToken( 'var a = ' + text, getFileName(), async (result, e) => { if (e) throw e; if (!result) throw new Error('No result'); }, phases ); } testLiteral(JSON.stringify('\\')); testLiteral(JSON.stringify('\"')); testLiteral(JSON.stringify('A string')); testLiteral(JSON.stringify('A string')); testLiteral(JSON.stringify("asdasd`\"`'''`\\\"")); testLiteral(JSON.stringify(213422342344234)); test` var a = 1 var b = 2.0 var c = true var d = false var f = "a string 'single' quote" var g = "an \\"escaped string" // var h = 'a string "double" quote' `; test` fun x(): string = "\\"'\`\\\\" `; // test` // fun x(): string = "// a comment inside a string" // fun singleLineComment(): void = { // START("Single line comment") // { // val p = Parser("// asd") // validateToken(p, LineComment, "// asd") // validateToken(p, EndOfFile, "") // END() // } // START("Single line comment 2") // { // val p = Parser("asd // asd\n asd") // validateToken(p, Identifier, "asd") // validateToken(p, LineComment, "// asd") // validateToken(p, NewLine, "\n") // validateToken(p, Whitespace, " ") // validateToken(p, Identifier, "asd") // validateToken(p, EndOfFile, "") // END() // } // } // ` }); describe('bin op', () => { test` var a = 1 + 2 var b = a.b.c + 2 var c = a + 3 var d = a == 4 var f = sarasa::sarasanga( a.b.c == b.c.d ) var g = sarasa::sarasanga( a.b.c == 1 ) var g = sarasa::sarasanga( a.b.c() == 1 ) `; }); describe('decorators', () => { test` fun aNormalFunction(): a = 1 #[inline] fun printf(str: u32, extra: i32): void = never `; test` #[inline] fun printf(str: u32, extra: i32): void = never `; test` #[ inline ] fun printf(str: u32, extra: i32): void = never `; test` #[export] #[ inline ] fun printf(str: u32, extra: i32): void = never `; test` #[export] #[ inline ] fun printf(str: u32, extra: i32): void = never `; test` #[export]fun printf(str: u32, extra: i32): void = never `; test` #[export] // Xomment #[ inline ] /* multiline */ fun printf(str: u32, extra: i32): void = never `; test` fun aNormalFunction(): a = 1 #[extern "env" "printf"] fun printf(str: u32, extra: i32): void = never #[extern "env" "putchar"] fun putchar(char: u32): void = never #[explicit] #[explicit] fun as(): void = never #[a 123 false] fun a(): void = never `; }); test`fun test(): void`; test`fun test() = 1`; test`fun test()`; test`fun test(): i32 = 1`; test`fun test(): void = {}`; test`fun test(): void = { }`; test`fun test(): void = { \n\n }`; test`private fun test( a: MBER, b : NumBer): i32 = 1`; test`fun test(): i32 = 2`; test`private var test: Double = 1`; test`private var test = 1`; test`var test = 1`; test`val test: Number = 1`; test`val test = 1`; test`val test = 1 * 1 - 2 / 4 && 1 == 3 || 4 <= 4`; test`val test = 1`; test`val test = 1.mul(4)`; test`val floatingNumber: Number = 1.0`; test`val floatingNumber: Number = 0.0`; test`private val test = 1`; test`val test = true`; test`val test = false`; test`fun test(): Number = 1`; test`fun test(): Number = /*asd*/ 1`; test`fun test(): Number = /**/ 1`; test`private fun test(a: Number): i32 = 2`; test`private fun test(a: Number, b: Type): i32 = 2`; test`val test = 1 + (4 + 1)`; test`val test = (1 + 4) + 1`; test` private var test = 1 var test2 = 1 val test2 = 1 `; test` var test = 1 fun getTest(): i32 = test `; test`var test: Entity = 1 fun valueOfTest(): Entity = test`; test`var test: Struct = 1`; test`var test: Struct = 1`; test`var test: Int64 = 1`; test`var test: _ = 1`; test`var test: _|_ = 1`; test`var test: a|b& c | d & b = 1`; test`var test: fun() -> void = 1`; test`var test: fun() -> void & fun(i32) -> i32 = 1`; test`var test: fun() -> void & fun(a: i32) -> i32 = 1`; test`var test: fun() -> void & fun( a : i32) -> i32 = 1`; test`var test: fun() -> (void & fun( a : i32) -> i32) = 1`; test`var test: (fun() -> void) | fun ( a : i32) -> i32 = 1`; // test` // private struct Entity { // a: Number, // b: Entity*, // c: Number*[] // } // private var entities: Entity* = 1 // private fun getTest() = test // `; test`val test = match 1 {}`; test`val test = match 1 { else -> 1 }`; test`val test = {match 1 { else -> 1 }}`; test` val test = match 1 { case 2 -> true else -> false } `; test` var a = {false} var b = { false } var c = { false } var d = { false false } `; test`val test = match 1 { case 2 -> true else -> false }`; test` val test = match 1 { case 2->true else->false } `; test` val test = match 1 { case 2 -> true else -> false } `; test` val test = match 1 { case x if true -> true case x if x < 1 && x < 10 -> true case 2 -> true else -> false } `; test` var x = if (x > y) gcd(x - y, y) else if (x < y) gcd(x, y - x) else x `; test` fun ifWithoutElse(x: i32): i32 = { if (x == 1) { a = 3 } } fun ifWithoutElse2(x: i32): i32 = { if (x == 1) asd() } `; test` var x = if (x) elseifo() .elsiso(3) else ifa() `; test`val test = match 1 { case x if x < 1 && x < 10 -> true }`; test`var a = (match x { else -> 1 }).map(1 * 2)`; test`var a = !x()`; test`var a = x()`; test`val test = (1).map(1).map(2).map(3)`; test`val test = x(1)`; test`val test = x(1,2)`; test`val test = x(1, asd)`; test`val test = nnn( 1 , \n asd )`; test`val test = x( 1 , 2 /* sdgf */)`; test` private fun compare(a: Color, b: Color): bool = { a == b } `; }); });
the_stack
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; // mqtt import {Chat21Service} from './chat-service'; // models import { ConversationModel } from '../../models/conversation'; // services import { ConversationsHandlerService } from '../abstract/conversations-handler.service'; // utils import { TYPE_GROUP } from '../../utils/constants'; import { getImageUrlThumbFromFirebasestorage, avatarPlaceholder, getColorBck } from '../../utils/utils-user'; import { compareValues, getFromNow, conversationsPathForUserId, searchIndexInArrayForUid } from '../../utils/utils'; import { ArchivedConversationsHandlerService } from '../abstract/archivedconversations-handler.service'; @Injectable({ providedIn: 'root' }) export class MQTTArchivedConversationsHandler extends ArchivedConversationsHandlerService { // BehaviorSubject BSConversationDetail: BehaviorSubject<ConversationModel>; // readAllMessages: BehaviorSubject<string>; archivedConversationAdded: BehaviorSubject<ConversationModel>; archivedConversationChanged: BehaviorSubject<ConversationModel>; archivedConversationRemoved: BehaviorSubject<ConversationModel>; loadedConversationsStorage: BehaviorSubject<ConversationModel[]>; BSConversations: BehaviorSubject<ConversationModel[]> // imageRepo: ImageRepoService; // public variables archivedConversations: Array<ConversationModel> = []; uidConvSelected: string; tenant: string; // FIREBASESTORAGE_BASE_URL_IMAGE: string; // urlStorageBucket: string; // private variables private loggedUserId: string; private translationMap: Map<string, string>; private isConversationClosingMap: Map<string, boolean>; private audio: any; private setTimeoutSound: any; constructor( // private tiledeskConversationsProvider: TiledeskConversationProvider, // public databaseProvider: DatabaseProvider, public chat21Service: Chat21Service ) { super(); } /** * inizializzo conversations handler */ initialize( tenant: string, userId: string, translationMap: Map<string, string> ) { console.log('initialize MQTTConversationsHandler'); this.loggedUserId = userId; this.translationMap = translationMap; this.archivedConversations = []; // this.databaseProvider.initialize(userId, this.tenant); this.isConversationClosingMap = new Map(); // this.getConversationsFromStorage(); } public getConversationDetail(conversationWith: string, callback) { // 1 cerco array locale // 2 cerco remoto // callback const conversation = this.archivedConversations.find(conv => conv.conversation_with === conversationWith); console.log('found locally? getConversationDetail *****: ', conversation); if (conversation) { console.log('found!'); callback(conversation); } else { console.log('Not found locally, remote.getConversationDetail *****: ', conversation); this.chat21Service.chatClient.conversationDetail(conversationWith, (conversation) => { if (conversation) { if (callback) { callback(this.completeConversation(conversation)); } } else { if (callback) { callback(null); } } }) } } setConversationRead(conversationrecipient): void { // const urlUpdate = conversationsPathForUserId(this.tenant, this.loggedUserId) + '/' + conversation.recipient; // const update = {}; // console.log('connect -------> conversations update', urlUpdate); // update['/is_new'] = false; // firebase.database().ref(urlUpdate).update(update); } /** * */ // private getConversationsFromStorage() { // const that = this; // this.databaseProvider.getConversations() // .then((conversations: [ConversationModel]) => { // that.loadedConversationsStorage.next(conversations); // // that.events.publish('loadedConversationsStorage', conversations); // }) // .catch((e) => { // console.log('error: ', e); // }); // } /** * connecting to conversations */ // connect() { // console.log('connecting MQTT conversations handler'); // const handlerConversationAdded = this.chat21Service.chatClient.onConversationAdded( (conv) => { // console.log('conversation added:', conv.text); // this.added(conv); // }); // const handlerConversationUpdated = this.chat21Service.chatClient.onConversationUpdated( (conv) => { // console.log('conversation updated:', conv.text); // this.changed(conv); // }); // const handlerConversationDeleted = this.chat21Service.chatClient.onConversationDeleted( (conv) => { // console.log('conversation deleted:', conv.text); // this.removed(conv); // }); // this.chat21Service.chatClient.lastConversations( (err, conversations) => { // console.log('Last conversations', conversations, 'err', err); // if (!err) { // conversations.forEach(conv => { // this.added(conv); // }); // } // }); // // SET AUDIO // this.audio = new Audio(); // this.audio.src = URL_SOUND; // this.audio.load(); // --------------------------------------------------------------------------------- // New connect - renamed subscribeToConversation //---------------------------------------------------------------------------------- subscribeToConversations(loaded) { console.log('connecting MQTT conversations handler'); const handlerConversationAdded = this.chat21Service.chatClient.onArchivedConversationAdded( (conv) => { console.log('conversation added:', conv.text); this.added(conv); }); // const handlerConversationUpdated = this.chat21Service.chatClient.onConversationUpdated( (conv) => { // console.log('conversation updated:', conv.text); // this.changed(conv); // }); const handlerConversationDeleted = this.chat21Service.chatClient.onArchivedConversationDeleted( (conv) => { console.log('conversation deleted:', conv.text); this.removed(conv); }); this.chat21Service.chatClient.lastConversations( true, (err, conversations) => { console.log('Last conversations', conversations, 'err', err); if (!err) { conversations.forEach(conv => { this.added(conv); }); loaded(); } }); // SET AUDIO // this.audio = new Audio(); // this.audio.src = URL_SOUND; // this.audio.load(); // const that = this; // const urlNodeFirebase = conversationsPathForUserId(this.tenant, this.loggedUserId); // console.log('connect -------> conversations', urlNodeFirebase); // this.ref = firebase.database().ref(urlNodeFirebase).orderByChild('timestamp').limitToLast(200); // this.ref.on('child_changed', (childSnapshot) => { // that.changed(childSnapshot); // }); // this.ref.on('child_removed', (childSnapshot) => { // that.removed(childSnapshot); // }); // this.ref.on('child_added', (childSnapshot) => { // that.added(childSnapshot); // }); } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice /** * 1 - completo la conversazione con i parametri mancanti * 2 - verifico che sia una conversazione valida * 3 - salvo stato conversazione (false) nell'array delle conversazioni chiuse * 4 - aggiungo alla pos 0 la nuova conversazione all'array di conversazioni * o sostituisco la conversazione con quella preesistente * 5 - salvo la conversazione nello storage * 6 - ordino l'array per timestamp * 7 - pubblico conversations:update */ private added(childSnapshot: any) { console.log("NEW CONV:::", childSnapshot) // const childData: ConversationModel = childSnapshot; // childData.uid = childSnapshot.key; // const conversation = this.completeConversation(childData); // if (this.isValidConversation(childSnapshot.key, conversation)) { // this.setClosingConversation(childSnapshot.key, false); // // da verificare l'utilità e spostare in questa classe // // this.tiledeskConversationsProvider.setClosingConversation(childSnapshot.key, false); // const index = searchIndexInArrayForUid(this.conversations, conversation.uid); // if (index > -1) { // this.conversations.splice(index, 1, conversation); // } else { // this.conversations.splice(0, 0, conversation); // // this.databaseProvider.setConversation(conversation); // } // this.conversations.sort(compareValues('timestamp', 'desc')); // console.log("ALL CONVS:", this.conversations) // this.conversationChanged.next(conversation); // this.conversationAdded.next(conversation); // // this.events.publish('conversationsChanged', this.conversations); // } else { // console.error('ChatConversationsHandler::added::conversations with conversationId: ', childSnapshot.key, 'is not valid'); // } // let childData: ConversationModel = childSnapshot; let conversation = this.completeConversation(childSnapshot); conversation.uid = conversation.conversation_with; // console.log("NUOVA CONVER;" + conversation.uid) console.log("NUOVA CONVER;.uid" + conversation.uid) if (this.isValidConversation(conversation)) { this.setClosingConversation(conversation.conversation_with, false); console.log("NUOVA CONVER;.uid1" + conversation.uid) console.log("conversations:", this.archivedConversations) console.log("cerco: ", conversation.uid) const index = this.searchIndexInArrayForConversationWith(this.archivedConversations, conversation.conversation_with); console.log("found index:", index) console.log("NUOVA CONVER;.uid2" + conversation.uid) if (index > -1) { console.log("TROVATO") this.archivedConversations.splice(index, 1, conversation); } else { console.log("NON TROVATO") this.archivedConversations.splice(0, 0, conversation); // this.databaseProvider.setConversation(conversation); } console.log("NUOVA CONVER;.uid3" + conversation.uid) this.archivedConversations.sort(compareValues('timestamp', 'desc')); console.log("NUOVA CONVER;.uid4" + conversation.uid) console.log("TUTTE:", this.archivedConversations) this.archivedConversationChanged.next(conversation); console.log("NUOVA CONVER;.uid5" + conversation.uid) this.archivedConversationAdded.next(conversation); console.log("NUOVA CONVER;.uid6" + conversation.uid) // this.events.publish('conversationsChanged', this.conversations); } else { console.error('ChatConversationsHandler::added::conversations with conversationId: ', conversation.conversation_with, 'is not valid'); } } searchIndexInArrayForConversationWith(conversations, conversation_with: string) { return conversations.findIndex(conv => conv.conversation_with === conversation_with); } /** * 1 - completo la conversazione con i parametri mancanti * 2 - verifico che sia una conversazione valida * 3 - aggiungo alla pos 0 la nuova conversazione all'array di conversazioni * 4 - salvo la conversazione nello storage * 5 - ordino l'array per timestamp * 6 - pubblico conversations:update * 7 - attivo sound se è un msg nuovo */ // private changed(childSnapshot: any) { // const childData: ConversationModel = childSnapshot.val(); // childData.uid = childSnapshot.key; // console.log('changed conversation: ', childData); // const conversation = this.completeConversation(childData); // if (this.isValidConversation(conversation)) { // this.setClosingConversation(childSnapshot.key, false); // const index = searchIndexInArrayForUid(this.conversations, conversation.uid); // if (index > -1) { // this.conversations.splice(index, 1, conversation); // } // // this.databaseProvider.setConversation(conversation); // this.conversations.sort(compareValues('timestamp', 'desc')); // this.conversationChanged.next(conversation); // // this.events.publish('conversationsChanged', this.conversations); // this.conversationChanged.next(conversation); // } else { // console.error('ChatConversationsHandler::changed::conversations with conversationId: ', childSnapshot.key, 'is not valid'); // } // if (conversation.is_new) { // this.soundMessage(); // } // } /** * 1 - cerco indice conversazione da eliminare * 2 - elimino conversazione da array conversations * 3 - elimino la conversazione dallo storage * 4 - pubblico conversations:update * 5 - elimino conversazione dall'array delle conversazioni chiuse */ private removed(childSnapshot) { const index = searchIndexInArrayForUid(this.archivedConversations, childSnapshot.key); if (index > -1) { const conversationRemoved = this.archivedConversations[index] this.archivedConversations.splice(index, 1); // this.conversations.sort(compareValues('timestamp', 'desc')); // this.databaseProvider.removeConversation(childSnapshot.key); this.archivedConversationRemoved.next(conversationRemoved); } // remove the conversation from the isConversationClosingMap this.deleteClosingConversation(childSnapshot.key); // const index = searchIndexInArrayForUid(this.conversations, childSnapshot.key); // if (index > -1) { // // 2 // this.conversations.splice(index, 1); // // this.conversations.sort(compareValues('timestamp', 'desc')); // // 3 // this.databaseProvider.removeConversation(childSnapshot.key); // // 4 // // this.conversationsChanged.next(this.conversations); // this.conversationsRemoved.next(this.conversations); // // this.events.publish('conversationsChanged', this.conversations); // } } /** * dispose reference di conversations */ dispose() { this.archivedConversations = []; this.archivedConversations.length = 0; this.uidConvSelected = ''; } getClosingConversation(conversationId: string) { return this.isConversationClosingMap[conversationId]; } setClosingConversation(conversationId: string, status: boolean) { this.isConversationClosingMap[conversationId] = status; } deleteClosingConversation(conversationId: string) { this.isConversationClosingMap.delete(conversationId); } archiveConversation(conversationId: string) { // da implementare } // ---------------------------------------------------------- // // BEGIN FUNCTIONS // ---------------------------------------------------------- // /** * Completo conversazione aggiungendo: * 1 - nel caso in cui sender_fullname e recipient_fullname sono vuoti, imposto i rispettivi id come fullname, * in modo da avere sempre il campo fullname popolato * 2 - imposto conversation_with e conversation_with_fullname con i valori del sender o al recipient, * a seconda che il sender corrisponda o meno all'utente loggato. Aggiungo 'tu:' se il sender coincide con il loggedUser * Se il sender NON è l'utente loggato, ma è una conversazione di tipo GROUP, il conversation_with_fullname * sarà uguale al recipient_fullname * 3 - imposto stato conversazione, che indica se ci sono messaggi non letti nella conversazione * 4 - imposto il tempo trascorso tra l'ora attuale e l'invio dell'ultimo messaggio * 5 - imposto avatar, colore e immagine * @param conv */ // public completeConversation(conv: any): ConversationModel { // const conversation: ConversationModel = conv; // // console.log('completeConversation', conv); // if (!conv.sender_fullname || conv.sender_fullname === 'undefined' || conv.sender_fullname.trim() === '') { // conversation.sender_fullname = conv.sender; // } else { // conversation.sender_fullname = conv.sender_fullname; // } // if (!conv.recipient_fullname || conv.recipient_fullname === 'undefined' || conv.recipient_fullname.trim() === ''){ // conversation.recipient_fullname = conv.recipient; // } else { // conversation.recipient_fullname = conv.recipient_fullname; // } // let LABEL_TU: string; // this.translate.get('LABEL_TU').subscribe((res: string) => { // LABEL_TU = res; // }); // let conversationWithFullname = conv.sender_fullname; // let conversationWith = conv.sender; // conversation.last_message_text = conv.last_message_text; // if (conv.sender === this.loggedUser.uid) { // conversationWith = conv.recipient; // conversationWithFullname = conv.recipient_fullname; // conversation.last_message_text = LABEL_TU + conv.last_message_text; // } else if (conv.channel_type === TYPE_GROUP) { // conversationWith = conv.recipient; // conversationWithFullname = conv.recipient_fullname; // conversation.last_message_text = conv.last_message_text; // } // conversation.conversation_with_fullname = conversationWithFullname; // conversation.selected = false; // console.log('conv.uid', conv.uid); // conversation.status = this.setStatusConversation(conv.sender, conv.uid); // conversation.time_last_message = this.getTimeLastMessage(conv.timestamp); // conversation.avatar = avatarPlaceholder(conversationWithFullname); // conversation.color = getColorBck(conversationWithFullname); // conversation.image = this.getImageUrlThumbFromFirebasestorage(conv.uid); // // try { // // const FIREBASESTORAGE_BASE_URL_IMAGE = this.appConfig.getConfig().FIREBASESTORAGE_BASE_URL_IMAGE; // // conversation.image = getImageUrlThumb(FIREBASESTORAGE_BASE_URL_IMAGE, conversationWith); // // } catch (err) { // // console.log(err); // // } // // console.log('completeConversation fine', conversation); // return conversation; // } private completeConversation(conv): ConversationModel { // console.log('completeConversation', conv); // const LABEL_TU = this.translationMap.get('LABEL_TU'); // conv.selected = false; // if (!conv.sender_fullname || conv.sender_fullname === 'undefined' || conv.sender_fullname.trim() === '') { // conv.sender_fullname = conv.sender; // } // if (!conv.recipient_fullname || conv.recipient_fullname === 'undefined' || conv.recipient_fullname.trim() === '') { // conv.recipient_fullname = conv.recipient; // } // let conversation_with_fullname = conv.sender_fullname; // let conversation_with = conv.sender; // if (conv.sender === this.loggedUserId) { // conversation_with = conv.recipient; // conversation_with_fullname = conv.recipient_fullname; // conv.last_message_text = LABEL_TU + conv.last_message_text; // } else if (conv.channel_type === TYPE_GROUP) { // conversation_with = conv.recipient; // conversation_with_fullname = conv.recipient_fullname; // conv.last_message_text = conv.last_message_text; // } // conv.conversation_with_fullname = conversation_with_fullname; // conv.status = this.setStatusConversation(conv.sender, conv.uid); // conv.time_last_message = this.getTimeLastMessage(conv.timestamp); // conv.avatar = avatarPlaceholder(conversation_with_fullname); // conv.color = getColorBck(conversation_with_fullname); // return conv; console.log('completeConversation', conv); conv.selected = false; if (!conv.sender_fullname || conv.sender_fullname === 'undefined' || conv.sender_fullname.trim() === '') { conv.sender_fullname = conv.sender; } if (!conv.recipient_fullname || conv.recipient_fullname === 'undefined' || conv.recipient_fullname.trim() === '') { conv.recipient_fullname = conv.recipient; } let conversation_with_fullname = conv.sender_fullname; let conversation_with = conv.sender; if (conv.sender === this.loggedUserId) { conversation_with = conv.recipient; conversation_with_fullname = conv.recipient_fullname; conv.last_message_text = conv.last_message_text; } else if (conv.channel_type === TYPE_GROUP) { conversation_with = conv.recipient; conversation_with_fullname = conv.recipient_fullname; conv.last_message_text = conv.last_message_text; } conv.conversation_with_fullname = conversation_with_fullname; conv.conversation_with = conversation_with; conv.status = this.setStatusConversation(conv.sender, conv.uid); conv.time_last_message = this.getTimeLastMessage(conv.timestamp); conv.avatar = avatarPlaceholder(conversation_with_fullname); conv.color = getColorBck(conversation_with_fullname); if (!conv.last_message_text) { conv.last_message_text = conv.text; // building conv with a message } return conv; } // /** // * // * @param uid // */ // private getImageUrlThumbFromFirebasestorage(uid: string) { // const FIREBASESTORAGE_BASE_URL_IMAGE = this.appConfig.getConfig().FIREBASESTORAGE_BASE_URL_IMAGE; // const urlStorageBucket = this.appConfig.getConfig().firebaseConfig.storageBucket + '/o/profiles%2F'; // const imageurl = FIREBASESTORAGE_BASE_URL_IMAGE + urlStorageBucket + uid + '%2Fthumb_photo.jpg?alt=media'; // return imageurl; // } /** */ // set the remote conversation as read // setConversationRead(conversationUid) { // var conversationRef = this.ref.ref.child(conversationUid); // conversationRef.update ({"is_new" : false}); // } /** */ // getConversationByUid(conversationUid) { // const index = searchIndexInArrayForUid(this.conversations, conversationUid); // return this.conversations[index]; // } /** */ private setStatusConversation(sender, uid): string { let status = '0'; // letto if (sender === this.loggedUserId || uid === this.uidConvSelected) { status = '0'; } else { status = '1'; // non letto } return status; } /** * calcolo il tempo trascorso da ora al timestamp passato * @param timestamp */ private getTimeLastMessage(timestamp: string) { const timestampNumber = parseInt(timestamp) / 1000; const time = getFromNow(timestampNumber); return time; } // removeByUid(uid) { // const index = searchIndexInArrayForUid(this.conversations, uid); // if (index > -1) { // this.conversations.splice(index, 1); // // this.events.publish('conversationsChanged', this.conversations); // this.conversationsChanged.next(this.conversations); // } // } // addConversationListener(uidUser, conversationId) { // var that = this; // this.tenant = environment.tenant; // // const tenant = this.chatManager.getTenant(); // const url = '/apps/' + this.tenant + '/users/' + uidUser + '/conversations/' + conversationId; // const reference = firebase.database().ref(url); // console.log("ChatConversationsHandler::addConversationListener::reference:",url, reference.toString()); // reference.on('value', function (snapshot) { // setTimeout(function () { // // that.events.publish(conversationId + '-listener', snapshot); // }, 100); // }); // } /** * restituisce il numero di conversazioni nuove */ countIsNew(): number { let num = 0; this.archivedConversations.forEach((element) => { if (element.is_new === true) { num++; } }); return num; } // ---------------------------------------------------------- // // END FUNCTIONS // ---------------------------------------------------------- // /** * attivo sound se è un msg nuovo */ private soundMessage() { console.log('****** soundMessage *****', this.audio); const that = this; // this.audio = new Audio(); // this.audio.src = 'assets/pling.mp3'; // this.audio.load(); this.audio.pause(); this.audio.currentTime = 0; clearTimeout(this.setTimeoutSound); this.setTimeoutSound = setTimeout(function () { //setTimeout(function() { that.audio.play() .then(function() { // console.log('****** then *****'); }) .catch(function() { // console.log('***//tiledesk-dashboard/chat*'); }); }, 1000); } // /** // * check if the conversations is valid or not // */ // private isValidConversation(convToCheckId, convToCheck: ConversationModel) : boolean { // //console.log("[BEGIN] ChatConversationsHandler:: convToCheck with uid: ", convToCheckId); // if (!this.isValidField(convToCheck.uid)) { // console.error("ChatConversationsHandler::isValidConversation:: 'uid is not valid' "); // return false; // } // if (!this.isValidField(convToCheck.is_new)) { // console.error("ChatConversationsHandler::isValidConversation:: 'is_new is not valid' "); // return false; // } // if (!this.isValidField(convToCheck.last_message_text)) { // console.error("ChatConversationsHandler::isValidConversation:: 'last_message_text is not valid' "); // return false; // } // if (!this.isValidField(convToCheck.recipient)) { // console.error("ChatConversationsHandler::isValidConversation:: 'recipient is not valid' "); // return false; // } // if (!this.isValidField(convToCheck.recipient_fullname)) { // console.error("ChatConversationsHandler::isValidConversation:: 'recipient_fullname is not valid' "); // return false; // } // if (!this.isValidField(convToCheck.sender)) { // console.error("ChatConversationsHandler::isValidConversation:: 'sender is not valid' "); // return false; // } // if (!this.isValidField(convToCheck.sender_fullname)) { // console.error("ChatConversationsHandler::isValidConversation:: 'sender_fullname is not valid' "); // return false; // } // if (!this.isValidField(convToCheck.status)) { // console.error("ChatConversationsHandler::isValidConversation:: 'status is not valid' "); // return false; // } // if (!this.isValidField(convToCheck.timestamp)) { // console.error("ChatConversationsHandler::isValidConversation:: 'timestamp is not valid' "); // return false; // } // if (!this.isValidField(convToCheck.channel_type)) { // console.error("ChatConversationsHandler::isValidConversation:: 'channel_type is not valid' "); // return false; // } // //console.log("[END] ChatConversationsHandler:: convToCheck with uid: ", convToCheckId); // // any other case // return true; // } /** * check if the conversations is valid or not */ private isValidConversation(convToCheck: ConversationModel) : boolean { //console.log("[BEGIN] ChatConversationsHandler:: convToCheck with uid: ", convToCheckId); console.log("checking uid of", convToCheck) console.log("uid is:", convToCheck.uid) console.log("channel_type is:", convToCheck.channel_type) if (!this.isValidField(convToCheck.uid)) { console.error("ChatConversationsHandler::isValidConversation:: 'uid is not valid' "); return false; } // if (!this.isValidField(convToCheck.is_new)) { // console.error("ChatConversationsHandler::isValidConversation:: 'is_new is not valid' "); // return false; // } if (!this.isValidField(convToCheck.last_message_text)) { console.error("ChatConversationsHandler::isValidConversation:: 'last_message_text is not valid' "); return false; } if (!this.isValidField(convToCheck.recipient)) { console.error("ChatConversationsHandler::isValidConversation:: 'recipient is not valid' "); return false; } if (!this.isValidField(convToCheck.recipient_fullname)) { console.error("ChatConversationsHandler::isValidConversation:: 'recipient_fullname is not valid' "); return false; } if (!this.isValidField(convToCheck.sender)) { console.error("ChatConversationsHandler::isValidConversation:: 'sender is not valid' "); return false; } if (!this.isValidField(convToCheck.sender_fullname)) { console.error("ChatConversationsHandler::isValidConversation:: 'sender_fullname is not valid' "); return false; } if (!this.isValidField(convToCheck.status)) { console.error("ChatConversationsHandler::isValidConversation:: 'status is not valid' "); return false; } if (!this.isValidField(convToCheck.timestamp)) { console.error("ChatConversationsHandler::isValidConversation:: 'timestamp is not valid' "); return false; } if (!this.isValidField(convToCheck.channel_type)) { console.error("ChatConversationsHandler::isValidConversation:: 'channel_type is not valid' "); return false; } //console.log("[END] ChatConversationsHandler:: convToCheck with uid: ", convToCheckId); // any other case return true; } // checks if a conversation's field is valid or not private isValidField(field) : boolean{ return (field === null || field === undefined) ? false : true; } }
the_stack
import * as vscode from "vscode"; import { executeCommand, ExpectedDocument, groupTestsByParentName } from "../utils"; suite("./test/suite/commands/search.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("easy > search-b", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` foo bar ^ 0 `); // Perform all operations. await executeCommand("dance.search", { input: "b" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:8:1", 6, String.raw` foo bar ^ 0 `); }); test("1 > search", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); // Perform all operations. await executeCommand("dance.search", { input: "brown" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:27:1", 6, String.raw` The quick brown fox ^^^^^ 0 jumps over the lazy dog quickly. `); }); test("1 > search-repeat", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); // Perform all operations. await executeCommand("dance.search", { input: "o", count: 2 }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:39:1", 6, String.raw` The quick brown fox ^ 0 jumps over the lazy dog quickly. `); }); test("1 > search-start", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); // Perform all operations. await executeCommand("dance.search", { input: "quick" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:51:1", 6, String.raw` The quick brown fox jumps over the lazy dog quickly. ^^^^^ 0 `); }); test("1 > search-start-wrap", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); // Perform all operations. await executeCommand("dance.search", { input: "quick " }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:65:1", 6, String.raw` The quick brown fox ^^^^^^ 0 jumps over the lazy dog quickly. `); }); test("1 > search-wrap", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); // Perform all operations. await executeCommand("dance.search", { input: "Th" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:79:1", 6, String.raw` The quick brown fox ^^ 0 jumps over the lazy dog quickly. `); }); test("1 > search-not-found", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); // Perform all operations. await executeCommand("dance.search", { input: "pig", $expect: /^no selections remain$/ }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:91:1", 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); }); test("1 > search-backward", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); // Perform all operations. await executeCommand("dance.search", { input: "Th", direction: -1 }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:106:1", 6, String.raw` The quick brown fox ^^ 0 jumps over the lazy dog quickly. `); }); test("1 > search-backward-wrap", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); // Perform all operations. await executeCommand("dance.search", { input: "he", direction: -1 }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:120:1", 6, String.raw` The quick brown fox jumps over the ^^ 0 lazy dog quickly. `); }); test("1 > search-backward-wrap-other", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); // Perform all operations. await executeCommand("dance.search", { input: "he q", direction: -1 }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:134:1", 6, String.raw` The quick brown fox ^^^^ 0 jumps over the lazy dog quickly. `); }); test("1 > search-backward-not-found", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); // Perform all operations. await executeCommand("dance.search", { input: "pig", direction: -1, $expect: /^no selections remain$/ }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:148:1", 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); }); test("1 > search-extend", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); // Perform all operations. await executeCommand("dance.search", { input: "quick", shift: "extend" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:163:1", 6, String.raw` The quick brown fox ^ 0 jumps over the lazy dog quickly. ^ 0 `); }); test("1 > search-extend-wrap", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); // Perform all operations. await executeCommand("dance.search", { input: "T", shift: "extend", $expect: /^no selections remain$/ }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:176:1", 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); }); test("1 > search-backward-extend", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); // Perform all operations. await executeCommand("dance.search", { input: "T", direction: -1, shift: "extend" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:192:1", 6, String.raw` The quick brown fox |^ 0 jumps over the lazy dog quickly. `); }); test("1 > search-backward-extend-character", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); // Perform all operations. await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" }); await executeCommand("dance.search", { input: "T", direction: -1, shift: "extend" }); await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:206:1", 6, String.raw` The quick brown fox |^^ 0 jumps over the lazy dog quickly. `); }); test("1 > search-backward-extend-other", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); // Perform all operations. await executeCommand("dance.search", { input: "Th", direction: -1, shift: "extend" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:222:1", 6, String.raw` The quick brown fox |^ 0 jumps over the lazy dog quickly. `); }); test("1 > search-backward-extend-character-other", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); // Perform all operations. await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" }); await executeCommand("dance.search", { input: "Th", direction: -1, shift: "extend" }); await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:236:1", 6, String.raw` The quick brown fox |^^ 0 jumps over the lazy dog quickly. `); }); test("1 > search-backward-extend-wrap", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); // Perform all operations. await executeCommand("dance.search", { input: "lazy", direction: -1, shift: "extend", $expect: /^no selections remain$/ }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:252:1", 6, String.raw` The quick brown fox ^^^ 0 jumps over the lazy dog quickly. `); }); test("2 > search", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox | 0 jumps over the lazy dog quickly. ^ 0 `); // Perform all operations. await executeCommand("dance.search", { input: "o" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:281:1", 6, String.raw` The quick brown fox jumps over the lazy dog quickly. ^ 0 `); }); test("2 > search-extend", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox | 0 jumps over the lazy dog quickly. ^ 0 `); // Perform all operations. await executeCommand("dance.search", { input: "o", shift: "extend" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:295:1", 6, String.raw` The quick brown fox jumps over the lazy dog quickly. ^^^^ 0 `); }); test("2 > search-extend-character", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox | 0 jumps over the lazy dog quickly. ^ 0 `); // Perform all operations. await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" }); await executeCommand("dance.search", { input: "o", shift: "extend" }); await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:309:1", 6, String.raw` The quick brown fox jumps over the lazy dog quickly. ^^^^^ 0 `); }); test("2 > search-wrap", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox | 0 jumps over the lazy dog quickly. ^ 0 `); // Perform all operations. await executeCommand("dance.search", { input: "he" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:325:1", 6, String.raw` The quick brown fox |^ 0 jumps over the lazy dog quickly. `); }); test("2 > search-extend-wrap", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox | 0 jumps over the lazy dog quickly. ^ 0 `); // Perform all operations. await executeCommand("dance.search", { input: "he", shift: "extend", $expect: /^no selections remain$/ }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:339:1", 6, String.raw` The quick brown fox | 0 jumps over the lazy dog quickly. ^ 0 `); }); test("2 > search-backward", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox | 0 jumps over the lazy dog quickly. ^ 0 `); // Perform all operations. await executeCommand("dance.search", { input: "u", direction: -1 }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:355:1", 6, String.raw` The quick brown fox ^ 0 jumps over the lazy dog quickly. `); }); test("2 > search-backward-extend", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox | 0 jumps over the lazy dog quickly. ^ 0 `); // Perform all operations. await executeCommand("dance.search", { input: "u", direction: -1, shift: "extend" }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:369:1", 6, String.raw` The quick brown fox | 0 jumps over the lazy dog quickly. ^ 0 `); }); test("2 > search-backward-wrap", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox | 0 jumps over the lazy dog quickly. ^ 0 `); // Perform all operations. await executeCommand("dance.search", { input: "o", direction: -1 }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:384:1", 6, String.raw` The quick brown fox jumps over the lazy dog quickly. ^ 0 `); }); test("2 > search-backward-extend-wrap", async function () { // Set-up document to be in expected initial state. await ExpectedDocument.apply(editor, 6, String.raw` The quick brown fox | 0 jumps over the lazy dog quickly. ^ 0 `); // Perform all operations. await executeCommand("dance.search", { input: "o", direction: -1, shift: "extend", $expect: /^no selections remain$/ }); // Ensure document is as expected. ExpectedDocument.assertEquals(editor, "./test/suite/commands/search.md:398:1", 6, String.raw` The quick brown fox | 0 jumps over the lazy dog quickly. ^ 0 `); }); groupTestsByParentName(this); });
the_stack
import { Data, EncodeEntry, expressionFunction, Mark, OnEvent, parse, Scale, Signal, Spec, View, Warn } from "vega"; import { View1D } from "../api"; import { Config } from "../config"; import { extent, repeatInvisible } from "../util"; export const darkerBlue = "#4c78a8"; export function loadingMarks(heightSignal: string, rotate = false) { return [ { type: "rect", interactive: false, encode: { enter: { x: { value: 0 }, y: { value: 0 }, x2: { signal: "width" }, y2: { signal: heightSignal }, fill: { value: "white" } }, update: { opacity: { signal: "pending ? '0.9' : '0'" } } } }, { type: "text", interactive: false, encode: { enter: { text: { value: "Loading View..." }, baseline: { value: "middle" }, align: { value: "center" }, x: { signal: "width", mult: 0.5 }, y: { signal: heightSignal, mult: 0.5 }, fill: { value: "grey" }, fontSize: { value: 18 }, ...(rotate ? { angle: { value: -90 } } : {}) }, update: { opacity: { signal: "pending ? '1' : '0'" } } } } ] as Mark[]; } export function createHistogramView<D extends string>( el: Element, view: View1D<D>, config: Config, logging: boolean ): View { const dimension = view.dimension; const data = [ { // base = unfiltered data name: "base", transform: [ { type: "filter", expr: "showBase" } ] }, { name: "table" } ] as Data[]; const barEncodeBase: EncodeEntry = { x: { scale: "x", field: "key", offset: 1 }, x2: { scale: "x", signal: `datum.key + bin.step` }, y: { scale: "y", field: "value" }, y2: { scale: "y", value: 0 } }; const marks: Mark[] = [ { type: "group", name: "main", encode: { enter: { height: { signal: "histHeight" }, width: { signal: "width" } } }, marks: [ { type: "text", name: "reset", encode: { enter: { x: config.toggleUnfiltered ? { signal: "width", mult: 0.5, offset: 5 } : { signal: "width" }, y: { value: -8 }, align: config.toggleUnfiltered ? { value: "left" } : { value: "right" }, cursor: { value: "pointer" }, fontWeight: { value: "bold" }, fill: { value: "black" } }, update: { text: { signal: "span(brush) ? 'Reset Brush' : ''" } } } }, { type: "text", encode: { enter: { x: config.toggleUnfiltered ? { signal: "width", mult: 0.5, offset: -5 } : { signal: "width", offset: -80 }, y: { value: -8 }, align: { value: "right" }, fill: { value: "#666" } }, update: { text: { signal: `span(brush) ? '[' + ${ dimension.time ? "timeFormat" : "format" }(brush[reverseBrush ? 1 : 0], '${dimension.format}') + ',' + ${ dimension.time ? "timeFormat" : "format" }(brush[reverseBrush ? 0 : 1], '${ dimension.format }') + ']' : ''` } } } }, { type: "group", name: "chart", encode: { enter: { height: { field: { group: "height" } }, width: { signal: "width" }, fill: { value: "transparent" }, cursor: { value: "crosshair" } }, update: { // clip brush when it is inactive clip: { signal: "!span(brush)" } } }, marks: [ { type: "rect", name: "brush", encode: { enter: { y: { value: 0 }, height: { field: { group: "height" } }, fill: { value: "#000" }, opacity: { value: 0.05 }, cursor: { value: "move" } }, update: { x: { signal: "brush[0]", scale: "x" }, x2: { signal: "brush[1]", scale: "x" } } } }, { type: "group", clip: true, marks: [ { type: "rect", interactive: false, from: { data: "base" }, encode: { enter: { fill: { value: "#000" }, opacity: { value: 0.07 } }, update: { ...barEncodeBase } } }, { type: "rect", interactive: false, from: { data: "table" }, encode: { enter: { fill: { value: darkerBlue } }, update: { opacity: { signal: "approximate ? 0.7 : 1" }, ...barEncodeBase } } } ] }, { type: "group", encode: { enter: { height: { field: { group: "height" } } }, update: { x: { signal: "brush ? scale('x', brush[0]) : -10" } } }, marks: [ { type: "path", name: "left_grabber", encode: { enter: { y: { field: { group: "height" }, mult: 0.5, offset: -50 }, fill: { value: "#eee" }, stroke: { value: "#666" }, cursor: { value: "ew-resize" } }, update: { path: { signal: "!reverseBrush ? 'M-0.5,33.333333333333336A6,6 0 0 0 -6.5,39.333333333333336V60.66666666666667A6,6 0 0 0 -0.5,66.66666666666667ZM-2.5,41.333333333333336V58.66666666666667M-4.5,41.333333333333336V58.66666666666667' : 'M0.5,33.333333333333336A6,6 0 0 1 6.5,39.333333333333336V60.66666666666667A6,6 0 0 1 0.5,66.66666666666667ZM2.5,41.333333333333336V58.66666666666667M4.5,41.333333333333336V58.66666666666667'" } } } }, { type: "rect", encode: { enter: { y: { value: 0 }, height: { field: { group: "height" } }, fill: { value: "firebrick" }, x: { value: 0 }, width: { value: 1 } } } }, { type: "rect", name: "left", encode: { enter: { y: { value: 0 }, height: { field: { group: "height" } }, fill: { value: "transparent" }, width: { value: 7 }, cursor: { value: "ew-resize" }, x: { value: -3 } } } } ] }, { type: "group", encode: { enter: { height: { field: { group: "height" } } }, update: { x: { signal: "brush ? scale('x', brush[1]) : -10" } } }, marks: [ { type: "path", name: "right_grabber", encode: { enter: { y: { field: { group: "height" }, mult: 0.5, offset: -50 }, fill: { value: "#eee" }, stroke: { value: "#666" }, cursor: { value: "ew-resize" } }, update: { path: { signal: "reverseBrush ? 'M-0.5,33.333333333333336A6,6 0 0 0 -6.5,39.333333333333336V60.66666666666667A6,6 0 0 0 -0.5,66.66666666666667ZM-2.5,41.333333333333336V58.66666666666667M-4.5,41.333333333333336V58.66666666666667' : 'M0.5,33.333333333333336A6,6 0 0 1 6.5,39.333333333333336V60.66666666666667A6,6 0 0 1 0.5,66.66666666666667ZM2.5,41.333333333333336V58.66666666666667M4.5,41.333333333333336V58.66666666666667'" } } } }, { type: "rect", encode: { enter: { y: { value: 0 }, height: { field: { group: "height" } }, fill: { value: "firebrick" }, width: { value: 1 } } } }, { type: "rect", name: "right", encode: { enter: { y: { value: 0 }, height: { field: { group: "height" } }, fill: { value: "transparent" }, width: { value: 7 }, cursor: { value: "ew-resize" }, x: { value: -3 } } } } ] } ] }, ...loadingMarks("histHeight") ], axes: [ { scale: "y", orient: "left", labelOverlap: true, tickCount: { signal: "ceil(histHeight/40)" }, title: "Count", grid: true }, { scale: "x", orient: "bottom", labelOverlap: true, ...(dimension.time ? { tickCount: dimension.bins } : { values: { signal: "sequence(bin.start, bin.stop + bin.step, bin.step)" }, tickCount: { signal: "ceil(width/20)" } }) } ] } ]; const onBrush: OnEvent[] = [ { events: "mouseup, touchend", update: "span(brush) ? brush : 0" }, { events: "@chart:dblclick!, @brush:dblclick!, @left_grabber:dblclick!, @left:dblclick!, @right_grabber:dblclick!, @right:dblclick!, @reset:click!, @reset:touchstart!", update: "0" }, { events: { signal: "pan" }, update: "clampRange(panLinear(anchor, pan / span(anchor)), invert('x', 0), invert('x', width))" }, { events: "[@chart:mousedown, window:mouseup] > window:mousemove!," + " [@chart:touchstart, window:touchend] > window:touchmove", update: "[down, clamp(snapped, invert('x', 0), invert('x', width))]" }, { events: "[@left:mousedown, window:mouseup] > window:mousemove!, [@left_grabber:mousedown, window:mouseup] > window:mousemove!," + "[@left:touchstart, window:touchend] > window:touchmove, [@left_grabber:touchstart, window:touchend] > window:touchmove", update: "[clamp(snapped, invert('x', 0), invert('x', width)), scale('snap', brush[1])]" }, { events: "[@right:mousedown, window:mouseup] > window:mousemove!, [@right_grabber:mousedown, window:mouseup] > window:mousemove!," + "[@right:touchstart, window:touchend] > window:touchmove, [@right_grabber:touchstart, window:touchend] > window:touchmove", update: "[scale('snap', brush[0]), clamp(snapped, invert('x', 0), invert('x', width))]" } ]; const signals: Signal[] = [ { name: "histHeight", value: config.histogramHeight }, { name: "pending", value: false }, { name: "approximate", value: false }, { name: "bin", value: dimension.binConfig }, { name: "pixels", value: 1 }, { name: "step", update: "(bin.stop - bin.start) / pixels" }, { name: "showBase", value: config.showUnfiltered, on: [ { events: "@toggleShowBase:click!, @toggleShowBase:touchstart!", update: "!showBase" } ] }, { name: "brush", value: 0, on: onBrush }, { name: "snapped", value: 0, on: [ { events: "window:mousemove, window:touchstart, window:touchend, window:touchmove", update: config.interpolate ? "invert('x', x())" : "scale('snap', invert('x', x()))" } ] }, { name: "down", value: 0, on: [ { events: "@chart:mousedown, @chart:touchstart, @brush:mousedown, @brush:touchstart", update: "snapped" } ] }, { name: "anchor", value: 0, on: [ { events: "@brush:mousedown, @brush:touchstart", update: "[scale('snap', brush[0]), scale('snap', brush[1])]" } ] }, { name: "pan", value: 0, on: [ { events: "[@brush:mousedown, window:mouseup] > window:mousemove!, [@brush:touchstart, window:touchend] > window:touchmove", update: "down - snapped" } ] }, { name: "binBrush", update: "span(brush) ? [(brush[0] - bin.start) / step, (brush[1] - bin.start) / step] : 0" }, { name: "pixelBrush", update: "span(brush) ? [scale('x', brush[0]), scale('x', brush[1])] : 0" }, { name: "reverseBrush", update: "brush[0] > brush[1]" }, // set the cursor when the mouse is moving { name: "cursor", value: "default", on: [ { events: { signal: "pan" }, update: "'move'" }, { events: "[@left:mousedown, window:mouseup] > window:mousemove, [@left_grabber:mousedown, window:mouseup] > window:mousemove, [@right:mousedown, window:mouseup] > window:mousemove, [@right_grabber:mousedown, window:mouseup] > window:mousemove", update: "'ew-resize'" }, { events: "[@chart:mousedown, window:mouseup] > window:mousemove!", update: "'crosshair'" }, { events: "window:mouseup", update: "'default'" } ] }, { name: "domain", value: [dimension.binConfig!.start, dimension.binConfig!.stop], on: config.zoom ? [ { events: { signal: "zoom" }, update: "keepWithin([zoomAnchor + (domain[0] - zoomAnchor) * zoom, zoomAnchor + (domain[1] - zoomAnchor) * zoom], brush)" } ] : [] } ]; if (config.zoom) { signals.push( ...([ { name: "zoomAnchor", value: 0, on: [ { events: "@chart:wheel, @brush:wheel, @left:wheel, @left_grabber:wheel, @right:wheel, @right_grabber:wheel", update: dimension.time ? "time(invert('x', x()))" : "invert('x', x())" } ] }, { name: "zoom", value: 0, on: [ { events: "@chart:wheel!, @brush:wheel!, @left:wheel!, @left_grabber:wheel!, @right:wheel!, @right_grabber:wheel!", force: true, update: "pow(1.001, event.deltaY * pow(16, event.deltaMode))" } ] } ] as Signal[]) ); } if (logging) { signals.push({ name: "brushMouse", value: 0, on: [ { events: "@chart:mousedown", update: "1" }, { events: "window:mouseup", update: "0" } ] }); } if (config.toggleUnfiltered) { marks.push({ type: "text", name: "toggleShowBase", encode: { enter: { x: { signal: "width" }, y: { value: -8 }, align: { value: "right" }, cursor: { value: "pointer" }, fontWeight: { value: "bold" }, fill: { value: "black" } }, update: { text: { signal: "showBase ? 'Hide Unfiltered' : 'Show Unfiltered'" } } } } as Mark); } const scales: Scale[] = [ { name: "y", type: "linear", domain: { fields: [ { data: "base", field: "value" }, { data: "table", field: "value" } ] }, range: [{ signal: "histHeight" }, 0], nice: true, zero: true }, { name: "x", type: dimension.time ? "time" : "linear", domain: { signal: "domain" }, range: "width", zero: false } as Scale, { name: "snap", type: "threshold", domain: { signal: "sequence(bin.start + step / 2, bin.stop, step)" }, range: { signal: "repeatInvisible(sequence(bin.start, bin.stop + step, step), invert('x', 0), invert('x', width))" } } ]; const vgSpec: Spec = { $schema: "https://vega.github.io/schema/vega/v4.0.json", autosize: "pad", width: config.histogramWidth, padding: 5, data: data, signals: signals, title: { text: view.title || "", anchor: "start", frame: "group", fontSize: 14, offset: -12 }, layout: { padding: { row: 10 }, columns: 1, bounds: "full", align: "each" }, marks: marks, scales: scales, config: { axisY: { minExtent: config.yAxisExtent } } }; // function to replace invisible steps with visible ones expressionFunction("repeatInvisible", repeatInvisible); // function to make sure we never zoom the brush outside the view expressionFunction("keepWithin", (range, bounds) => { bounds = extent(bounds); if (bounds[0] < range[0]) { range[0] = bounds[0]; } if (bounds[1] > range[1]) { range[1] = bounds[1]; } return range; }); const runtime = parse(vgSpec); const vgView = new View(runtime) .logLevel(Warn) .renderer(config.renderer) .initialize(el); vgView["_spec"] = vgSpec; return vgView; }
the_stack
import { EventBus } from '../../core/modules/EventBus'; import { Data } from '../Data/Data'; import { ApiClient } from '../ApiClient/ApiClient'; import { IMapRequest, IMapResponse, IRequest, TMethod } from '../ApiClient/ApiClient.types'; import * as CONSTANTS from '../../constants'; import { SetPurchaseAttributes } from './Api.types'; export class Api { private readonly data: Data; private readonly apiClient: ApiClient; private readonly eventBus: EventBus; constructor( eventBus: EventBus, data: Data = new Data(), apiClient: ApiClient = new ApiClient(), ) { this.eventBus = eventBus; this.data = data; this.apiClient = apiClient; } public async checkDevice(): Promise<IMapResponse['checkDevice']> { const params = await this.getRequestParams(); return await this.apiClient.checkDevice(params); } public async checkDeviceSubscribeForPushNotifications(useCache: boolean = true): Promise<boolean> { // get current subscription status from local storage let status = localStorage.getItem(CONSTANTS.KEY_DEVICE_REGISTRATION_STATUS); // check need force update if (typeof status === 'undefined' || !useCache) { const { exist, push_token_exist } = await this.checkDevice(); localStorage.setItem(CONSTANTS.KEY_DEVICE_REGISTRATION_STATUS, exist && push_token_exist ? CONSTANTS.DEVICE_REGISTRATION_STATUS_REGISTERED : CONSTANTS.DEVICE_REGISTRATION_STATUS_UNREGISTERED ); status = localStorage.getItem(CONSTANTS.KEY_DEVICE_REGISTRATION_STATUS); } return status === CONSTANTS.DEVICE_REGISTRATION_STATUS_REGISTERED; } public async getConfig(features: string[]): Promise<IMapResponse['getConfig']> { const params = await this.getRequestParams(); return this.apiClient.getConfig({ ...params, features, }); } public async applicationOpen(): Promise<IMapResponse['applicationOpen']> { const params = await this.getRequestParams(); // set do database latest sending time await this.data.setLastOpenApplicationTime(Date.now()); return this.apiClient.applicationOpen(params); } public async registerDevice(): Promise<IMapResponse['registerDevice']> { // check communication disabled const isCommunicationDisabled = await this.data.getStatusCommunicationDisabled(); // if communication disabled -> can't register device if (isCommunicationDisabled) { throw new Error(`Can't register device: Communication is disabled!`); } const params = await this.getRequestParams(); const tokens = await this.data.getTokens(); // if have not pushToken -> user not get permission for send push notifications if (!tokens.pushToken) { throw new Error(`Can't register device: pushToken is not exist!`); } // register device into Pushwoosh const response = await this.apiClient.registerDevice({ ...params, ...{ push_token: tokens.pushToken, auth_token: tokens.authToken, public_key: tokens.publicKey, fcm_push_set: tokens.fcmPushSet, fcm_token: tokens.fcmToken, }, }); // set info to database, that the device IS NOT manual unsubscribed await this.data.setStatusManualUnsubscribed(false); // set info to local storage, that device is subscribed localStorage.setItem(CONSTANTS.KEY_DEVICE_REGISTRATION_STATUS, CONSTANTS.DEVICE_REGISTRATION_STATUS_REGISTERED); // emit event this.eventBus.dispatchEvent('register', {}); return response; } public async unregisterDevice(): Promise<IMapResponse['unregisterDevice']> { const params = await this.getRequestParams(); const response = this.apiClient.unregisterDevice(params); // set info to local storage, that device is unsubscribed localStorage.setItem(CONSTANTS.KEY_DEVICE_REGISTRATION_STATUS, CONSTANTS.DEVICE_REGISTRATION_STATUS_UNREGISTERED); // emit event this.eventBus.dispatchEvent('unsubscribe', {}); return response; } public async deleteDevice(): Promise<IMapResponse['deleteDevice']> { const params = await this.getRequestParams(); const response = this.apiClient.deleteDevice(params); // set info to database, that the device IS manual unsubscribed await this.data.setStatusManualUnsubscribed(true); // set info to local storage, that device is unsubscribed localStorage.setItem(CONSTANTS.KEY_DEVICE_REGISTRATION_STATUS, CONSTANTS.DEVICE_REGISTRATION_STATUS_UNREGISTERED); // emit event this.eventBus.dispatchEvent('unsubscribe', {}); return response; } public async messageDeliveryEvent(hash: string, isTrackingLogOnFailure?: boolean, metaData: {[key: string]: any} = {}): Promise<IMapResponse['messageDeliveryEvent']> { const startTime = Math.round(+new Date()); const params = await this.getRequestParams(); try { return await this.apiClient.messageDeliveryEvent({ ...params, hash, metaData }); } catch (error) { if (isTrackingLogOnFailure) { this.trackLog( 'messageDeliveryEvent', { ...params, hash, metaData }, { startTime, error } ); } throw error; } } public async pushStat(hash: string, isTrackingLogOnFailure?: boolean, metaData: {[key: string]: any} = {}): Promise<IMapResponse['pushStat']> { const startTime = Math.round(+new Date()); const params = await this.getRequestParams(); try { return await this.apiClient.pushStat({ ...params, hash, metaData, }); } catch (error) { if (isTrackingLogOnFailure) { this.trackLog( 'pushStat', { ...params, hash, metaData }, { startTime, error } ); } throw error; } } public async setTags(tags: { [key: string]: any }): Promise<IMapResponse['setTags']> { const params = await this.getRequestParams(); return this.apiClient.setTags({ ...params, tags, }); } public async getTags(): Promise<IMapResponse['getTags']> { const params = await this.getRequestParams(); return this.apiClient.getTags(params); } public async registerUser(userId: string | number): Promise<IMapResponse['registerUser']> { const params = await this.getRequestParams(); const deviceType = await this.data.getDeviceType(); const id = `${userId}`; // register user in pushwoosh const response = await this.apiClient.registerUser({ ...params, userId: id, ts_offset: -(new Date).getTimezoneOffset() * 60, device_type: deviceType }); // set user id to database await this.data.setUserId(`${userId}`); // set info to database that user id was change await this.data.setStatusUserIdWasChanged(true); return response; } public async postEvent(event: string, attributes: { [key: string]: any }): Promise<IMapResponse['postEvent']> { const params = await this.getRequestParams(); const date = new Date(); const time = date.getTime(); const timestampUTC = Math.floor(time / 1000); const timestampCurrent = timestampUTC - (date.getTimezoneOffset() / 60 * 3600); // if post event send after notification open: // need add message hash to event const lastOpenMessage = await this.data.getLastOpenMessage(); if (lastOpenMessage && lastOpenMessage.expiry > Date.now()) { if (attributes['msgHash']) { return Promise.reject('attribute msgHash already defined'); } attributes = { ...attributes, msgHash: lastOpenMessage.messageHash }; } // remove last open message await this.data.setLastOpenMessage(undefined); const response = await this.apiClient.postEvent({ ...params, event, timestampUTC, timestampCurrent, attributes, }); if (response && response.code) { this.eventBus.dispatchEvent('receive-in-app-code', { code: response.code }); } return response; } public async getInboxMessages(count: number = 0): Promise<IMapResponse['getInboxMessages']> { const params = await this.getRequestParams(); const lastCode = await this.data.getInboxLastRequestCode(); const lastRequestTime = await this.data.getInboxLastRequestTime(); return this.apiClient.getInboxMessages({ ...params, ...{ count, last_code: lastCode, last_request_time: lastRequestTime }, }); } public async inboxStatus(order: string, status: number): Promise<IMapResponse['inboxStatus']> { const params = await this.getRequestParams(); return this.apiClient.inboxStatus({ ...params, ...{ inbox_code: order, status, time: (new Date()).getTime(), } }); } public async triggerEvent(): Promise<void> { throw new Error(`Method has been deprecated, because we don't aggregate this statistics.`); } public async pageVisit(config: { title: string, url_path: string, url: string }): Promise<IMapResponse['pageVisit']> { const params = await this.getRequestParams(); const features = await this.data.getFeatures(); const url = features && features.page_visit && features.page_visit.entrypoint; if (!url) { return; } return this.apiClient.pageVisit({ ...params, ...config, }, url); } public async getInApps(): Promise<IMapResponse['getInApps']> { const params = await this.getRequestParams(); return this.apiClient.getInApps(params); } public async setPurchase(attributes: SetPurchaseAttributes): Promise<IMapResponse['setPurchase']> { const params = await this.getRequestParams(); return this.apiClient.setPurchase({ ...params, ...attributes, }); } public async getParams() { const applicationCode = await this.data.getApplicationCode(); const hwid = await this.data.getHwid(); const apiParams = await this.data.getTokens(); const initParams = await this.data.getInitParams(); return { applicationCode, hwid, ...apiParams, ...initParams, }; } public get params(): void { throw new Error('Property "Pushwoosh.api.params" have been deprecated. Use the async method "Pushwoosh.api.getParams()"'); } private async getRequestParams(): Promise<IRequest> { const applicationCode = await this.data.getApplicationCode(); const hwid = await this.data.getHwid(); const userId = await this.data.getUserId(); const deviceType = await this.data.getDeviceType(); const deviceModel = await this.data.getDeviceModel(); const language = await this.data.getLanguage(); const version = await this.data.getSdkVersion(); const timezone = -(new Date).getTimezoneOffset() * 60; return { application: applicationCode, hwid: hwid, userId: userId || hwid, device_type: deviceType, device_model: deviceModel, timezone: timezone, language: language, v: version, }; }; private async trackLog<Method extends TMethod>(method: Method, payload: IMapRequest[Method], others: { [key: string]: any }): Promise<void> { const endTime = Math.round(+new Date()); const entrypoint = await this.data.getApiEntrypoint(); fetch('https://post-log.pushwoosh.com/websdk', { method: 'POST', headers: { 'Content-Type': 'text/plain;charset=UTF-8' }, body: JSON.stringify({ payload, startTime: others.startTime, endTime, executionTime: endTime - others.startTime, error: { code: others.error.code, message: others.error.message, }, method, entrypoint, location: { hostname: self.location.hostname, origin: self.location.origin, pathname: self.location.pathname, }, type: 'websdk', }), }); } }
the_stack
import * as JSONX from "./index"; import mochaJSDOM from "jsdom-global"; import chai from "chai"; import sinon from "sinon"; import React from "react"; import ReactTestUtils from "react-dom/test-utils"; // ES6 import ReactDOM from "react-dom"; import ReactDOMElements from "react-dom-factories"; import { expect as expectCHAI } from "chai"; import { JSDOM } from "jsdom"; import numeral from "numeral"; import * as luxon from "luxon"; chai.use(require("sinon-chai")); // import 'mocha-sinon'; const _jsonxChildren = JSONX._jsonxChildren; const sampleJSONX = { component: "div", props: { id: "generatedJSONX", className: "jsonx" }, children: [ { component: "p", props: { style: { color: "red", fontWeight: "bold" } }, children: "hello world" }, { component: "div", children: [ { component: "ul", children: [ { component: "li", children: "hey" }, { component: "li", children: "in" }, { component: "li", children: "list" } ] } ] } ] }; const passableJSONX = { component: "div", props: { title: "this is passed", style: { color: "red" } }, passprops: true, children: [ { component: "span", props:{}, children: "should have props" }, { component: "p", props: { style: { color: "blue" } }, children: "but no style" } ] }; describe("jsonx", function() { describe("getChildrenProperty", () => { const getChildrenProperty = _jsonxChildren.getChildrenProperty; it("should return the children of an JSONX Object", () => { const JSONXChildren = getChildrenProperty({ jsonx: sampleJSONX }); const JSONXChildrenPTag = getChildrenProperty({ jsonx: sampleJSONX.children[0] }); expectCHAI(JSONXChildren).to.be.an("array"); expectCHAI(JSONXChildren.length).to.eql(sampleJSONX.children.length); expectCHAI(JSONXChildrenPTag).to.be.a("string"); expectCHAI(JSONXChildrenPTag).to.eql(sampleJSONX.children[0].children); expectCHAI( getChildrenProperty({ jsonx: { props: { _children: {} }, children: "hello" } }) ).to.eql("hello"); expectCHAI( getChildrenProperty({ jsonx: {} }) ).to.eql(null); expectCHAI(getChildrenProperty({ props: { children: [1, 2, 3] } })).to.be.an( "array" ); expectCHAI( getChildrenProperty({ jsonx: { props: { children: "hello" } } }) ).to.eql("hello"); }); it("should get the children from jsonx.props._children property", () => { const testJSONX = { component: "div", props: { _children: "some text" } }; const testJSONX2 = { component: "div", props: { _children: [ { component: "p", children: "nested p tag" }, { component: "p", children: "nested p tag" } ] } }; const testJSONX3 = { component: "div", props: { _children: "some text", children: "ignore this prop for children" }, children: [ { component: "p", children: "should ignore nested p tag" }, { component: "p", children: "should ignore nested p tag" } ] }; const JSONXChildren = getChildrenProperty({ jsonx: testJSONX }); const JSONXChildren2 = getChildrenProperty({ jsonx: testJSONX2 }); const JSONXChildren3 = getChildrenProperty({ jsonx: testJSONX3 }); expectCHAI(JSONXChildren).to.be.a("string"); expectCHAI(JSONXChildren).to.eql(testJSONX.props._children); expectCHAI(JSONXChildren2).to.be.an("array"); expectCHAI(JSONXChildren2.length).to.eql(testJSONX2.props._children.length); expectCHAI(JSONXChildren3).to.be.a("string"); expectCHAI(JSONXChildren3).to.eql(testJSONX3.props._children); }); it("should get the children from jsonx.props.children property", () => { const testJSONX = { component: "div", props: { children: "some text" } }; const testJSONX2 = { component: "div", props: { children: [ { component: "p", children: "nested p tag" }, { component: "p", children: "nested p tag" } ] } }; const testJSONX3 = { component: "div", props: { children: "ignore this prop for children" }, children: [ { component: "p", children: "should ignore nested p tag" }, { component: "p", children: "should ignore nested p tag" } ] }; const testJSONX4 = { component: "div", props: { children: () => "not valid, should be null" } }; const JSONXChildren = getChildrenProperty({ jsonx: testJSONX }); const JSONXChildren2 = getChildrenProperty({ jsonx: testJSONX2 }); const JSONXChildren3 = getChildrenProperty({ jsonx: testJSONX3 }); const JSONXChildren4 = getChildrenProperty({ jsonx: testJSONX4 }); expectCHAI(JSONXChildren).to.be.a("string"); expectCHAI(JSONXChildren).to.eql(testJSONX.props.children); expectCHAI(JSONXChildren2).to.be.an("array"); expectCHAI(JSONXChildren2.length).to.eql(testJSONX2.props.children.length); expectCHAI(JSONXChildren3).to.be.a("array"); expectCHAI(JSONXChildren3).to.eql(testJSONX3.children); expectCHAI(JSONXChildren4).to.be.a("function"); }); }); describe("getChildrenProps", () => { const getChildrenProps = _jsonxChildren.getChildrenProps.bind({}); const getChildrenProperty = _jsonxChildren.getChildrenProperty; it("should return child JSONX if not passing props", () => { const renderIndex = 1; const childjsonx = getChildrenProperty({ jsonx: sampleJSONX })[0]; const childProps = getChildrenProps({ jsonx: sampleJSONX, childjsonx, renderIndex }); expectCHAI(childProps).to.eq(childjsonx); }); it("should pass props except for styles", () => { const renderIndex = 1; const childjsonx_span = getChildrenProperty({ jsonx: passableJSONX })[0]; const childjsonx_p = getChildrenProperty({ jsonx: passableJSONX })[1]; const childProps_span = getChildrenProps({ jsonx: passableJSONX, childjsonx: childjsonx_span, renderIndex }); const childProps_p = getChildrenProps({ jsonx: passableJSONX, childjsonx: childjsonx_p, renderIndex }); //@ts-ignore expectCHAI(childProps_span.props.title).to.eq(passableJSONX.props.title); //@ts-ignore expectCHAI(childProps_p.props.title).to.eq(passableJSONX.props.title); //@ts-ignore expectCHAI(childProps_p.props.style.color).to.eq( //@ts-ignore passableJSONX.children[1].props.style.color ); //@ts-ignore expectCHAI(childProps_p.props.key).to.not.eq(renderIndex); //@ts-ignore expectCHAI(childProps_span.props.key).to.not.eq(renderIndex); }); it('should only pass selected props',()=>{ const renderIndex = 1; const passableSelectedJSONX = { component: "div", props: { title: "this is passed", anotherProp:true, additionalProp:true, value:302, size:2 }, passprops: ['value','size'], children: [ { component: "span", props:{}, children: "should have props" }, { component: "p", props: { style: { color: "blue" } }, children: "but no style" } ] }; const childjsonx_span = getChildrenProperty({ jsonx: passableSelectedJSONX })[0]; const childProps_span = getChildrenProps({ jsonx: passableSelectedJSONX, childjsonx: childjsonx_span, renderIndex }); //@ts-ignore expectCHAI(childProps_span.props).to.eql({ value: 302, size: 2 }) }) }); describe("getJSONXChildren", () => { const getJSONXChildren = _jsonxChildren.getJSONXChildren; const testDate = new Date(); const testDateISO = testDate.toISOString(); const luxonFormat = "LL/dd/yyyy"; it("should work with JSON", () => { const getJSONXChildren = _jsonxChildren.getJSONXChildren.bind({ returnJSON: true }); const JXM = { component: "ol", // props: { data: "ok" } children: [null, null, null] // children: [ // { component: "li", children: "1st" }, // { component: "li", children: "2nd" }, // { component: "li", children: "3rd" }, // { component: "li", children: "4th" } // ] }; // const JXMChildrenJSON = getJSONXChildren({ jsonx: JXM }); }); it("should return JSONX Child Objects", () => { const renderIndex = 1; const JSONXChildren = getJSONXChildren.call( {}, { jsonx: passableJSONX, renderIndex } ); //@ts-ignore JSONXChildren.forEach(ReactiveJSON => { expectCHAI(ReactiveJSON).to.be.an("object"); expectCHAI(ReactiveJSON).to.haveOwnProperty("$$typeof"); expectCHAI(ReactiveJSON).to.haveOwnProperty("type"); expectCHAI(ReactiveJSON).to.haveOwnProperty("key"); expectCHAI(ReactiveJSON).to.haveOwnProperty("ref"); expectCHAI(ReactiveJSON).to.haveOwnProperty("props"); }); }); it("should return null on error", () => { //@ts-ignore expectCHAI(getJSONXChildren.call({}, { logError: () => {} })).to.eql(null); }); it("should stringify children", () => { const obj = { some: "data", to: "stringify" }; expectCHAI( getJSONXChildren.call( {}, { jsonx: { //@ts-ignore children: obj, //@ts-ignore ___stringifyChildren: [null, 2] } } ) ).to.eql(JSON.stringify(obj, null, 2)); //normal stringify expectCHAI( //@ts-ignore getJSONXChildren( { jsonx: { //@ts-ignore children: obj, //@ts-ignore ___stringifyChildren: true } } ) ).to.eql(JSON.stringify(obj, null, 2)); }); it("should toString children", () => { const obj = { some: "data", to: "stringify" }; const testDate = new Date(); expectCHAI( getJSONXChildren.call( {}, { jsonx: { //@ts-ignore children: obj, //@ts-ignore ___toStringChildren: true } } ) ).to.eql(obj.toString()); expectCHAI( getJSONXChildren.call( {}, { jsonx: { component: 'div', children: testDate, ___toStringChildren: true } } ) ).to.eql(testDate.toString()); }); it("should convert children to numeral formatted string", () => { const numeralValue = 1500.23; const numeralFormat = "0,0"; const numeralFormattedString = numeral(numeralValue).format( numeralFormat ); expectCHAI( //@ts-ignore getJSONXChildren.call( {}, { jsonx: { //@ts-ignore children: numeralValue, ___toNumeral: numeralFormat } } ) ).to.eql(numeralFormattedString); }); it("should convert children date object to luxon formatted string", () => { const testLuxonFormat = luxon.DateTime.fromJSDate(testDate).toFormat( luxonFormat ); // console.log({ testDate, testDateISO, luxonFormat, testLuxonFormat }); expectCHAI( getJSONXChildren.call( {}, { jsonx: { children: testDate, ___JSDatetoLuxonString: luxonFormat } } ) ).to.eql(testLuxonFormat); }); it("should convert children iso string to luxon formatted string", () => { const testLuxonFormat = luxon.DateTime.fromISO(testDateISO).toFormat( luxonFormat ); expectCHAI( getJSONXChildren.call( {}, { jsonx: { children: testDateISO, ___ISOtoLuxonString: luxonFormat } } ) ).to.eql(testLuxonFormat); }); it("should import templates into children", () => { const importedTemplate = JSONX._jsonxChildren.getJSONXChildren.call( //@ts-ignore { returnJSON: true, debug:true }, { jsonx: { component: "Fragment", ___template: "./src/mock/simple_template.jxm.json" } } ); expectCHAI(_jsonxChildren.templateCache).to.be.lengthOf(1); expectCHAI(importedTemplate).to.be.an("array"); //@ts-ignore expectCHAI(importedTemplate[0].type).to.eql("div"); //@ts-ignore expectCHAI(importedTemplate[0].children).to.eql("from external template"); }); }); describe('fetchJSONSync', () => { const fetchJSONSync = _jsonxChildren.fetchJSONSync; const xmlhttpreq ={ status: 200, responseText: '{"some":"data"}', DONE: 1, HEADERS_RECEIVED: 1, LOADING: 1, OPENED: 1, UNSENT: 1, } it('should returns sync json',()=>{ const returnJSON = { open : jest.fn(), send : jest.fn(), setRequestHeader: jest.fn(), } const xhrMockClass = () => ({ ...returnJSON, ...xmlhttpreq }) //@ts-ignore window.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass) const response = fetchJSONSync('/mock-endpoint') expect(response).toBe('{"some":"data"}') expect(returnJSON.open).toHaveBeenCalledTimes(1) expect(returnJSON.send).toHaveBeenCalledTimes(1) expect(returnJSON.setRequestHeader).toHaveBeenCalledTimes(0) }); it('should apply custom headers',()=>{ const cusomtHEADER = { open : jest.fn(), send : jest.fn(), setRequestHeader: jest.fn(), } const xhrMockClass = () => ({ ...cusomtHEADER, ...xmlhttpreq }); //@ts-ignore window.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass) const response = fetchJSONSync('/mock-endpoint',{headers:[{user:'testUser'}]}) expect(response).toBe('{"some":"data"}') expect(cusomtHEADER.open).toHaveBeenCalledTimes(1) expect(cusomtHEADER.send).toHaveBeenCalledTimes(1) expect(cusomtHEADER.setRequestHeader).toHaveBeenCalledTimes(1) }); it('should handle request errors',()=>{ const handleError = { open : jest.fn(), send : jest.fn(), setRequestHeader: jest.fn(), } const xhrMockClass = () => ({ ...handleError, ...xmlhttpreq, status: 500, responseText: 'Testing Response Errors', }); //@ts-ignore window.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass) expect(()=>{ fetchJSONSync('/mock-endpoint') }).toThrow('Testing Response Errors') // const response = fetchJSONSync('/mock-endpoint') // console.log({response}) // expect(response).toBe('{"some":"data"}') expect(handleError.open).toHaveBeenCalledTimes(1) expect(handleError.send).toHaveBeenCalledTimes(1) expect(handleError.setRequestHeader).toHaveBeenCalledTimes(0) }); }); describe('getChildrenTemplate',()=>{ const {getChildrenTemplate,templateCache,clearTemplateCache} = _jsonxChildren; it('should fetch json templates via ajax',()=>{ const xhrMockClass = () => ({ open : jest.fn(), send : jest.fn(), setRequestHeader: jest.fn(), status: 200, responseText: '{"some":"data"}', DONE: 1, HEADERS_RECEIVED: 1, LOADING: 1, OPENED: 1, UNSENT: 1, }); //@ts-ignore window.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass) //@ts-ignore const response = getChildrenTemplate('/mock-endpoint','fetch') expect(response).toMatchObject({ some: 'data' }) }) it('should handle no input',()=>{ //@ts-ignore const response = getChildrenTemplate() expect(response).toBe(null) }) it('should clear cache w/clearTemplateCache',()=>{ expect(()=>{ clearTemplateCache() }).not.toThrow() expect(templateCache.size).toBe(0) }) }) });
the_stack
import {assert} from 'chrome://resources/js/assert.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {FilePath} from 'chrome://resources/mojo/mojo/public/mojom/base/file_path.mojom-webui.js'; import {Url} from 'chrome://resources/mojo/url/mojom/url.mojom-webui.js'; import {isNonEmptyArray} from '../../common/utils.js'; import {WallpaperCollection, WallpaperImage, WallpaperLayout, WallpaperProviderInterface, WallpaperType} from '../personalization_app.mojom-webui.js'; import {PersonalizationStore} from '../personalization_store.js'; import {isFilePath, isWallpaperImage} from '../utils.js'; import * as action from './wallpaper_actions.js'; /** * @fileoverview contains all of the functions to interact with C++ side through * mojom calls. Handles setting |PersonalizationStore| state in response to * mojom data. */ /** Fetch wallpaper collections and save them to the store. */ export async function fetchCollections( provider: WallpaperProviderInterface, store: PersonalizationStore): Promise<void> { let {collections} = await provider.fetchCollections(); if (!isNonEmptyArray(collections)) { console.warn('Failed to fetch wallpaper collections'); collections = null; } store.dispatch(action.setCollectionsAction(collections)); } /** Helper function to fetch and dispatch images for a single collection. */ async function fetchAndDispatchCollectionImages( provider: WallpaperProviderInterface, store: PersonalizationStore, collection: WallpaperCollection): Promise<void> { let {images} = await provider.fetchImagesForCollection(collection.id); if (!isNonEmptyArray(images)) { console.warn('Failed to fetch images for collection id', collection.id); images = null; } store.dispatch(action.setImagesForCollectionAction(collection.id, images)); } /** Fetch all of the wallpaper collection images in parallel. */ async function fetchAllImagesForCollections( provider: WallpaperProviderInterface, store: PersonalizationStore): Promise<void> { const collections = store.data.wallpaper.backdrop.collections; if (!Array.isArray(collections)) { console.warn( 'Cannot fetch data for collections when it is not initialized'); return; } store.dispatch(action.beginLoadImagesForCollectionsAction(collections)); await Promise.all(collections.map( collection => fetchAndDispatchCollectionImages(provider, store, collection))); } /** * Fetches the list of Google Photos photos for the album associated with the * specified id and saves it to the store. */ export async function fetchGooglePhotosAlbum( _: WallpaperProviderInterface, store: PersonalizationStore, albumId: string): Promise<void> { store.dispatch(action.beginLoadGooglePhotosAlbumAction(albumId)); // TODO(dmblack): Create and wire up mojo API. For now, simulate an async // request that returns a list of 1,000 Google Photos photos. return new Promise(resolve => setTimeout(() => { store.dispatch(action.setGooglePhotosAlbumAction( albumId, Array.from({length: 1000}))); resolve(); }, 1000)); } /** Fetches the list of Google Photos albums and saves it to the store. */ async function fetchGooglePhotosAlbums( _: WallpaperProviderInterface, store: PersonalizationStore): Promise<void> { store.dispatch(action.beginLoadGooglePhotosAlbumsAction()); // TODO(dmblack): Create and wire up mojo API. For now, simulate an async // request that returns a list of fictitious Google Photos albums. return new Promise(resolve => setTimeout(() => { store.dispatch(action.setGooglePhotosAlbumsAction([ '9bd1d7a3-f995-4445-be47-53c5b58ce1cb', '0ec40478-9712-42e1-b5bf-3e75870ca042', '0a268a37-877a-4936-81d4-38cc84b0f596', '27597eb3-a42d-474c-ab39-592680dcf35a', 'bdcd6ba5-ed70-4866-9bc0-87ccf87db08c', ].map((uuid, i) => { const album = new WallpaperCollection(); album.id = uuid; album.name = `Album ${i}`; return album; }))); resolve(); }, 1000)); } /** Fetches the count of Google Photos photos and saves it to the store. */ async function fetchGooglePhotosCount( provider: WallpaperProviderInterface, store: PersonalizationStore): Promise<void> { store.dispatch(action.beginLoadGooglePhotosCountAction()); const {count} = await provider.fetchGooglePhotosCount(); store.dispatch(action.setGooglePhotosCountAction(count >= 0 ? count : null)); } /** Fetches the list of Google Photos photos and saves it to the store. */ async function fetchGooglePhotosPhotos( _: WallpaperProviderInterface, store: PersonalizationStore): Promise<void> { store.dispatch(action.beginLoadGooglePhotosPhotosAction()); // TODO(dmblack): Create and wire up mojo API. For now, simulate an async // request that returns a list of 1,000 Google Photos photos. return new Promise( resolve => setTimeout(() => { // Temporarily use hard-coded URLs from the solid colors backdrop // collection since the backdrop server is already allowlisted with the // untrusted iframe's content security policy. const urls = [ 'https://lh6.googleusercontent.com/proxy/dVgC6TzmRH-4uhdcqZK37RyRErOz46Y4S9W8Pw3tfRHyPluwELODHfvrx-SorsUFq5YphXy1VXIxQO2oXlF7GfjeRLY4hsH9c20FqCM4Tpk', 'https://lh6.googleusercontent.com/proxy/qcBQd3OJ8qwQeFvAb0p23WJau6s1w5RQ0UAUFD1bm56SVBgP1X7-LAfv2_uF47-9Dd6v_fCVKYVU6SCsorTxMRahBSdv6of9FBdReaoqPg', 'https://lh6.googleusercontent.com/proxy/fahpL4TekPUgLhKJQ289ISWz_FPG9XutzfjqBiSdDhxjuBfZ7SjlE4j58rg9wzEsu9NcQ0Yrm0B5NW_MWaLbX0TWJ5yRDVH1z-Zf', 'https://lh6.googleusercontent.com/proxy/dVgC6TzmRH-4uhdcqZK37RyRErOz46Y4S9W8Pw3tfRHyPluwELODHfvrx-SorsUFq5YphXy1VXIxQO2oXlF7GfjeRLY4hsH9c20FqCM4Tpk', 'https://lh6.googleusercontent.com/proxy/5ftru2Wt8g3R7r4TzRAOhJD7jMpLWOiqKxgql3vd_s26EnV51M5WfJe-ZJZkrMnqbOQ4uB1iBycwwGziEVYCwMeRx2Tcdmiq2lH44hUD3OLX', 'https://lh6.googleusercontent.com/proxy/qcBQd3OJ8qwQeFvAb0p23WJau6s1w5RQ0UAUFD1bm56SVBgP1X7-LAfv2_uF47-9Dd6v_fCVKYVU6SCsorTxMRahBSdv6of9FBdReaoqPg', ]; store.dispatch(action.setGooglePhotosPhotosAction( Array.from({length: 1000}) .map((_, i) => ({url: urls[i % urls.length]})))); resolve(); }, 1000)); } /** Get list of local images from disk and save it to the store. */ export async function getLocalImages( provider: WallpaperProviderInterface, store: PersonalizationStore): Promise<void> { store.dispatch(action.beginLoadLocalImagesAction()); const {images} = await provider.getLocalImages(); if (images == null) { console.warn('Failed to fetch local images'); } store.dispatch(action.setLocalImagesAction(images)); } /** * Because thumbnail loading can happen asynchronously and is triggered * on page load and on window focus, multiple "threads" can be fetching * thumbnails simultaneously. Synchronize them with a task queue. */ const imageThumbnailsToFetch = new Set<FilePath['path']>(); /** * Get an image thumbnail one at a time for every local image that does not have * a thumbnail yet. */ async function getMissingLocalImageThumbnails( provider: WallpaperProviderInterface, store: PersonalizationStore): Promise<void> { if (!Array.isArray(store.data.wallpaper.local.images)) { console.warn('Cannot fetch thumbnails with invalid image list'); return; } // Set correct loading state for each image thumbnail. Do in a batch update to // reduce number of times that polymer must re-render. store.beginBatchUpdate(); for (const filePath of store.data.wallpaper.local.images) { if (store.data.wallpaper.local.data[filePath.path] || store.data.wallpaper.loading.local.data[filePath.path] || imageThumbnailsToFetch.has(filePath.path)) { // Do not re-load thumbnail if already present, or already loading. continue; } imageThumbnailsToFetch.add(filePath.path); store.dispatch(action.beginLoadLocalImageDataAction(filePath)); } store.endBatchUpdate(); // There may be multiple async tasks triggered that pull off this queue. while (imageThumbnailsToFetch.size) { const path = imageThumbnailsToFetch.values().next().value; imageThumbnailsToFetch.delete(path); const {data} = await provider.getLocalImageThumbnail({path}); if (!data) { console.warn('Failed to fetch local image data', path); } store.dispatch(action.setLocalImageDataAction({path}, data)); } } export async function selectWallpaper( image: WallpaperImage|FilePath, provider: WallpaperProviderInterface, store: PersonalizationStore, layout: WallpaperLayout = WallpaperLayout.kCenterCropped): Promise<void> { // Batch these changes together to reduce polymer churn as multiple state // fields change quickly. store.beginBatchUpdate(); store.dispatch(action.beginSelectImageAction(image)); store.dispatch(action.beginLoadSelectedImageAction()); const {tabletMode} = await provider.isInTabletMode(); const shouldPreview = tabletMode && loadTimeData.getBoolean('fullScreenPreviewEnabled'); store.endBatchUpdate(); const {success} = await (() => { if (isWallpaperImage(image)) { return provider.selectWallpaper( image.assetId, /*preview_mode=*/ shouldPreview); } else if (isFilePath(image)) { return provider.selectLocalImage( image, layout, /*preview_mode=*/ shouldPreview); } else { console.warn('Image must be a local image or a WallpaperImage'); return {success: false}; } })(); store.beginBatchUpdate(); store.dispatch(action.endSelectImageAction(image, success)); // Delay opening full screen preview until done loading. This looks better if // the image load takes a long time, otherwise the user will see the old // wallpaper image for a while. if (success && shouldPreview) { store.dispatch(action.setFullscreenEnabledAction(/*enabled=*/ true)); } if (!success) { console.warn('Error setting wallpaper'); store.dispatch( action.setSelectedImageAction(store.data.wallpaper.currentSelected)); } store.endBatchUpdate(); } /** * @param {!WallpaperLayout} layout * @param {!WallpaperProviderInterface} provider * @param {!PersonalizationStore} store */ export async function setCustomWallpaperLayout( layout: WallpaperLayout, provider: WallpaperProviderInterface, store: PersonalizationStore): Promise<void> { const image = store.data.wallpaper.currentSelected; assert(image && image.type === WallpaperType.kCustomized); assert( layout === WallpaperLayout.kCenter || layout === WallpaperLayout.kCenterCropped); if (image?.layout === layout) { return; } store.dispatch(action.beginLoadSelectedImageAction()); await provider.setCustomWallpaperLayout(layout); } export async function setDailyRefreshCollectionId( collectionId: WallpaperCollection['id'], provider: WallpaperProviderInterface, store: PersonalizationStore): Promise<void> { await provider.setDailyRefreshCollectionId(collectionId); // Dispatch action to highlight enabled daily refresh. getDailyRefreshCollectionId(provider, store); } /** * Get the daily refresh collection id. It can be empty if daily refresh is not * enabled. */ export async function getDailyRefreshCollectionId( provider: WallpaperProviderInterface, store: PersonalizationStore): Promise<void> { const {collectionId} = await provider.getDailyRefreshCollectionId(); store.dispatch(action.setDailyRefreshCollectionIdAction(collectionId)); } /** Refresh the wallpaper. Noop if daily refresh is not enabled. */ export async function updateDailyRefreshWallpaper( provider: WallpaperProviderInterface, store: PersonalizationStore): Promise<void> { store.dispatch(action.beginUpdateDailyRefreshImageAction()); store.dispatch(action.beginLoadSelectedImageAction()); const {success} = await provider.updateDailyRefreshWallpaper(); if (success) { store.dispatch(action.setUpdatedDailyRefreshImageAction()); } } /** Confirm and set preview wallpaper as actual wallpaper. */ export async function confirmPreviewWallpaper( provider: WallpaperProviderInterface): Promise<void> { await provider.confirmPreviewWallpaper(); } /** Cancel preview wallpaper and show the previous wallpaper. */ export async function cancelPreviewWallpaper( provider: WallpaperProviderInterface): Promise<void> { await provider.cancelPreviewWallpaper(); } /** * Fetches list of collections, then fetches list of images for each * collection. */ export async function initializeBackdropData( provider: WallpaperProviderInterface, store: PersonalizationStore): Promise<void> { await fetchCollections(provider, store); await fetchAllImagesForCollections(provider, store); } /** Fetches initial Google Photos data and saves it to the store. */ export async function initializeGooglePhotosData( provider: WallpaperProviderInterface, store: PersonalizationStore): Promise<void> { await fetchGooglePhotosCount(provider, store); // If the count of Google Photos photos is zero or null, it's not necesssary // to query the server for the list of albums/photos. const count = store.data.wallpaper.googlePhotos.count; if (count === 0 || count === null) { const /** ?Array<undefined> */ result = count === 0 ? [] : null; store.beginBatchUpdate(); store.dispatch(action.beginLoadGooglePhotosAlbumsAction()); store.dispatch(action.beginLoadGooglePhotosPhotosAction()); store.dispatch(action.setGooglePhotosAlbumsAction(result)); store.dispatch(action.setGooglePhotosPhotosAction(result)); store.endBatchUpdate(); return; } await Promise.all([ fetchGooglePhotosAlbums(provider, store), fetchGooglePhotosPhotos(provider, store), ]); } /** * Gets list of local images, then fetches image thumbnails for each local * image. */ export async function fetchLocalData( provider: WallpaperProviderInterface, store: PersonalizationStore): Promise<void> { // Do not restart loading local image list if a load is already in progress. if (!store.data.wallpaper.loading.local.images) { await getLocalImages(provider, store); } await getMissingLocalImageThumbnails(provider, store); }
the_stack
import * as vscode from 'vscode'; import { angularCollectionName, extensionName } from '../defaults'; import { Output, FileSystem, Terminals } from '../utils'; import { Workspace, WorkspaceFolderConfig } from '../workspace'; import { Collection, Schematic } from '../workspace/schematics'; import { shortcutsConfirmationChoices, SHORTCUTS_CONFIRMATION_LABEL, MODULE_TYPE } from '../workspace/shortcuts'; import { CliCommand } from './cli-command'; import { CliCommandOptions, dasherize, formatCliCommandOptions } from './cli-options'; export class UserJourney { private static shortcutSchematics = ['component', 'service', 'module']; private workspaceFolder!: WorkspaceFolderConfig; private cliCommand!: CliCommand; private projectName = ''; private collection!: Collection; private schematic!: Schematic; async start(contextUri?: vscode.Uri, collectionName?: string, schematicName?: string): Promise<void> { /* As the configurations are loaded in an async way, they may not be ready */ try { /* Show progress to the user */ await vscode.window.withProgress({ location: vscode.ProgressLocation.Window, title: `${extensionName}: loading configuration, please wait...`, }, () => Workspace.whenStable()); } catch { Output.showError(`Loading configurations needed for ${extensionName} extension was too long. Check Output channel for error logs.`); return; } let workspaceFolder: WorkspaceFolderConfig | undefined; /* Get workspace folder configuration */ try { workspaceFolder = await Workspace.askFolder(contextUri); } catch { Output.showError(`No valid Angular config file found for the chosen workspace. Add a "angular.json" file in your project with \`{ "version": 1 }\``); return; } if (!workspaceFolder) { Output.logInfo(`You have canceled the workspace folder choice.`); return; } this.workspaceFolder = workspaceFolder; Output.logInfo(`Workspace folder selected: "${workspaceFolder.name}"`); this.cliCommand = new CliCommand(workspaceFolder, contextUri); /* If the project has not been already resolved via context path (in `CliCommand` constructor) * and if the Angular projects have been correctly resolved from config */ if (!this.cliCommand.getProjectName() && (this.workspaceFolder.getAngularProjects().size > 0)) { const projectName = await this.askProjectName(); if (!projectName) { Output.logInfo(`You have canceled the Angular project choice.`); return; } this.cliCommand.setProjectName(projectName); } this.projectName = this.cliCommand.getProjectName(); if (this.projectName) { Output.logInfo(`Angular project used: "${this.cliCommand.getProjectName()}"`); } /* Collection may be already defined (from shortcut command or from view) */ if (!collectionName) { try { collectionName = await this.askCollectionName(); } catch { /* Happens if `@schematics/angular` is not installed */ this.showCollectionMissingErrorWithFix(angularCollectionName).catch(() => {}); return; } if (!collectionName) { Output.logInfo(`You have canceled the collection choice.`); return; } } Output.logInfo(`Collection used: "${collectionName}"`); this.cliCommand.setCollectionName(collectionName); const collection = this.workspaceFolder.collections.getCollection(collectionName); if (!collection) { this.showCollectionMissingErrorWithFix(collectionName).catch(() => {}); return; } this.collection = collection; /* Schematic may be already defined (from shortcut command or from view) */ if (!schematicName) { schematicName = await this.askSchematicName(); if (!schematicName) { Output.logInfo(`You have canceled the schematic choice.`); return; } } Output.logInfo(`Schematic used: "${collectionName}:${schematicName}"`); const schematic = this.collection.getSchematic(schematicName); if (!schematic) { Output.showError(`Cannot load "${collectionName}:${schematicName}" schematic. See Output channel for error logs.`); return; } this.schematic = schematic; this.cliCommand.setSchematic(schematic); /* Project can only be validated once the schematic is here */ if (!await this.cliCommand.validateProject()) { /* If no project or path has been detected, user is asked about the source path */ const sourcePath = await this.askSourcePath(); if (!sourcePath) { Output.logInfo(`You have canceled the source path choice.`); return; } this.cliCommand.addOptions([['path', sourcePath]]); } let nameAsFirstArg: string | undefined; if (this.schematic.hasNameAsFirstArg()) { Output.logInfo(`This schematic has a default argument to set the path and name.`); nameAsFirstArg = await this.askNameAsFirstArg(); if (!nameAsFirstArg) { Output.logInfo(`You have canceled the default argument input.`); return; } this.cliCommand.setNameAsFirstArg(nameAsFirstArg); } let shortcutConfirm: boolean | undefined = false; /* Quicker scenario for basic schematics (component, service, module of official schematics) */ if ((collectionName === angularCollectionName) && UserJourney.shortcutSchematics.includes(schematicName)) { let shortcutOptions: CliCommandOptions | undefined; /* Special scenario for component types */ if (schematicName === 'component') { shortcutOptions = await this.askComponentOptions(); if (!shortcutOptions) { Output.logInfo(`You have canceled the component type choice.`); return; } /* Special scenario for module types */ } else if (schematicName === 'module') { /* We know that Angular module schematics has a name as first argument */ shortcutOptions = await this.askModuleOptions(); if (!shortcutOptions) { Output.logInfo(`You have canceled the module type choice.`); return; } /* A module should be imported somewhere, so ask the user */ if (!shortcutOptions.has('module')) { const whereToImportModule = await this.askWhereToImportModule(); if (whereToImportModule) { this.cliCommand.addOptions([['module', whereToImportModule]]); } } } if (shortcutOptions) { this.cliCommand.addOptions(shortcutOptions); } /* Ask direct confirmation or adding more options or cancel */ shortcutConfirm = await this.askShortcutConfirmation(); /* "Cancel" choice */ if (shortcutConfirm === undefined) { Output.logInfo(`You have canceled the generation.`); return; } } /* Ask for advanced options if user didn't choose a direct confirmation */ if (!shortcutConfirm) { const filledOptions = await this.askOptions(); this.cliCommand.addOptions(filledOptions); /* Ask final confirmation */ const confirm = await this.askConfirmation(); /* "Cancel" choice */ if (!confirm) { Output.logInfo(`You have canceled the generation.`); return; } } this.cliCommand.launchCommand(); try { /* Show progress to the user */ await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: `${extensionName}: launching the generation, please wait...`, }, () => this.jumpToFile(this.cliCommand.guessGereratedFileUri())); } catch { /* Auto-opening the file was not possible, warn the user the command is launched * and propose to refresh Explorer to see the generated files */ this.showUnknownStatus().catch(() => {}); } } private async askProjectName(): Promise<string | undefined> { /* If there is only one Angular project, default to it */ if (this.workspaceFolder.getAngularProjects().size === 1) { return Array.from(this.workspaceFolder.getAngularProjects().keys())[0]; } /* Otherwise ask the user */ else { const projectsChoices: vscode.QuickPickItem[] = Array.from(this.workspaceFolder.getAngularProjects()) .map(([label, project]) => { /* Tell if it is an application or a library, and the path */ const rawDescription = `${this.workspaceFolder.isRootAngularProject(label) ? `root ` : ''}${project.getType()} in ${project.getAppOrLibPath()}`; /* Uppercase first letter */ const description = `${rawDescription.charAt(0).toUpperCase()}${rawDescription.substr(1)}`; return { label, description, }; }); const projectChoice = await vscode.window.showQuickPick(projectsChoices, { placeHolder: `In which your Angular projects do you want to generate?`, ignoreFocusOut: true, }); return projectChoice?.label; } } private async askCollectionName(): Promise<string | undefined> { if (this.workspaceFolder.collections.getCollectionsNames().length === 0) { throw new Error(); } else if (this.workspaceFolder.collections.getCollectionsNames().length === 1) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const collectionName = this.workspaceFolder.collections.getCollectionsNames()[0]!; Output.logInfo(`Only collection detected: "${collectionName}". Default to it.`); return collectionName; } else { Output.logInfo(`Multiple collections detected: ask the user which one to use.`); return vscode.window.showQuickPick(this.workspaceFolder.collections.getCollectionsNames(), { placeHolder: `What schematics collection do you want to use?`, ignoreFocusOut: true, }); } } private async askSchematicName(): Promise<string | undefined> { const choice = await vscode.window.showQuickPick(this.collection.schematicsChoices, { placeHolder: `What schematics do you want to generate?`, ignoreFocusOut: true, }); return choice ? choice.label : undefined; } private async askSourcePath(): Promise<string | undefined> { return vscode.window.showInputBox({ prompt: `What is the source path? (Pro-tip: the extension can detect it with a correct "angular.json" or if there is an "app.module.ts" file)`, placeHolder: 'src/app', ignoreFocusOut: true, }); } // TODO: `@schematics/angular:interface` has a second argv private async askNameAsFirstArg(): Promise<string | undefined> { const projectName = this.cliCommand.getProjectName(); const contextPath = this.cliCommand.getContextForNameAsFirstArg(); Output.logInfo(`Context path detected for default argument: "${contextPath}"`); let prompt = `Choose the name${this.schematic.hasOption('path') ? ` or path/to/name` : ''}.`; /* Pro-tip to educate users that it is easier to launch the command from a right-click in Explorer */ if (this.schematic.hasOption('path') && this.workspaceFolder.isRootAngularProject(projectName) && !contextPath) { prompt = `${prompt} Pro-tip: the path can be inferred if you right-click on the directory where you want to generate.`; } const nameInput = await vscode.window.showInputBox({ prompt, /* If existing, prefill the input with the rgiht-clicked directory */ value: contextPath, /* Position the cursor to the end of the prefilled value, so the user can type directly after */ valueSelection: [contextPath.length, contextPath.length], ignoreFocusOut: true, }); /* Remove suffix (like `.component`) as Angular CLI will already add it */ const suffix = `.${this.schematic.getName()}`; const name = nameInput?.endsWith(suffix) ? nameInput.replace(suffix, '') : nameInput; return name; } private async askComponentOptions(): Promise<CliCommandOptions | undefined> { const types = this.workspaceFolder.getComponentTypes(this.projectName); const typesChoices = Array.from(types.values()).map((type) => type.choice); const typeChoice = await vscode.window.showQuickPick(typesChoices, { placeHolder: `What type of component do you want?`, ignoreFocusOut: true, }); return typeChoice ? types.get(typeChoice.label)?.options : undefined; } private async askModuleOptions(): Promise<CliCommandOptions | undefined> { const types = this.workspaceFolder.getModuleTypes(); /* Set specific route name for lazy-loaded module type */ const lazyModuleType = types.get(MODULE_TYPE.LAZY); if (lazyModuleType) { /* Usage of `posix` is important here as we are working with path with Linux separators `/` */ const routeName = this.cliCommand.getRouteFromFirstArg(); lazyModuleType.options.set('route', routeName); lazyModuleType.choice.description = formatCliCommandOptions(lazyModuleType.options); } const typesChoices = Array.from(types.values()).map((type) => type.choice); const typeChoice = await vscode.window.showQuickPick(typesChoices, { placeHolder: `What type of module do you want?`, ignoreFocusOut: true, }); return typeChoice ? types.get(typeChoice.label)?.options : undefined; } private async askWhereToImportModule(): Promise<string | undefined> { const nowhereLabel = `Nowhere`; const projectSourceUri = this.cliCommand.getProjectSourceUri(); /* Should look only in the current project */ const pattern = new vscode.RelativePattern(projectSourceUri, '**/*.module.ts'); /* Show progress to the user */ const existingModulesUris = await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: `${extensionName}: looking for existing modules, please wait...`, }, () => vscode.workspace.findFiles(pattern, undefined, 50)); const modulesChoices = existingModulesUris /* Routing module should not be proposed */ .filter((uri) => !uri.path.includes('-routing')) /* We keep only the relative module path */ .map((uri) => FileSystem.relative(projectSourceUri, uri)) /* We stop at `-10` to remove `.module.ts` */ .map((pathValue) => pathValue.substr(0, pathValue.length - 10)); if (modulesChoices.length === 0) { return undefined; } modulesChoices.unshift(nowhereLabel); const whereToImportChoice = await vscode.window.showQuickPick(modulesChoices, { placeHolder: `Where do you want to import the module?`, ignoreFocusOut: true, }); return (whereToImportChoice !== nowhereLabel) ? whereToImportChoice : undefined; } private async askShortcutConfirmation(): Promise<boolean | undefined> { const choice = await vscode.window.showQuickPick(shortcutsConfirmationChoices, { placeHolder: this.cliCommand.getCommand(), ignoreFocusOut: true, }); if (choice?.label === SHORTCUTS_CONFIRMATION_LABEL.YES) { return true; } else if (choice?.label === SHORTCUTS_CONFIRMATION_LABEL.MORE_OPTIONS) { return false; } return undefined; } private async askOptions(): Promise<CliCommandOptions> { const selectedOptionsNames = await this.askOptionsNames(); if (selectedOptionsNames) { return await this.askOptionsValues(selectedOptionsNames); } return new Map(); } private async askOptionsNames(): Promise<string[]> { const optionsChoices = this.schematic.optionsChoices; if (optionsChoices.length === 0) { return []; } const selectedOptions = await vscode.window.showQuickPick(optionsChoices, { canPickMany: true, placeHolder: `Do you need some options? (if not, just press Enter to skip this step)`, ignoreFocusOut: true, }) ?? []; return selectedOptions.map((selectedOption) => selectedOption.label); } private async askOptionsValues(optionsNames: string[]): Promise<CliCommandOptions> { /* Force required options, otherwise the schematic will fail */ const options = [...this.schematic.getRequiredOptions(), ...this.schematic.getSomeOptions(optionsNames)]; const filledOptions: CliCommandOptions = new Map<string, string | string[]>(); for (const [optionName, option] of options) { let choice: string | string[] | undefined = ''; /* Some schematics have a prompt message already defined, otherwise we use the description */ const prompt = option?.['x-prompt'] ?? option.description ?? `What value do you want for this option?`; if (option.enum !== undefined) { choice = await this.askOptionEnum(optionName, option.enum, prompt); } else if (option.type === 'boolean') { /* Put the default value first */ const choices = (option.default === false) ? ['false', 'true'] : ['true', 'false']; choice = await this.askOptionEnum(optionName, choices, prompt); } /* Only makes sense if the option is an array AND have suggestions, * otherwise the user must manually type the value in a classic text input box */ else if ((option.type === 'array')) { /* Angular >= 8.3 */ if (option.items?.enum) { choice = await this.askOptionMultiselect(optionName, option.items.enum, prompt); } else { choice = await this.askOptionText(optionName, prompt); } } else { choice = await this.askOptionText(optionName, prompt); } if (choice) { filledOptions.set(optionName, choice); } } return filledOptions; } private async askOptionText(optionName: string, prompt: string): Promise<string | undefined> { return vscode.window.showInputBox({ prompt: `--${dasherize(optionName)}: ${prompt}`, ignoreFocusOut: true, }); } private async askOptionEnum(optionName: string, choices: string[], placeholder: string): Promise<string | undefined> { return vscode.window.showQuickPick(choices, { placeHolder: `--${dasherize(optionName)}: ${placeholder}`, ignoreFocusOut: true, }); } private async askOptionMultiselect(optionName: string, choices: string[], placeholder: string): Promise<string[] | undefined> { return vscode.window.showQuickPick(choices, { placeHolder: `--${dasherize(optionName)}: ${placeholder}`, canPickMany: true, ignoreFocusOut: true, }); } private async askConfirmation(): Promise<boolean> { const confirmationLabel = `$(check) Confirm`; const testLabel = `$(debug-alt) Test`; const confirmationChoices: vscode.QuickPickItem[] = [{ label: confirmationLabel, description: `Pro-tip: take a minute to check the command above is really what you want`, }, { label: testLabel, description: `Simulate the command with --dry-run`, }, { label: `$(close) Cancel`, }]; const choice = await vscode.window.showQuickPick(confirmationChoices, { placeHolder: this.cliCommand.getCommand(), ignoreFocusOut: true, }); if (choice?.label === testLabel) { this.cliCommand.launchCommand({ dryRun: true }); return this.askConfirmation(); } return (choice?.label === confirmationLabel) ? true : false; } /** * Automatically open the generated file */ private async jumpToFile(possibleUri?: vscode.Uri, counter = 0): Promise<void> { /* If we don't know the generated file path, we can't know if the command succeeded or not, * as we can't react on Terminal output */ if (!possibleUri) { throw new Error(); } /* If the file exists, open it */ else if (await FileSystem.isReadable(possibleUri, { silent: true })) { const document = await vscode.workspace.openTextDocument(possibleUri); await vscode.window.showTextDocument(document); /* Go back to previously active terminal */ Terminals.back(this.workspaceFolder); Output.logInfo(`Command has succeeded! Check the Terminal for more details.`); return; } /* Otherwise retry every half second, 10 times (so 5 seconds maximum) */ else if (counter < 10) { counter += 1; await new Promise<void>((resolve, reject) => { setTimeout(() => { this.jumpToFile(possibleUri, counter).then(() => { resolve(); }).catch(() => { reject(); }); }, 500); }); } /* After 10 failures */ else { throw new Error(); } } /** * Show an information message when we cannot detect the generated file */ private async showUnknownStatus(): Promise<void> { const refreshLabel = `Refresh Explorer`; Output.logInfo(`Command launched.`); const action = await vscode.window.showInformationMessage( `Command launched, check the Terminal to know its status. You may need to refresh the Explorer to see the generated file(s).`, `Refresh Explorer`, ); if (action === refreshLabel) { /* Refresh Explorer, otherwise you may not see the generated files */ vscode.commands.executeCommand('workbench.files.action.refreshFilesExplorer').then(() => {}, () => {}); } } private async showCollectionMissingErrorWithFix(collectionName: string): Promise<void> { const message = (collectionName === angularCollectionName) ? `"${collectionName}" should be present in a correctly installed Angular project.` : `Cannot load "${collectionName}" collection. It may not exist in "${this.workspaceFolder.name}" workspace folder.`; Output.logError(message); const fixLabel = `Try to npm install the missing schematics`; const fixAction = await vscode.window.showErrorMessage(message, fixLabel); if (fixAction === fixLabel) { Output.logInfo(`Trying to npm install ${collectionName}`); Terminals.send(this.workspaceFolder, `npm install ${collectionName} --save-dev`); const reloadLabel = `Reload window`; const reloadAction = await vscode.window.showInformationMessage(`Once the npm install is finished, the project must be reloaded.`, reloadLabel); if (reloadAction === reloadLabel) { vscode.commands.executeCommand('workbench.action.reloadWindow').then(() => {}, () => {}); } } } }
the_stack
import SObject from '../Core/SObject'; import Actor from '../Core/Actor'; import GameMode from '../Info/GameModeActor'; import LevelScriptActor from '../Info/LevelScriptActor'; import Engine from '../Core/Engine'; import World from '../Core/World'; import Level from '../Core/Level'; import EventManager from '../Event/EventManager'; import Hilo3d from '../Core/Hilo3d'; import {SClass} from '../Core/Decorator'; import ResourceManager from '../Resource/ResourceManager'; import { IGlobalDefaultLoaders, IGlobalHIDDefaultEvents, IGlobalDefaultEvents } from '../types/Global'; import GlTFLoader from '../Resource/GlTFLoader'; import ImageLoader from '../Resource/ImageLoader'; import TextureLoader from '../Resource/TextureLoader'; import AtlasLoader from '../Resource/AtlasLoader'; import {TGameModeConstructor, TLevelScriptConstructor, TConstructor, IDeviceInfo} from '../types/Common'; import { KeyDownTrigger, KeyPressTrigger, KeyUpTrigger } from '../HID/KeyboardTrigger'; import { TouchStartTrigger, TouchEndTrigger, TouchMoveTrigger, TouchCancelTrigger } from '../HID/TouchTrigger'; import { MouseClickTrigger, MouseDownTrigger, MouseEnterTrigger, MouseLeaveTrigger, MouseMoveTrigger, MouseOutTrigger, MouseOverTrigger, MouseUpTrigger, MouseWheelTrigger, ContextMenuTrigger, WheelTrigger } from '../HID/MouseTrigger'; import WindowResizeTrigger from '../HID/WindowResizeTrigger'; import BaseException from '../Exception/BaseException'; import throwException from '../Exception/throwException'; import BreakGuardException from '../Exception/BreakGuardException'; import MemberConflictException from '../Exception/MemberConflictException'; import UnmetRequireException from '../Exception/UnmetRequireException'; import SArray from '../DataStructure/SArray'; import Player from '../Player/Player'; import SMap from '../DataStructure/SMap'; import MissingMemberException from '../Exception/MissingMemberException'; import Ticker from '../Core/Ticker'; import SceneActor from '../Renderer/ISceneActor'; import InfoActor from '../Info/InfoActor'; import StateActor from '../Info/StateActor'; import PhysicSystemActor from '../Physic/PhysicSystemActor'; import CubeTextureLoader from '../Resource/CubeTextureLoader'; import Fog from '../Renderer/Fog'; import Debug from '../Debug'; /** * 游戏初始化配置。 */ export interface IGameOptions { /** * 游戏视图容器。 */ canvas: HTMLCanvasElement; /** * 游戏容器宽度,默认为容器宽度。 */ width?: number; /** * 游戏容器高度,默认为容器高度。 */ height?: number; /** * 游戏容器像素密度,默认自动计算。 */ pixelRatio?: number; /** * 背景清除色,默认为`rgb(0, 0, 0)`。 */ clearColor?: Hilo3d.Color; /** * 是否使用Framebuffer,默认不开启。 * * @default false */ useFramebuffer?: boolean; /** * framebuffer配置。 * * @default {} */ framebufferOption?: any; /** * 是否使用对数深度,默认不开启。 * * @default false */ useLogDepth?: boolean; /** * 是否开启透明背景,默认不开启。 * * @default false */ alpha?: boolean; /** * 是否开启`depth test`,默认开启。 * * @default true */ depth?: boolean; /** * 是否开启`stencil test`,默认不开启。 * * @default false */ stencil?: boolean; /** * 是否开启抗锯齿,默认开启。 * * @default true */ antialias?: boolean; /** * 是否使用instanced,默认不开启,仅在WebGL2.0有效。 * * @default false */ useInstanced?: boolean; /** * 是否使用VAO,默认开启。 * * @default true */ useVao?: boolean; /** * 是否开启预乘alpha,默认开启。 * * @default true */ premultipliedAlpha?: boolean; /** * 是否在每一帧buffer渲染前不清除并保护它们的数据,默认不开启。 * * @default false */ preserveDrawingBuffer?: boolean; /** * 当性能低下的时候,是否要创建context。 * * @default false */ failIfMajorPerformanceCaveat?: boolean; /** * 默认顶点着色器精度,针对原生的Basic和PBR等材质有效。 * * @default 'highp' */ vertexPrecision?: 'highp' | 'mediump' | 'lowp'; /** * 默认片段着色器精度,针对原生的Basic和PBR等材质有效。 * 在移动端,为了兼容性,建议为`'mediump'`。 * * @default 'highp' */ fragmentPrecision?: 'highp' | 'mediump' | 'lowp'; /** * 雾 */ fog?: Fog; /** * 指定解压压缩模型时分配给WASM的内存页,每页64kB,如果超出了则会降级到JS解压。 * * @default 256 */ amcMemPages?: number; /** * 是否开启游戏模式,UC专用。 */ gameMode?: boolean; } /** * 判断一个实例是否为`Game`。 */ export function isGame(value: SObject): value is Game { return (value as Game).isGame; } /** * 游戏类,整个Game逻辑中实际的顶层类,将作为一个单例存在于整个Game中,通常使用`getGame`获取。 * * @template IState Game的状态Actor类型,用于存储整个Game的全局状态。 * @noInheritDoc */ @SClass({className: 'Game', classType: 'Game'}) export default class Game< IState extends StateActor = StateActor > extends SObject { public isGame: boolean = true; /** * 当前的一些设备信息。 */ public deviceInfo: IDeviceInfo = { touchable: !!(window && ('ontouchstart' in window)) }; protected _engine: Engine = null; private _resource: ResourceManager<IGlobalDefaultLoaders> = null; protected _event: EventManager<IGlobalDefaultEvents> = null; protected _hid: EventManager<IGlobalHIDDefaultEvents> = null; protected _initState: IState; protected _state: IState; protected _worldsMeta: { [name: string]: { GameMode: TGameModeConstructor<GameMode>, levels: { [name: string]: { Script: TLevelScriptConstructor<LevelScriptActor> } } } } = {}; protected _defaultWorldName: string = null; protected _world: World = null; protected _actors: SArray<InfoActor> = new SArray(); protected _actorsForUpdate: SArray<Actor> = new SArray(); protected _actorsNeedUpdate: boolean = false; protected _actorsPriorities: number[] = []; protected _actorsPriorityCount: {[priority: number]: number} = {}; protected _players: SMap<Player> = new SMap(); protected _defaultPlayer: string = null; protected _paused: boolean = true; private _hiloStage: Hilo3d.Stage = null; /** * @param StateClass 游戏全局状态实例的类 * @param initState 游戏全局状态实例的初始值,若存在,将在初始化时从它clone */ constructor( name: string, options: IGameOptions, StateClass: TConstructor<IState> = StateActor as any, initState: IState = null ) { super(name); this._initState = initState; this._hiloStage = new Hilo3d.Stage(options); this._hiloStage.needCallChildUpdate = false; this._resource = new ResourceManager(this); this._event = new EventManager(this); this._hid = new EventManager(this); this._state = this.addActor('game-state', StateClass); this._state.copy(this._initState); this.canvas.style.width = ''; this.canvas.style.height = ''; this.initEvents(); this.initLoaders(options); this.initSystems(); try { this.onInit(); } catch (error) { throwException(error, this); } this._event.trigger('GameDidInit', {game: this}); } /** * Game状态Actor实例引用。 */ get state() { return this._state; } /** * Game全局事件管理器实例引用。 * 默认事件列表见[IGlobalDefaultEvents](../interfaces/iglobaldefaultevents`)。 */ get event() { return this._event; } /** * Game全局HID管理器全局实例引用。 * 这实际上是一个特化过的事件管理器,默认事件列表见[IGlobalHIDDefaultEvents](../interfaces/iglobalhiddefaultevents`)。 */ get hid() { return this._hid; } /** * 当前Game锁帧帧率。 */ get fps() { return this._engine.options.fps; } /** * 当前游戏是否处于暂停状态。 */ get paused() { return this._paused; } /** * Game的父级引擎实例引用。 */ get parent() { return this._engine; } /** * @hidden */ get game(): Game<IState> { return this; } /** * 当前`World`实例引用。一般不直接使用,而是用`actor.getWorld()`或`component.getWorld`,提供更好的泛型类型推断。 */ get world(): World { return this._world; } /** * 当前`Level`实例引用。一般不直接使用,而是用`actor.getLevel()`或`component.getLevel`,提供更好的泛型类型推断。 */ get level(): Level { return this._world.level; } /** * 当前的玩家列表,要结合玩家系统,详见[Player](./player)。 */ get players() { return this._players; } /** * 当前`Game`实例下的所有Actor列表,注意列表中的`Actor`必须为`InfoActor`,单纯负责逻辑而没有`transform`。 * 如果你需要实际上可视的Actor的列表,请参考`world.actors`。 */ get actors(): SArray<InfoActor> { return this._actors; } /** * Game的全局资源管理器实例引用,用于加载和管理所有的Game资源。 */ get resource() { return this._resource; } /** * Game的全局Ticker,来自`Engine`类,所有Game共用。 */ get ticker(): Ticker { return this._engine.ticker; } /** * 当前的`canvas`实例引用。 */ get canvas() { return this._hiloStage.canvas; } /** * 当前视口的实际像素宽度。 */ get screenWidth() { return this.canvas.offsetWidth; } /** * 当前视口的实际像素高度。 */ get screenHeight() { return this.canvas.offsetHeight; } /** * 当前视口的实际边界属性。 */ get bound() { return this.canvas.getBoundingClientRect(); } /** * 当前视口实际的纵横比。 */ get screenAspect() { const {offsetWidth, offsetHeight} = this.canvas; return offsetWidth / offsetHeight; } /** * 当前运行环境,一般为`development`或`production`。 */ get env() { return Debug.env; } /** * `env`不为`production`时,判定为开发环境。 */ get devMode() { return Debug.devMode; } /** * @hidden */ get renderer(): Hilo3d.WebGLRenderer { return this._hiloStage.renderer; } /** * @hidden */ get hiloStage(): Hilo3d.Stage { return this._hiloStage; } /** * @hidden */ public getGame(): Game<IState> { return this; } /** * 获取全局事件管理器引用。 */ public getEvent<IEvents extends IGlobalDefaultEvents = IGlobalDefaultEvents>(): EventManager<IEvents> { return this._event as EventManager<IEvents>; } /** * 获取全局HID管理器引用。 */ public getHID<IHIDs extends IGlobalHIDDefaultEvents = IGlobalHIDDefaultEvents>(): EventManager<IHIDs> { return this._hid as EventManager<IHIDs>; } /** * 获取全局资源管理器引用。 */ public getResource<IEntities extends IGlobalDefaultLoaders = IGlobalDefaultLoaders>(): ResourceManager<IEntities> { return this._resource as ResourceManager<IEntities>; } /** * 设定特定渲染配置。 */ public setOption<TKey extends keyof IGameOptions>(key: TKey, value: IGameOptions[TKey]) { this._hiloStage.renderer[key as string] = value; this._initState[key as string] = value; } /** * 获取特定渲染配置。 */ public getOption<TKey extends keyof IGameOptions>(key: TKey): IGameOptions[TKey] { return this._initState[key as string]; } /** * 生命周期,在Game初始化时被触发。 * 大部分Game生命周期都有其对应的全局方法,建议在`game.event`中去监听使用。 */ public onInit() { } /** * 生命周期,在Game被添加到引擎成功后被触发。 * 大部分Game生命周期都有其对应的全局方法,建议在`game.event`中去监听使用。 */ public onAdd() { } /** * 生命周期,在Game启动后被处罚。 * 大部分Game生命周期都有其对应的全局方法,建议在`game.event`中去监听使用。 */ public onStart() { } /** * 生命周期,在Game被暂停前触发。 * 大部分Game生命周期都有其对应的全局方法,建议在`game.event`中去监听使用。 */ public onPause() { } /** * 生命周期,在Game被唤醒后触发。 * 大部分Game生命周期都有其对应的全局方法,建议在`game.event`中去监听使用。 */ public onResume() { } /** * 生命周期,用于错误边界处理。将在Game中大部分可预知错误发生时被调用(通常是生命周期中的非异步错误)。 * 错误将会根据一定的路径向上传递,一直到`Engine`的层次,你可以在确保完美处理了问题后返回`true`来通知引擎不再向上传递。 * 当然你也可以将自定义的一些错误加入错误边界机制中,详见[Exception](../../guide/exception)。 */ public onError(error: BaseException, details?: any): boolean | void { } /** * 生命周期,在Game每一帧更新时被触发。 * 大部分Game生命周期都有其对应的全局方法,建议在`game.event`中去监听使用。 */ public onUpdate(delta: number) { } /** * 生命周期,在Game销毁时被触发。 * 大部分Game生命周期都有其对应的全局方法,建议在`game.event`中去监听使用。 */ public onDestroy() { } /** * 向Game类添加一个`World`。 * * @param GameMode 承载World逻辑的Actor,需继承自`GameModeActor`,此World所有的Level都将共有这一个GameMode。 * @param PersistentLevelScript World至少有一个默认的Level,在添加World时必须指定一个入口Level。 * @param isDefault 此World是否是游戏默认的World,在游戏开始前至少有一个默认的World。 */ public addWorld< TGameModeClass extends GameMode<any>, TPersistentLevelScriptClass extends LevelScriptActor<any>, >( name: string, GameMode: TGameModeConstructor<TGameModeClass>, PersistentLevelScript: TLevelScriptConstructor<TPersistentLevelScriptClass>, isDefault: boolean = false ) { this._worldsMeta[name] = { GameMode, levels: { persistent: { Script: PersistentLevelScript } } }; if (isDefault || Object.keys(this._worldsMeta).length < 2) { this._defaultWorldName = name; } return this; } /** * 从Game类中移除一个`World`。 * * 注意不能移除当前正在运作的World。 */ public removeWorld(name: string) { if (this._world.name.equalsTo(name)) { throw new BreakGuardException(this, `World ${name} is running could not be removed !`); } this._world.destroy(); delete this._worldsMeta[name]; return this; } /** * 切换当前正在运行的`World`。 * * @param initState 如果需要,指定初始化状态,将会被clone,传`null`则没有效果。 * @param needInheritActors 是否需要从上一个World继承Actors。 */ public async switchWorld( name: string, initState: StateActor = null, needInheritActors: boolean = false ) { if (!this._worldsMeta[name]) { throw new MissingMemberException(this, 'World', name, this); } let inheritActors: SArray<SceneActor>; const oldWorld = this._world; // todo: inherit actors from pre world if (oldWorld) { inheritActors = oldWorld.destroy(!needInheritActors); } const {GameMode, levels} = this._worldsMeta[name]; this._world = new World(name, GameMode, levels, this); await this._world.init(initState); if (inheritActors && needInheritActors) { await this._world.switchLevel('persistent', null, inheritActors); } else { await this.switchLevel('persistent'); } } /** * 向指定World添加一个`Level`。 * * @param Script 承载Level逻辑的Actor,需继承自`LevelScriptActor`。 */ public addLevel<TLevelScriptClass extends LevelScriptActor<any>>( worldName: string, levelName: string, Script: TLevelScriptConstructor<TLevelScriptClass> ) { if (!this._worldsMeta[worldName]) { throw new MissingMemberException(this, 'World', worldName, this); } if (this._worldsMeta[worldName].levels[levelName]) { throw new MemberConflictException(this, `Level of world ${worldName}`, levelName, this); } this._worldsMeta[worldName].levels[levelName] = {Script}; return this; } /** * 从指定World中移除一个`Level`。 */ public removeLevel(worldName: string, levelName: string) { if (!this._worldsMeta[worldName]) { return; } if (this._world.name.equalsTo(worldName) && this.level.name.equalsTo(levelName)) { throw new BreakGuardException(this, `Level ${worldName} in world ${this._world.name} is running could not be removed !`); } delete this._worldsMeta[worldName].levels[levelName]; return this; } /** * 切换当前World中运行的`Level`。 * 注意Level之间的actors是会默认进入继承逻辑的。 */ public switchLevel(name: string, initState: any = null) { return this._world.switchLevel(name, initState); } /** * 通过指定的InfoActor类`ActorClass`和初始化参数`initOptions`,向Game中添加一个actor。 * 注意继承自`SceneActor`或根组件为`SceneComponent`的Actor应当被添加到`World`中,而不是`Game`中。 */ public addActor<TActor extends InfoActor<any, any>>( name: string, ActorClass: TConstructor<TActor>, initOptions?: TActor['OPTIONS_TYPE'] ): TActor { const actor = new ActorClass(name, this, initOptions); if (this.devMode) { try { actor.verifyAdding(initOptions); } catch (error) { throwException(error, actor); return; } } actor.initialized(); const {updatePriority} = actor; const priorities = this._actorsPriorities; const priorityCount = this._actorsPriorityCount; let count = priorityCount[updatePriority]; if (updatePriority === InfoActor.UPDATE_PRIORITY.Others) { this._actors.add(actor); } else { const length = priorities.length; let index = 0; for (let i = 0; i < length; i += 1) { const p = priorities[i]; if (updatePriority < p) { break; } index += priorityCount[p]; } if (count === undefined) { count = 0; priorities.push(updatePriority); /** * @todo: change to insert sorting? */ priorities.sort(); } priorityCount[updatePriority] = count + 1; this._actors.insert(index, actor); } (actor as any)._parent = this; actor.added(); this._actorsNeedUpdate = true; return actor; } /** * 从Game中移除一个actor。 */ public removeActor(actor: InfoActor) { actor.destroy(); (actor as any)._parent = null; this._actors.remove(actor); const {updatePriority} = actor; const priorities = this._actorsPriorities; const priorityCount = this._actorsPriorityCount; let count = priorityCount[updatePriority]; if (updatePriority !== InfoActor.UPDATE_PRIORITY.Others) { count -= 1; } if (count === 0) { delete priorityCount[count]; priorities.splice(priorities.indexOf(updatePriority), 1); } this._actorsNeedUpdate = true; return this; } /** * 通过指定的玩家类`PlayerClass`,向Game中创建一个Player。 * 要结合玩家系统,详见[Player](./player)。 */ public createPlayer<TPlayer extends Player = Player>( name: string, PlayerClass?: TConstructor<TPlayer>, isDefault: boolean = false ): TPlayer { if (PlayerClass) { this._players.set(name, new PlayerClass(name, this)); } else { this._players.set(name, new Player(name, this)); } if (isDefault || this._players.empty) { this._defaultPlayer = name; } return this._players.get(name); } /** * 获取一个指定的Player实例引用。 */ public getPlayer(name?: string) { if (!name && this._defaultPlayer) { name = this._defaultPlayer; } return this._players.get(name); } /** * 移除一个指定的Player。 */ public removePlayer(name: string) { const player = this._players.remove(name); player.releaseController(); return this; } /** * 清空Player列表。 */ public clearPlayers() { this._players.forEach(player => { player.releaseController(); }); this._players.clear(); return this; } protected initLoaders(options: IGameOptions) { this._resource.register('GlTF', GlTFLoader); this._resource.register('Image', ImageLoader); this._resource.register('Texture', TextureLoader); this._resource.register('CubeTexture', CubeTextureLoader); this._resource.register('Atlas', AtlasLoader); if (options.amcMemPages) { (GlTFLoader.GET_EXTENSION_HANDLER('ALI_amc_mesh_compression') as any).memPages = options.amcMemPages; } } protected initEvents() { this._hid.register('MouseClick', MouseClickTrigger); this._hid.register('MouseDown', MouseDownTrigger); this._hid.register('MouseEnter', MouseEnterTrigger); this._hid.register('MouseLeave', MouseLeaveTrigger); this._hid.register('MouseMove', MouseMoveTrigger); this._hid.register('MouseOut', MouseOutTrigger); this._hid.register('MouseOver', MouseOverTrigger); this._hid.register('MouseUp', MouseUpTrigger); this._hid.register('MouseWheel', MouseWheelTrigger); this._hid.register('Wheel', WheelTrigger); this._hid.register('ContextMenu', ContextMenuTrigger); this._hid.register('KeyDown', KeyDownTrigger); this._hid.register('KeyUp', KeyUpTrigger); this._hid.register('KeyPress', KeyPressTrigger); this._hid.register('TouchStart', TouchStartTrigger); this._hid.register('TouchEnd', TouchEndTrigger); this._hid.register('TouchMove', TouchMoveTrigger); this._hid.register('TouchCancel', TouchCancelTrigger); this._event.register('Resize', WindowResizeTrigger); this._event.register('GameDidInit'); this._event.register('GameDidStart'); this._event.register('GameWillPause'); this._event.register('GameDidResume'); this._event.register('GameWillDestroy'); this._event.register('WorldDidInit'); this._event.register('WorldDidCreatePlayers'); this._event.register('WorldWillDestroy'); this._event.register('LevelDidInit'); this._event.register('LevelWillPreload'); this._event.register('LevelIsPreloading'); this._event.register('LevelDidPreload'); this._event.register('LevelDidCreateActors'); this._event.register('LevelWillDestroy'); this._event.register('WebglContextLost'); this._event.register('WebglContextRestored'); this._event.register('MainRendererWillStart'); this._event.register('MainRendererIsCleared'); this._event.register('MainRendererIsFinished'); (this._hiloStage.renderer as any).on('webglContextLost', () => this._event.trigger('WebglContextLost')); (this._hiloStage.renderer as any).on('webglContextRestored', () => this._event.trigger('WebglContextRestored')); (this._hiloStage.renderer as any).on('beforeRenderScene', () => this._event.trigger('MainRendererIsCleared')); this.event.add('Resize', () => this.resize()); } protected initSystems() { this.game.addActor('physicSystem', PhysicSystemActor); } /** * 重置画布容器尺寸。 */ public resize(bound?: {width: number, height: number}) { bound = bound || this.bound; const {width, height} = bound; const {pixelRatio, renderer} = this._hiloStage; (this._hiloStage as any).width = width; (this._hiloStage as any).height = height; renderer.resize(width * pixelRatio, height * pixelRatio, true); if (this.world) { setTimeout(() => this.world.resizeMainCamera(), 0); } return this; } /** * 启动这个游戏。 */ public async start() { if (!this._defaultWorldName) { throw new UnmetRequireException(this, 'A default world must be specified !'); } this.resize(); await this.switchWorld(this._defaultWorldName); // destroyed if (!this._engine) { return this; } this._engine.startGame(this); this._paused = false; this._event.trigger('GameDidStart', {game: this}); return this; } /** * 暂停这个游戏。 */ public pause() { if (this._paused) { return; } this._event.trigger('GameWillPause', {game: this}); this._engine.pauseGame(this); this._paused = true; return this; } /** * 唤醒这个游戏。 */ public resume() { if (!this._paused) { return; } this._engine.resumeGame(this); this._paused = false; this._event.trigger('GameDidResume', {game: this}); return this; } /** * 销毁这个游戏。 */ public destroy() { super.destroy(); this._paused = true; this._event.trigger('GameWillDestroy', {game: this}); this._engine.destroyGame(this); this._engine = null; this._hid.destroy(); this._event.destroy(); this._world.destroy(); this.removeActor(this._state); this._actors.forEach(actor => actor.destroy()); this._actors.clear(); this._hiloStage.destroy(); this._resource.destroy(); } /** * **不要自己调用!!** * * @hidden */ public update(delta: number) { this._hid.flushAll(); this._event.flushAll(); try { this.onUpdate(delta); } catch (error) { throwException(error, this); } if (this._actorsNeedUpdate) { this._actorsForUpdate.copy(this._actors); this._actorsNeedUpdate = false; } this._actorsForUpdate.forEach(actor => actor.update(delta)); this._players.forEach(player => player.update(delta)); if (this.world) { this.world.update(delta); } } }
the_stack
import { Line, Segment } from './line'; import { Matrix } from './matrix'; import { Sylvester, OutOfRangeError, InvalidOperationError } from './sylvester'; import { Vector } from './vector'; import { isPlaneLike, isLineLike, isSegmentLike, isVectorOrListLike, VectorOrList, Geometry, } from './likeness'; export class Plane { /** * Plane anchor point. */ public readonly anchor: Vector; /** * Plane normal from the anchor. */ public readonly normal: Vector; /** * Creates a plan from the anchor point and normal to the plane. If three * arguments are specified, the normal is calculated by assuming the three * points should lie in the same plane. If only two are sepcified, the second * is taken to be the normal. Normal vector is normalised before storage. */ constructor(anchor: VectorOrList, v1: VectorOrList, v2?: VectorOrList) { anchor = new Vector(anchor).to3D(); v1 = new Vector(v1).to3D(); v2 = v2 && new Vector(v2).to3D(); const A1 = anchor.elements[0]; const A2 = anchor.elements[1]; const A3 = anchor.elements[2]; const v11 = v1.elements[0]; const v12 = v1.elements[1]; const v13 = v1.elements[2]; let normal; let mod; if (!v2) { mod = Math.sqrt(v11 * v11 + v12 * v12 + v13 * v13); if (mod === 0) { throw new OutOfRangeError('Vectors provided to the plane must refer to unique points'); } normal = new Vector([v1.elements[0] / mod, v1.elements[1] / mod, v1.elements[2] / mod]); } else { const v21 = v2.elements[0]; const v22 = v2.elements[1]; const v23 = v2.elements[2]; normal = new Vector([ (v12 - A2) * (v23 - A3) - (v13 - A3) * (v22 - A2), (v13 - A3) * (v21 - A1) - (v11 - A1) * (v23 - A3), (v11 - A1) * (v22 - A2) - (v12 - A2) * (v21 - A1), ]); mod = normal.magnitude(); if (mod === 0) { throw new OutOfRangeError( 'Vectors provided to the plane must refer to unique, non-colinear points', ); } normal = new Vector([ normal.elements[0] / mod, normal.elements[1] / mod, normal.elements[2] / mod, ]); } this.anchor = anchor; this.normal = normal; } /** * Returns true iff the plane occupies the same space as the argument. * @param epsilon - precision used for comparing angles */ public eql(plane: unknown, epsilon = Sylvester.precision): boolean { return ( plane instanceof Plane && this.contains(plane.anchor) && this.isParallelTo(plane, epsilon) ); } /** * Returns the result of translating the plane by the given vector * @diagram Plane.translate */ public translate(vector: VectorOrList): Plane { const V = Vector.toElements(vector, 3); return new Plane( [ this.anchor.elements[0] + V[0], this.anchor.elements[1] + V[1], this.anchor.elements[2] + V[2], ], this.normal, ); } /** * Returns true iff the plane is parallel to the argument. Will return true * if the planes are equal, or if you give a line and it lies in the plane. * @param epsilon - precision used for comparing angles * @diagram Plane.isParallelTo */ public isParallelTo(obj: Geometry, epsilon = Sylvester.precision): boolean { if (isPlaneLike(obj)) { return this.normal.isParallelTo(obj.normal, epsilon); } else if (isLineLike(obj)) { return this.normal.isPerpendicularTo(obj.direction, epsilon); } else if (isSegmentLike(obj)) { return this.normal.isPerpendicularTo(obj.line.direction, epsilon); } else if (isVectorOrListLike(obj)) { return this.normal.isPerpendicularTo(obj, epsilon); } else { throw new InvalidOperationError(`Cannot check whether ${obj} is parallel to a plane`); } } /** * Returns true iff the receiver is perpendicular to the argument. * @param epsilon - precision used for comparing angles * @diagram Plane.isPerpendicularTo */ public isPerpendicularTo(obj: Geometry, epsilon = Sylvester.precision): boolean { if (isPlaneLike(obj)) { return this.normal.isPerpendicularTo(obj.normal, epsilon); } else if (isLineLike(obj)) { return this.normal.isParallelTo(obj.direction, epsilon); } else if (isSegmentLike(obj)) { return this.normal.isParallelTo(obj.line.direction, epsilon); } else if (isVectorOrListLike(obj)) { return this.normal.isParallelTo(obj, epsilon); } else { throw new InvalidOperationError(`Cannot check whether ${obj} is parallel to a plane`); } } /** * Returns the plane's distance from the given object (point, line or plane) * @diagram Plane.distanceFrom */ public distanceFrom(obj: Geometry): number { if (this.intersects(obj) || this.contains(obj)) { return 0; } if (isSegmentLike(obj)) { return Math.min(this.distanceFrom(obj.start), this.distanceFrom(obj.end)); } else if (isLineLike(obj) || isPlaneLike(obj)) { const A = this.anchor.elements; const B = obj.anchor.elements; const N = this.normal.elements; return Math.abs((A[0] - B[0]) * N[0] + (A[1] - B[1]) * N[1] + (A[2] - B[2]) * N[2]); } else if (isVectorOrListLike(obj)) { const P = Vector.toElements(obj, 3); const A = this.anchor.elements; const N = this.normal.elements; return Math.abs((A[0] - P[0]) * N[0] + (A[1] - P[1]) * N[1] + (A[2] - P[2]) * N[2]); } else { throw new InvalidOperationError(`Cannot get plane distance from {obj}`); } } /** * Returns true iff the plane contains the given point or line. * @param epsilon - precision used for comparing angles * @diagram Plane.contains */ public contains(obj: Geometry, epsilon = Sylvester.precision): boolean { if (isLineLike(obj)) { return ( this.contains(obj.anchor, epsilon) && this.contains(obj.anchor.add(obj.direction), epsilon) ); } else if (isSegmentLike(obj)) { return this.contains(obj.line, epsilon); } else if (isPlaneLike(obj)) { return this.eql(obj, epsilon); } else if (isVectorOrListLike(obj)) { const P = Vector.toElements(obj, 3); const A = this.anchor.elements; const N = this.normal.elements; const diff = Math.abs(N[0] * (A[0] - P[0]) + N[1] * (A[1] - P[1]) + N[2] * (A[2] - P[2])); return diff <= epsilon; } else { throw new InvalidOperationError(`Cannot check if a plane contains {obj}`); } } /** * Returns true iff the plane has a unique point/line of intersection with the argument. * @param epsilon - precision used for comparing angles * @diagram Plane.intersects */ public intersects(obj: Geometry, epsilon = Sylvester.precision): boolean { if (isVectorOrListLike(obj)) { return this.contains(obj, epsilon); } else if (isSegmentLike(obj)) { // for segments, we need to compute the intersection to ensure that it's // within the start and end bounds. return this.intersectionWith(obj) !== null; } else { return !this.isParallelTo(obj, epsilon); } } /** * Returns the unique intersection with the argument, if one exists. The result * will be a vector if a line is supplied, and a line if a plane is supplied. * @param epsilon - precision used for comparing angles * @diagram Plane.intersectionWith */ intersectionWith(obj: Line | Segment, epsilon?: number): Vector | null; intersectionWith(obj: Plane, epsilon?: number): Line | null; intersectionWith( obj: Plane | Line | Segment, epsilon = Sylvester.precision, ): Line | Vector | null { if (!isSegmentLike(obj) && !this.intersects(obj, epsilon)) { return null; } if (isLineLike(obj)) { const A = obj.anchor.elements; const D = obj.direction.elements; const P = this.anchor.elements; const N = this.normal.elements; const multiplier = (N[0] * (P[0] - A[0]) + N[1] * (P[1] - A[1]) + N[2] * (P[2] - A[2])) / (N[0] * D[0] + N[1] * D[1] + N[2] * D[2]); return new Vector([ A[0] + D[0] * multiplier, A[1] + D[1] * multiplier, A[2] + D[2] * multiplier, ]); } if (isSegmentLike(obj)) { const point = this.intersectionWith(obj.line); return point && obj.contains(point) ? point : null; } if (isPlaneLike(obj)) { const direction = this.normal.cross(obj.normal).toUnitVector(); // To find an anchor point, we find one co-ordinate that has a value // of zero somewhere on the intersection, and remember which one we picked const N = this.normal.elements; const A = this.anchor.elements; const O = obj.normal.elements; const B = obj.anchor.elements; let solver = Matrix.Zero(2, 2); let i = 0; while (solver.isSingular()) { i++; solver = new Matrix([ [N[i % 3], N[(i + 1) % 3]], [O[i % 3], O[(i + 1) % 3]], ]); } // Then we solve the simultaneous equations in the remaining dimensions const inverse = solver.inverse().elements; const x = N[0] * A[0] + N[1] * A[1] + N[2] * A[2]; const y = O[0] * B[0] + O[1] * B[1] + O[2] * B[2]; const intersection = [ inverse[0][0] * x + inverse[0][1] * y, inverse[1][0] * x + inverse[1][1] * y, ]; const anchor = []; for (let j = 1; j <= 3; j++) { // This formula picks the right element from intersection by // cycling depending on which element we set to zero above anchor.push(i === j ? 0 : intersection[(j + ((5 - i) % 3)) % 3]); } return new Line(anchor, direction); } throw new InvalidOperationError(`Cannot get a plane's intersection with ${obj}`); } /** * Returns the point in the plane closest to the given point. * @diagram Plane.pointClosestTo */ public pointClosestTo(point: Line | Segment, epsilon?: number): Vector | null; public pointClosestTo(point: VectorOrList, epsilon?: number): Vector; public pointClosestTo( point: Line | Segment | VectorOrList, epsilon = Sylvester.precision, ): Vector | null { if (isLineLike(point) || isSegmentLike(point)) { return this.intersectionWith(point, epsilon); } const P = Vector.toElements(point, 3); const A = this.anchor.elements; const N = this.normal.elements; const dot = (A[0] - P[0]) * N[0] + (A[1] - P[1]) * N[1] + (A[2] - P[2]) * N[2]; return new Vector([P[0] + N[0] * dot, P[1] + N[1] * dot, P[2] + N[2] * dot]); } /** * Returns a copy of the plane, rotated by t radians about the given line. * See notes on {@link Line.rotate}. * @param t - degrees in radians * @diagram Plane.rotate */ public rotate(t: number | Matrix, line: Line): Plane { const R = t instanceof Matrix ? t.elements : Matrix.Rotation(t, line.direction).elements; const C = line.pointClosestTo(this.anchor).elements; const A = this.anchor.elements; const N = this.normal.elements; const C1 = C[0]; const C2 = C[1]; const C3 = C[2]; const A1 = A[0]; const A2 = A[1]; const A3 = A[2]; const x = A1 - C1; const y = A2 - C2; const z = A3 - C3; return new Plane( [ C1 + R[0][0] * x + R[0][1] * y + R[0][2] * z, C2 + R[1][0] * x + R[1][1] * y + R[1][2] * z, C3 + R[2][0] * x + R[2][1] * y + R[2][2] * z, ], [ R[0][0] * N[0] + R[0][1] * N[1] + R[0][2] * N[2], R[1][0] * N[0] + R[1][1] * N[1] + R[1][2] * N[2], R[2][0] * N[0] + R[2][1] * N[1] + R[2][2] * N[2], ], ); } /** * Returns the reflection of the plane in the given point, line or plane. * @diagram Plane.reflectionIn */ public reflectionIn(obj: Geometry): Plane { if (isPlaneLike(obj)) { const A = this.anchor.elements; const N = this.normal.elements; const A1 = A[0]; const A2 = A[1]; const A3 = A[2]; const N1 = N[0]; const N2 = N[1]; const N3 = N[2]; const newA = this.anchor.reflectionIn(obj).elements; // Add the plane's normal to its anchor, then mirror that in the other plane const AN1 = A1 + N1; const AN2 = A2 + N2; const AN3 = A3 + N3; const Q = obj.pointClosestTo([AN1, AN2, AN3]).elements; const newN = [ Q[0] + (Q[0] - AN1) - newA[0], Q[1] + (Q[1] - AN2) - newA[1], Q[2] + (Q[2] - AN3) - newA[2], ]; return new Plane(newA, newN); } if (isLineLike(obj)) { return this.rotate(Math.PI, obj); } if (isSegmentLike(obj)) { return this.rotate(Math.PI, obj.line); } const P = Vector.toElements(obj, 3); return new Plane(this.anchor.reflectionIn([P[0], P[1], P[2]]), this.normal); } /** * Returns a textual representation of the object. */ public toString() { return `Plane<${this.anchor.toString()}, ${this.normal.toString()}>`; } /** * Returns the plane containing the given points (can be arrays as * well as vectors). If the points are not coplanar, returns null. * @diagram Plane.fromPoints */ public static fromPoints(...points: ReadonlyArray<VectorOrList>) { const np = points.length; const list: Vector[] = []; let i: number; let P: Vector; let n: number = 0; let N: Vector; let A: ReadonlyArray<number>; let B: ReadonlyArray<number>; let C: ReadonlyArray<number>; let theta: number; let prevN: Vector | undefined; let totalN = Vector.Zero(3); for (i = 0; i < np; i++) { P = new Vector(points[i]).to3D(); list.push(P); n = list.length; if (n > 2) { // Compute plane normal for the latest three points A = list[n - 1].elements; B = list[n - 2].elements; C = list[n - 3].elements; N = new Vector([ (A[1] - B[1]) * (C[2] - B[2]) - (A[2] - B[2]) * (C[1] - B[1]), (A[2] - B[2]) * (C[0] - B[0]) - (A[0] - B[0]) * (C[2] - B[2]), (A[0] - B[0]) * (C[1] - B[1]) - (A[1] - B[1]) * (C[0] - B[0]), ]).toUnitVector(); if (n > 3) { // If the latest normal is not (anti)parallel to the previous one, we've strayed off the plane. // This might be a slightly long-winded way of doing things, but we need the sum of all the normals // to find which way the plane normal should point so that the points form an anticlockwise list. theta = N.angleFrom(prevN!); if (!isNaN(theta)) { if ( !( Math.abs(theta) <= Sylvester.precision || Math.abs(theta - Math.PI) <= Sylvester.precision ) ) { throw new OutOfRangeError('The points provided to Plane.fromPoints are colinear'); } } } totalN = totalN.add(N); prevN = N; } } // We need to add in the normals at the start and end points, which the above misses out A = list[1].elements; B = list[0].elements; C = list[n - 1].elements; const D = list[n - 2].elements; totalN = totalN .add( new Vector([ (A[1] - B[1]) * (C[2] - B[2]) - (A[2] - B[2]) * (C[1] - B[1]), (A[2] - B[2]) * (C[0] - B[0]) - (A[0] - B[0]) * (C[2] - B[2]), (A[0] - B[0]) * (C[1] - B[1]) - (A[1] - B[1]) * (C[0] - B[0]), ]).toUnitVector(), ) .add( new Vector([ (B[1] - C[1]) * (D[2] - C[2]) - (B[2] - C[2]) * (D[1] - C[1]), (B[2] - C[2]) * (D[0] - C[0]) - (B[0] - C[0]) * (D[2] - C[2]), (B[0] - C[0]) * (D[1] - C[1]) - (B[1] - C[1]) * (D[0] - C[0]), ]).toUnitVector(), ); return new Plane(list[0], totalN); } /** * XY plane. */ public static readonly XY = new Plane(Vector.Zero(3), Vector.k); /** * YX plane. */ public static readonly YX = new Plane(Vector.Zero(3), Vector.k); /** * YZ plane. */ public static readonly YZ = new Plane(Vector.Zero(3), Vector.i); /** * ZY plane. */ public static readonly ZY = new Plane(Vector.Zero(3), Vector.i); /** * ZX plane. */ public static readonly ZX = new Plane(Vector.Zero(3), Vector.j); /** * XZ plane. */ public static readonly XZ = new Plane(Vector.Zero(3), Vector.j); }
the_stack
import { Colors } from '../constants/Colors'; import { CurveEditorFx } from './CurveEditorFx'; import { CurveEditorFxBg } from './CruveEditorFxBg'; import { CurveEditorGraph } from './CurveEditorGraph'; import { CurveEditorNode } from './CurveEditorNode'; import { ErrorBoundary } from './ErrorBoundary'; import { MouseComboBit, mouseCombo } from '../utils/mouseCombo'; import { RangeBar } from './RangeBar'; import { Resolution } from '../utils/Resolution'; import { TimeValueGrid } from './TimeValueGrid'; import { TimeValueLines } from './TimeValueLines'; import { TimeValueRange, dx2dt, snapTime, snapValue, x2t, y2v } from '../utils/TimeValueRange'; import { registerMouseEvent } from '../utils/registerMouseEvent'; import { showToasty } from '../states/Toasty'; import { useDispatch, useSelector } from '../states/store'; import { useDoubleClick } from '../utils/useDoubleClick'; import { useRect } from '../utils/useRect'; import React, { useCallback, useEffect, useRef } from 'react'; import styled from 'styled-components'; // == microcomponent =============================================================================== const Lines = ( { curveId, range, size }: { curveId: string; range: TimeValueRange; size: Resolution; } ): JSX.Element | null => { const { time, value } = useSelector( ( state ) => ( { time: state.automaton.curvesPreview[ curveId ]?.time, value: state.automaton.curvesPreview[ curveId ]?.value, } ) ); if ( time == null || value == null ) { return null; } return <TimeValueLines range={ range } size={ size } time={ time ?? undefined } value={ value ?? undefined } />; }; const Nodes = ( { curveId, range, size }: { curveId: string; range: TimeValueRange; size: Resolution; } ): JSX.Element | null => { const { nodes } = useSelector( ( state ) => ( { nodes: state.automaton.curves[ curveId ]?.nodes } ) ); if ( nodes == null ) { return null; } // 👾 See: https://github.com/yannickcr/eslint-plugin-react/issues/2584 // eslint-disable-next-line react/jsx-no-useless-fragment return <> { Object.values( nodes ).map( ( node ) => ( <CurveEditorNode key={ node.$id } curveId={ curveId } node={ node } range={ range } size={ size } /> ) ) } </>; }; const Fxs = ( { curveId, range, size }: { curveId: string; range: TimeValueRange; size: Resolution; } ): JSX.Element | null => { const { fxs } = useSelector( ( state ) => ( { fxs: state.automaton.curves[ curveId ]?.fxs } ) ); if ( fxs == null ) { return null; } return <> { Object.values( fxs ).map( ( fx ) => ( <CurveEditorFxBg key={ fx.$id } fx={ fx } range={ range } size={ size } /> ) ) } { Object.values( fxs ).map( ( fx ) => ( <CurveEditorFx key={ fx.$id } curveId={ curveId } fx={ fx } range={ range } size={ size } /> ) ) } </>; }; // == styles ======================================================================================= const SVGRoot = styled.svg` width: 100%; height: 100%; `; const Body = styled.div` position: absolute; left: 0; top: 0; width: 100%; height: calc( 100% - 4px ); background: ${ Colors.back1 }; pointer-events: auto; `; const StyledLines = styled( Lines )` position: absolute; `; const StyledRangeBar = styled( RangeBar )` position: absolute; left: 0; bottom: 0; height: 4px; `; const Root = styled.div` background: ${ Colors.black }; `; // == element ====================================================================================== export interface CurveEditorProps { className?: string; } const CurveEditor = ( { className }: CurveEditorProps ): JSX.Element => { const dispatch = useDispatch(); const checkDoubleClick = useDoubleClick(); const { selectedCurve, range, guiSettings, automaton, } = useSelector( ( state ) => ( { selectedCurve: state.curveEditor.selectedCurve, range: state.curveEditor.range, guiSettings: state.automaton.guiSettings, automaton: state.automaton.instance } ) ); const { curveLength, previewItemTime, previewItemSpeed, previewItemOffset, } = useSelector( ( state ) => ( { curveLength: state.automaton.curves[ selectedCurve ?? -1 ]?.length ?? null, previewItemTime: state.automaton.curvesPreview[ selectedCurve ?? -1 ]?.itemTime ?? null, previewItemSpeed: state.automaton.curvesPreview[ selectedCurve ?? -1 ]?.itemSpeed ?? null, previewItemOffset: state.automaton.curvesPreview[ selectedCurve ?? -1 ]?.itemOffset ?? null, } ) ); const curve = ( selectedCurve != null && automaton?.getCurveById( selectedCurve ) ) ?? null; const refBody = useRef<HTMLDivElement>( null ); const rect = useRect( refBody ); const move = useCallback( ( dx: number, dy: number ): void => { dispatch( { type: 'CurveEditor/MoveRange', size: rect, dx, dy } ); }, [ dispatch, rect ] ); const zoom = useCallback( ( cx: number, cy: number, dx: number, dy: number ): void => { dispatch( { type: 'CurveEditor/ZoomRange', size: rect, cx, cy, dx, dy } ); }, [ dispatch, rect ] ); const createNodeAndGrab = useCallback( ( x0: number, y0: number ): void => { if ( !curve ) { return; } let x = x0; let y = y0; const timePrev = x2t( x, range, rect.width ); const valuePrev = y2v( y, range, rect.height ); let time = timePrev; let value = valuePrev; const data = curve.createNode( time, value ); dispatch( { type: 'CurveEditor/SelectItems', nodes: [ data.$id ] } ); registerMouseEvent( ( event, movementSum ) => { x += movementSum.x; y += movementSum.y; const holdTime = event.ctrlKey || event.metaKey; const holdValue = event.shiftKey; const ignoreSnap = event.altKey; time = holdTime ? timePrev : x2t( x, range, rect.width ); value = holdValue ? valuePrev : y2v( y, range, rect.height ); if ( !ignoreSnap ) { if ( !holdTime ) { time = snapTime( time, range, rect.width, guiSettings ); } if ( !holdValue ) { value = snapValue( value, range, rect.height, guiSettings ); } } curve.moveNodeTime( data.$id, time ); curve.moveNodeValue( data.$id, value ); }, () => { if ( selectedCurve == null ) { return; } curve.moveNodeTime( data.$id, time ); curve.moveNodeValue( data.$id, value ); data.time = time; data.value = value; dispatch( { type: 'History/Push', description: 'Add Node', commands: [ { type: 'curve/createNodeFromData', curveId: selectedCurve, data } ] } ); } ); }, [ range, rect, curve, guiSettings, dispatch, selectedCurve ] ); const startSeek = useCallback( ( x: number ): void => { if ( !automaton || previewItemTime == null || previewItemSpeed == null || previewItemOffset == null ) { return; } const isPlaying = automaton.isPlaying; automaton.pause(); const t0 = x2t( x - rect.left, range, rect.width ); automaton.seek( previewItemTime + ( t0 - previewItemOffset ) / previewItemSpeed ); let dx = 0.0; let t = t0; registerMouseEvent( ( event, movementSum ) => { dx += movementSum.x; t = t0 + dx2dt( dx, range, rect.width ); automaton.seek( previewItemTime + ( t - previewItemOffset ) / previewItemSpeed ); }, () => { automaton.seek( previewItemTime + ( t - previewItemOffset ) / previewItemSpeed ); if ( isPlaying ) { automaton.play(); } } ); }, [ automaton, previewItemOffset, previewItemSpeed, previewItemTime, range, rect.left, rect.width, ] ); const handleMouseDown = useCallback( ( event ) => mouseCombo( event, { [ MouseComboBit.LMB ]: ( event ) => { if ( checkDoubleClick() ) { createNodeAndGrab( event.clientX - rect.left, event.clientY - rect.top ); } }, [ MouseComboBit.MMB ]: () => { registerMouseEvent( ( event, movementSum ) => move( movementSum.x, movementSum.y ) ); }, [ MouseComboBit.LMB + MouseComboBit.Alt ]: ( event ) => { startSeek( event.clientX ); }, } ), [ checkDoubleClick, createNodeAndGrab, startSeek, rect.left, rect.top, move ] ); const createNode = useCallback( ( x: number, y: number ) => { if ( !curve || selectedCurve == null ) { showToasty( { dispatch, kind: 'error', message: 'Add Node: No curve is selected! Select a curve before creating a node.' } ); return; } const t = x2t( x, range, rect.width ); const v = y2v( y, range, rect.height ); const data = curve.createNode( t, v ); dispatch( { type: 'CurveEditor/SelectItems', nodes: [ data.$id ] } ); dispatch( { type: 'History/Push', description: 'Add Node', commands: [ { type: 'curve/createNodeFromData', curveId: selectedCurve, data } ] } ); }, [ range, rect, curve, selectedCurve, dispatch ] ); const createFx = useCallback( ( x: number ) => { if ( !curve || selectedCurve == null ) { showToasty( { dispatch, kind: 'error', message: 'Add Fx: No curve is selected! Select a curve before creating a node.' } ); return; } dispatch( { type: 'FxSpawner/Open', callback: ( name: string ) => { const t = x2t( x, range, rect.width ); const data = curve.createFx( t, 1.0, name ); if ( data ) { dispatch( { type: 'CurveEditor/SelectItems', fxs: [ data.$id ] } ); dispatch( { type: 'History/Push', description: 'Add Fx', commands: [ { type: 'curve/createFxFromData', curveId: selectedCurve, data } ] } ); } } } ); }, [ range, rect, curve, selectedCurve, dispatch ] ); const handleContextMenu = useCallback( ( event: React.MouseEvent ): void => { event.preventDefault(); const x = event.clientX - rect.left; const y = event.clientY - rect.top; dispatch( { type: 'ContextMenu/Push', position: { x: event.clientX, y: event.clientY }, commands: [ { name: 'Add Node', description: 'Add a new bezier curve node.', callback: () => createNode( x, y ) }, { name: 'Add Fx', description: 'Add a new fx section.', callback: () => createFx( x ) } ] } ); }, [ rect, createNode, createFx, dispatch ] ); const handleWheel = useCallback( ( event: WheelEvent ): void => { event.preventDefault(); if ( event.shiftKey ) { zoom( event.offsetX, event.offsetY, event.deltaY, 0.0 ); } else if ( event.ctrlKey ) { zoom( event.offsetX, event.offsetY, 0.0, event.deltaY ); } else { move( -event.deltaX, -event.deltaY ); } }, [ zoom, move ] ); useEffect( // 🔥 fuck () => { const body = refBody.current; if ( !body ) { return; } body.addEventListener( 'wheel', handleWheel, { passive: false } ); return () => ( body.removeEventListener( 'wheel', handleWheel ) ); }, [ handleWheel ] ); return ( <Root className={ className }> <ErrorBoundary> <Body ref={ refBody }> <SVGRoot onMouseDown={ handleMouseDown } onContextMenu={ handleContextMenu } > <TimeValueGrid range={ range } size={ rect } /> { selectedCurve != null && <> <Fxs curveId={ selectedCurve } range={ range } size={ rect } /> <CurveEditorGraph curveId={ selectedCurve } range={ range } size={ rect } /> <Nodes curveId={ selectedCurve } range={ range } size={ rect } /> <StyledLines curveId={ selectedCurve } range={ range } size={ rect } /> </> } </SVGRoot> </Body> { curveLength != null && ( <StyledRangeBar range={ range } width={ rect.width } length={ curveLength } /> ) } </ErrorBoundary> </Root> ); }; export { CurveEditor };
the_stack
import { ADMIN } from '@/role' import { all, any, anyDisconnected, anyUpdated, connect, connectPhoneWithInvitation, connectWithInvitation, disconnect, disconnection, expectEveryoneToKnowEveryone, joinTestChannel, setup, TestChannel, updated, } from '@/util/testing' describe('connection', () => { describe('sync', () => { describe('two peers', () => { it('knows when users are up to date', async () => { const { alice, bob } = setup('alice', 'bob') // 👩🏾 👨🏻‍🦲 Alice and Bob connect await connect(alice, bob) }) it('updates remote user after connecting', async () => { const { alice, bob } = setup('alice', 'bob') // at this point, Alice and Bob have the same signature chain // 👩🏾 but now Alice does some stuff alice.team.addRole('managers') alice.team.addMemberRole('bob', 'managers') expect(alice.team.hasRole('managers')).toBe(true) expect(alice.team.memberHasRole('bob', 'managers')).toBe(true) // 👨🏻‍🦲 Bob hasn't connected, so he doesn't have Alice's changes expect(bob.team.hasRole('managers')).toBe(false) expect(bob.team.memberHasRole('bob', 'managers')).toBe(false) // 👩🏾 👨🏻‍🦲 Alice and Bob connect await connect(alice, bob) // ✅ 👨🏻‍🦲 Bob is up to date with Alice's changes expect(bob.team.hasRole('managers')).toBe(true) expect(bob.team.memberHasRole('bob', 'managers')).toBe(true) }) it('updates local user after connecting', async () => { const { alice, bob } = setup('alice', 'bob') // at this point, Alice and Bob have the same signature chain // 👨🏻‍🦲 but now Bob does some stuff bob.team.addRole('managers') bob.team.addMemberRole('bob', 'managers') // 👩🏾 👨🏻‍🦲 Alice and Bob connect await connect(alice, bob) // ✅ 👩🏾 Alice is up to date with Bob's changes expect(alice.team.hasRole('managers')).toBe(true) expect(alice.team.memberHasRole('bob', 'managers')).toBe(true) }) it('updates remote user while connected', async () => { const { alice, bob } = setup('alice', 'bob') // 👩🏾 👨🏻‍🦲 Alice and Bob connect await connect(alice, bob) // at this point, Alice and Bob have the same signature chain // 👨🏻‍🦲 now Alice does some stuff alice.team.addRole('managers') await anyUpdated(alice, bob) // ✅ 👩🏾 Bob is up to date with Alice's changes expect(bob.team.hasRole('managers')).toBe(true) }) it('updates local user while connected', async () => { const { alice, bob } = setup('alice', 'bob') // 👩🏾 👨🏻‍🦲 Alice and Bob connect await connect(alice, bob) // at this point, Alice and Bob have the same signature chain // 👨🏻‍🦲 now Bob does some stuff bob.team.addRole('managers') await anyUpdated(alice, bob) // ✅ 👩🏾 Alice is up to date with Bob's changes expect(alice.team.hasRole('managers')).toBe(true) }) it('resolves concurrent non-conflicting changes when updating', async () => { const { alice, bob } = setup('alice', 'bob') // 👩🏾 Alice creates a new role expect(alice.team.hasRole('MANAGERS')).toBe(false) alice.team.addRole('MANAGERS') expect(alice.team.hasRole('MANAGERS')).toBe(true) // 👨🏻‍🦲 concurrently, Bob invites Charlie const { id } = bob.team.inviteMember() expect(bob.team.hasInvitation(id)).toBe(true) // Bob doesn't see the new role expect(bob.team.hasRole('MANAGERS')).toBe(false) // Alice doesn't see Bob's invitation for Charlie expect(alice.team.hasInvitation(id)).toBe(false) // 👩🏾<->👨🏻‍🦲 Alice and Bob connect await connect(alice, bob) // ✅ now Bob does see the new role 👨🏻‍🦲💭 expect(bob.team.hasRole('MANAGERS')).toBe(true) // ✅ and Alice does see the invitation 👩🏾💭 expect(alice.team.hasInvitation(id)).toBe(true) }) it('resolves concurrent duplicate changes when updating', async () => { const { alice, bob } = setup('alice', 'bob') // 👩🏾 Alice creates a new role alice.team.addRole('MANAGERS') expect(alice.team.hasRole('MANAGERS')).toBe(true) // 👨🏻‍🦲 concurrently, Bob adds the same role bob.team.addRole('MANAGERS') expect(bob.team.hasRole('MANAGERS')).toBe(true) // 👩🏾<->👨🏻‍🦲 Alice and Bob connect await connect(alice, bob) // ✅ nothing blew up, and they both have the role expect(alice.team.hasRole('MANAGERS')).toBe(true) expect(bob.team.hasRole('MANAGERS')).toBe(true) }) }) describe('three or more peers', () => { it('sends updates across multiple hops', async () => { const { alice, bob, charlie } = setup('alice', 'bob', 'charlie') // 👩🏾 👨🏻‍🦲 Alice and Bob connect await connect(alice, bob) await connect(bob, charlie) // at this point, Alice and Bob have the same signature chain // 👨🏻‍🦲 now Alice does some stuff alice.team.addRole('managers') alice.team.addMemberRole('bob', 'managers') await Promise.all([ anyUpdated(alice, bob), // anyUpdated(bob, charlie), ]) // ✅ 👩🏾 Bob is up to date with Alice's changes expect(bob.team.hasRole('managers')).toBe(true) // ✅ Charlie sees the new role, even though he's not connected directly to Alice 👳🏽‍♂️💭 expect(charlie.team.hasRole('managers')).toBe(true) }) it('syncs up three ways - changes made after connecting', async () => { const { alice, bob, charlie } = setup('alice', 'bob', 'charlie') // 👩🏾<->👨🏻‍🦲<->👳🏽‍♂️ Alice, Bob, and Charlie all connect to each other await connect(alice, bob) await connect(bob, charlie) await connect(alice, charlie) // <-> while connected... // 👩🏾 Alice adds a new role alice.team.addRole('ALICES_FRIENDS') // 👨🏻‍🦲 Bob adds a new role bob.team.addRole('BOBS_FRIENDS') // 👳🏽‍♂️ Charlie adds a new role charlie.team.addRole('CHARLIES_FRIENDS') await Promise.all([ updated(alice, bob), // updated(bob, charlie), // updated(alice, charlie), ]) // ✅ All three get the three new roles expect(bob.team.hasRole('ALICES_FRIENDS')).toBe(true) expect(charlie.team.hasRole('ALICES_FRIENDS')).toBe(true) expect(alice.team.hasRole('CHARLIES_FRIENDS')).toBe(true) expect(bob.team.hasRole('CHARLIES_FRIENDS')).toBe(true) expect(alice.team.hasRole('BOBS_FRIENDS')).toBe(true) expect(charlie.team.hasRole('BOBS_FRIENDS')).toBe(true) }) it('syncs up three ways - changes made before connecting', async () => { const { alice, bob, charlie } = setup('alice', 'bob', 'charlie') // 🔌 while disconnected... // 👩🏾 Alice adds a new role alice.team.addRole('ALICES_FRIENDS') // 👨🏻‍🦲 Bob adds a new role bob.team.addRole('BOBS_FRIENDS') // 👳🏽‍♂️ Charlie adds a new role charlie.team.addRole('CHARLIES_FRIENDS') // 👩🏾<->👨🏻‍🦲<->👳🏽‍♂️ Alice, Bob, and Charlie all connect to each other await connect(alice, bob) await connect(bob, charlie) await connect(alice, charlie) // ✅ All three get the three new roles expect(bob.team.hasRole('ALICES_FRIENDS')).toBe(true) expect(charlie.team.hasRole('ALICES_FRIENDS')).toBe(true) expect(alice.team.hasRole('CHARLIES_FRIENDS')).toBe(true) expect(bob.team.hasRole('CHARLIES_FRIENDS')).toBe(true) expect(alice.team.hasRole('BOBS_FRIENDS')).toBe(true) expect(charlie.team.hasRole('BOBS_FRIENDS')).toBe(true) }) it('syncs up three ways - duplicate changes', async () => { const { alice, bob, charlie } = setup('alice', 'bob', 'charlie') // 🔌 while disconnected... // 👩🏾 Alice adds a new role alice.team.addRole('MANAGERS') // 👨🏻‍🦲 Bob adds the same role bob.team.addRole('MANAGERS') // 👳🏽‍♂️ Charlie adds the same role!! WHAT??!! charlie.team.addRole('MANAGERS') // 👩🏾<->👨🏻‍🦲<->👳🏽‍♂️ Alice, Bob, and Charlie all connect to each other await connect(alice, bob) await connect(bob, charlie) await connect(alice, charlie) // ✅ All three get the three new roles, and nothing bad happened expect(alice.team.hasRole('MANAGERS')).toBe(true) expect(bob.team.hasRole('MANAGERS')).toBe(true) expect(charlie.team.hasRole('MANAGERS')).toBe(true) }) }) describe('removals and demotions', () => { it('resolves concurrent duplicate removals', async () => { const { alice, bob } = setup('alice', 'bob', 'charlie') // 👳🏽‍♂️ Charlie is a member expect(alice.team.has('charlie')).toBe(true) expect(bob.team.has('charlie')).toBe(true) // 👨🏻‍🦲 Bob removes 👳🏽‍♂️ Charlie bob.team.remove('charlie') expect(alice.team.has('charlie')).toBe(true) expect(bob.team.has('charlie')).toBe(false) // 👩🏾 concurrently, Alice also removes 👳🏽‍♂️ Charlie alice.team.remove('charlie') expect(alice.team.has('charlie')).toBe(false) expect(bob.team.has('charlie')).toBe(false) // 👩🏾<->👨🏻‍🦲 Alice and Bob connect await connect(alice, bob) // ✅ nothing blew up, and Charlie has been removed on both sides 🚫👳🏽‍♂️ expect(alice.team.has('charlie')).toBe(false) expect(bob.team.has('charlie')).toBe(false) }) it('lets a member remove the founder', async () => { const { alice, bob } = setup('alice', 'bob') // 👩🏾<->👨🏻‍🦲 Alice and Bob connect await connect(alice, bob) // 👨🏻‍🦲 Bob removes Alice bob.team.remove('alice') // 👩🏾🔌👨🏻‍🦲 Alice is no longer a member, so they're disconnected await anyDisconnected(alice, bob) // ✅ Alice is no longer on the team 👩🏾👎 expect(bob.team.has('alice')).toBe(false) }) it('eventually updates disconnected members when someone uses an invitation to join', async () => { const { alice, bob, charlie } = setup('alice', 'bob', { user: 'charlie', member: false }) // 👩🏾📧👳🏽‍♂️ Alice invites Charlie const { seed } = alice.team.inviteMember() // 👳🏽‍♂️📧<->👩🏾 Charlie connects to Alice and uses his invitation to join await connectWithInvitation(alice, charlie, seed) // 👩🏾<->👨🏻‍🦲 Alice and Bob connect await connect(alice, bob) // ✅ expectEveryoneToKnowEveryone(alice, charlie, bob) }) it('updates connected members when someone uses an invitation to join', async () => { const { alice, bob, charlie } = setup('alice', 'bob', { user: 'charlie', member: false }) // 👩🏾<->👨🏻‍🦲 Alice and Bob connect await connect(alice, bob) // 👩🏾📧👳🏽‍♂️👴 Alice invites Charlie const { seed } = alice.team.inviteMember() await Promise.all([ // 👳🏽‍♂️📧<->👩🏾 Charlie connects to Alice and uses his invitation to join connectWithInvitation(alice, charlie, seed), // 👩🏾<->👨🏻‍🦲 Bob learns about Charlie from Alice anyUpdated(alice, bob), ]) // ✅ expectEveryoneToKnowEveryone(alice, charlie, bob) }) it('resolves concurrent duplicate invitations when updating', async () => { const { alice, bob, charlie, dwight } = setup([ 'alice', 'bob', { user: 'charlie', member: false }, { user: 'dwight', member: false }, ]) // 👩🏾📧👳🏽‍♂️👴 Alice invites Charlie and Dwight const aliceInvitesCharlie = alice.team.inviteMember() const aliceInvitesDwight = alice.team.inviteMember() // invitation unused, but that's OK // 👨🏻‍🦲📧👳🏽‍♂️👴 concurrently, Bob invites Charlie and Dwight const bobInvitesCharlie = bob.team.inviteMember() // invitation unused, but that's OK const bobInvitesDwight = bob.team.inviteMember() // 👳🏽‍♂️📧<->👩🏾 Charlie connects to Alice and uses his invitation to join await connectWithInvitation(alice, charlie, aliceInvitesCharlie.seed) // 👴📧<->👨🏻‍🦲 Dwight connects to Bob and uses his invitation to join await connectWithInvitation(bob, dwight, bobInvitesDwight.seed) // 👩🏾<->👨🏻‍🦲 Alice and Bob connect await connect(alice, bob) // ✅ No problemo expectEveryoneToKnowEveryone(alice, charlie, bob, dwight) }) it('resolves mutual demotions in favor of the senior member', async () => { const { alice, bob } = setup('alice', 'bob') await connect(alice, bob) // Both are admins expect(alice.team.memberIsAdmin('alice')).toBe(true) expect(bob.team.memberIsAdmin('alice')).toBe(true) expect(alice.team.memberIsAdmin('bob')).toBe(true) expect(bob.team.memberIsAdmin('bob')).toBe(true) // they both go offline await disconnect(alice, bob) // 👨🏻‍🦲 Bob removes 👩🏾 Alice from admin role bob.team.removeMemberRole('alice', ADMIN) // 👩🏾 Alice concurrently removes 👨🏻‍🦲 Bob from admin role alice.team.removeMemberRole('bob', ADMIN) // 👩🏾<->👨🏻‍🦲 Alice and Bob connect. Bob's demotion of Alice is discarded (because they were // done concurrently and Alice is senior so she wins) await connect(alice, bob) // ✅ Alice is still an admin 👩🏾👍 expect(alice.team.memberIsAdmin('alice')).toBe(true) expect(bob.team.memberIsAdmin('alice')).toBe(true) // ✅ Bob is no longer an admin 👨🏻‍🦲👎 expect(alice.team.memberIsAdmin('bob')).toBe(false) expect(bob.team.memberIsAdmin('bob')).toBe(false) // ✅ They are still connected 👩🏾<->👨🏻‍🦲 expect(alice.getState('bob')).toEqual('connected') expect(bob.getState('alice')).toEqual('connected') }) it('resolves mutual removals in favor of the senior member', async () => { const { alice, bob, charlie, dwight } = setup('alice', 'bob', 'charlie', 'dwight') // 👨🏻‍🦲 Bob removes 👩🏾 Alice bob.team.remove('alice') // 👩🏾 Alice concurrently removes 👨🏻‍🦲 Bob alice.team.remove('bob') // 👳🏽‍♂️<->👨🏻‍🦲 Charlie and Bob connect await connect(bob, charlie) // 👳🏽‍♂️💭 Charlie now knows that Bob has removed Alice expect(charlie.team.has('alice')).toBe(false) // 👴<->👩🏾 Dwight and Alice connect await connect(alice, dwight) // 👴💭 Dwight now knows that Alice has removed Bob expect(dwight.team.has('bob')).toBe(false) // 👴<->👳🏽‍♂️ Dwight and Charlie connect await connect(dwight, charlie) // 👴💭 👳🏽‍♂️💭 Both Dwight and Charlie now know about the mutual conflicting removals. // They each discard Bob's removal of Alice (because they were done concurrently and // Alice is senior so she wins) // ✅ Both kept Alice 👩🏾👍 expect(dwight.team.has('alice')).toBe(true) expect(charlie.team.has('alice')).toBe(true) // ✅ Both removed Bob 👨🏻‍🦲👎 expect(dwight.team.has('bob')).toBe(false) expect(charlie.team.has('bob')).toBe(false) }) it('gets both sides of the story in the case of mutual removals', async () => { const { alice, bob, charlie } = setup('alice', 'bob', 'charlie') // 👨🏻‍🦲 Bob removes 👩🏾 Alice bob.team.remove('alice') // 👩🏾 Alice concurrently removes 👨🏻‍🦲 Bob alice.team.remove('bob') // 👳🏽‍♂️<->👨🏻‍🦲 Charlie and Bob connect await connect(bob, charlie) // 👳🏽‍♂️💭 Charlie now knows that Bob has removed Alice expect(charlie.team.has('alice')).toBe(false) await disconnect(bob, charlie) // 👳🏽‍♂️<->👩🏾 Charlie and Alice connect // Even though Charlie now thinks Alice has been removed, he still syncs with her because // she might have more information, e.g. that Bob (who removed her) was concurrently removed await connect(charlie, alice) expect(charlie.team.has('alice')).toBe(true) expect(charlie.team.has('bob')).toBe(false) // ✅ Charlie is disconnected from Bob because Bob is no longer a member 👳🏽‍♂️🔌👨🏻‍🦲 await disconnection(bob, charlie) }) it(`when a member is demoted and makes concurrent admin-only changes, discards those changes`, async () => { const { alice, bob } = setup('alice', 'bob', { user: 'charlie', admin: false }) // 👩🏾 Alice removes 👨🏻‍🦲 Bob from admin role alice.team.removeMemberRole('bob', ADMIN) // 👨🏻‍🦲 concurrently, Bob makes 👳🏽‍♂️ Charlie an admin bob.team.addMemberRole('charlie', ADMIN) expect(bob.team.memberHasRole('charlie', ADMIN)).toBe(true) // 👩🏾<->👨🏻‍🦲 Alice and Bob connect await connect(alice, bob) // ✅ Bob's promotion of Charlie is discarded, because Bob concurrently lost admin privileges. 🚫👨🏻‍🦲👳🏽‍♂️ expect(alice.team.memberHasRole('charlie', ADMIN)).toBe(false) expect(bob.team.memberHasRole('charlie', ADMIN)).toBe(false) }) it(`when a member is demoted and concurrently adds a device, the new device is kept`, async () => { const { alice, bob } = setup('alice', 'bob') // 👩🏾 Alice removes 👨🏻‍🦲 Bob from admin role alice.team.removeMemberRole('bob', ADMIN) // 👨🏻‍🦲💻📧📱 concurrently, on his laptop, Bob invites his phone const { seed } = bob.team.inviteDevice() // 💻<->📱 Bob's phone and laptop connect and the phone joins await connectPhoneWithInvitation(bob, seed) // 👨🏻‍🦲👍📱 Bob's phone is added to his list of devices expect(bob.team.members('bob').devices).toHaveLength(2) // 👩🏾 Alice doesn't know about the new device expect(alice.team.members('alice').devices).toHaveLength(1) // 👩🏾<->👨🏻‍🦲 Alice and Bob connect await connect(alice, bob) // ✅ Bob's phone is still in his devices expect(bob.team.members('bob').devices).toHaveLength(2) // ✅ Alice knows about the new device expect(alice.team.members('bob').devices).toHaveLength(2) }) it('when an invitation is discarded, also discard related admittance actions', async () => { const { alice, bob, charlie } = setup('alice', 'bob', { user: 'charlie', member: false }) // 👩🏾 Alice removes 👨🏻‍🦲 Bob from admin role alice.team.removeMemberRole('bob', ADMIN) // 👨🏻‍🦲 concurrently, Bob invites 👳🏽‍♂️ Charlie and admits him to the team const { seed } = bob.team.inviteMember() await connectWithInvitation(bob, charlie, seed) expect(bob.team.has('charlie')).toBe(true) // 👩🏾<->👨🏻‍🦲 Alice and Bob connect await connect(alice, bob) // ✅ Bob's invitation is discarded, because Bob concurrently lost admin privileges expect(alice.team.has('charlie')).toBe(false) expect(bob.team.has('charlie')).toBe(false) }) it('resolves circular concurrent demotions ', async () => { const { alice, bob, charlie, dwight } = setup('alice', 'bob', 'charlie', 'dwight') // Bob demotes Charlie bob.team.removeMemberRole('charlie', ADMIN) // Charlie demotes Alice charlie.team.removeMemberRole('alice', ADMIN) // Alice demotes Bob alice.team.removeMemberRole('bob', ADMIN) // Dwight connects to all three await Promise.all([ connect(dwight, alice), // connect(dwight, bob), connect(dwight, charlie), ]) const isAdmin = dwight.team.memberIsAdmin // Bob is no longer an admin expect(isAdmin('bob')).toBe(false) // Alice is still an admin (because seniority) expect(isAdmin('alice')).toBe(true) // Charlie is still an admin (because Bob demoted him while being demoted) expect(isAdmin('charlie')).toBe(true) }) it('Alice promotes Bob then demotes him', async () => { const { alice, bob } = setup('alice', { user: 'bob', admin: false }) await connect(alice, bob) // 👨🏻‍🦲 Bob is not an admin expect(bob.team.memberIsAdmin('bob')).toBe(false) // 👩🏾 Alice promotes Bob alice.team.addMemberRole('bob', ADMIN) await anyUpdated(alice, bob) // 👨🏻‍🦲 Bob sees that he is admin expect(bob.team.memberIsAdmin('bob')).toBe(true) // 👩🏾 Alice demotes Bob alice.team.removeMemberRole('bob', ADMIN) await anyUpdated(alice, bob) // 👨🏻‍🦲 Bob sees that he is no longer admin expect(alice.team.memberIsAdmin('bob')).toBe(false) expect(bob.team.memberIsAdmin('bob')).toBe(false) }) it('rotates keys after a member is removed', async () => { const { alice, bob } = setup('alice', 'bob') await connect(alice, bob) // 👨🏻‍🦲 Bob has admin keys expect(() => bob.team.adminKeys()).not.toThrow() // We have the first-generation keys expect(alice.team.adminKeys().generation).toBe(0) expect(alice.team.teamKeys().generation).toBe(0) // <-> while connected... // 👩🏾 Alice removes Bob from the team alice.team.remove('bob') await anyDisconnected(alice, bob) // The admin keys and team keys have been rotated expect(alice.team.adminKeys().generation).toBe(1) expect(alice.team.teamKeys().generation).toBe(1) }) it('rotates keys after a member is demoted', async () => { const { alice, bob } = setup('alice', 'bob') await connect(alice, bob) // 👨🏻‍🦲 Bob has admin keys expect(() => bob.team.adminKeys()).not.toThrow() // We have the first-generation keys expect(alice.team.adminKeys().generation).toBe(0) // <-> while connected... // 👩🏾 Alice demotes Bob alice.team.removeMemberRole('bob', ADMIN) await anyUpdated(alice, bob) // 👨🏻‍🦲 Bob no longer has admin keys expect(() => bob.team.adminKeys()).toThrow() // The admin keys have been rotated expect(alice.team.adminKeys().generation).toBe(1) // The team keys haven't been rotated because Bob wasn't removed from the team expect(alice.team.teamKeys().generation).toBe(0) }) }) describe('post-compromise recovery', () => { it(`Eve steals Bob's phone; Bob heals the team`, async () => { const { alice, bob, charlie } = setup('alice', 'bob', 'charlie') await connect(alice, bob) await connect(bob, charlie) // Bob invites his phone and it joins const { seed } = bob.team.inviteDevice() await Promise.all([ connectPhoneWithInvitation(bob, seed), // anyUpdated(alice, bob), ]) // Bob and Alice know about Bob's phone expect(bob.team.members('bob').devices).toHaveLength(2) expect(alice.team.members('bob').devices).toHaveLength(2) // Eve steals Bob's phone. // From his laptop, Bob removes his phone from the team bob.team.removeDevice('bob', 'phone') expect(bob.team.members('bob').devices).toHaveLength(1) // Alice can see that Bob only has one device await anyUpdated(alice, bob) expect(alice.team.members('bob').devices).toHaveLength(1) await anyUpdated(bob, charlie) expect(charlie.team.members('bob').devices).toHaveLength(1) // Eve tries to connect to Charlie from Bob's phone, but she can't const phoneContext = { device: bob.phone, user: bob.user, team: bob.team, } const join = joinTestChannel(new TestChannel()) const eveOnBobsPhone = join(phoneContext).start() const heyCharlie = join(charlie.connectionContext).start() // GRRR foiled again await any([eveOnBobsPhone, heyCharlie], 'disconnected') }) it.todo(`Eve steals Bob's laptop; Alice heals the team`) //, async () => { // const { alice, bob, charlie } = setup('alice', 'bob', 'charlie') // await connect(alice, bob) // await connect(alice, charlie) // expect(alice.team.adminKeys().generation).toBe(0) // expect(alice.team.teamKeys().generation).toBe(0) // // Eve steals Bob's laptop, so Alice removes Bob's laptop from the team // alice.team.removeDevice('bob', 'laptop') // // Alice can see that Bob has no devices // expect(alice.team.members('bob').devices).toHaveLength(0) // await updated(alice, charlie) // // The keys have been rotated // expect(charlie.team.adminKeys().generation).toBe(1) // expect(charlie.team.teamKeys().generation).toBe(1) // // Eve tries to connect to Charlie from Bob's laptop, but she can't // connect(bob, charlie) // // GRRR foiled again // await disconnection(bob, charlie) // const { seed } = alice.team.inviteDevice() // const phoneContext = { // userName: bob.userName, // device: bob.phone, // invitationSeed: seed, // } as InviteeDeviceInitialContext // const join = joinTestChannel(new TestChannel()) // const aliceBobPhone = await join(alice.connectionContext).start() // const bobPhone = await join(phoneContext).start() // await all([aliceBobPhone, bobPhone], 'connected') // // TODO: This will require a distinct workflow. Alice can't admit Bob's device because she's not Bob. // // When a user admits their own device, they create a lockbox for the device so that it has the user keys. // // In this case, Bob's old user keys are gone forever, so the device needs to be able to generate new ones. // }) }) }) })
the_stack
import * as path from "path"; import { promises } from "fs"; import * as _ from "lodash"; import * as inquirer from "inquirer"; import { ReplayUtils, ReplayState } from "./replayUtils"; const datauri = require("datauri"); // eslint-disable-line @typescript-eslint/no-var-requires const titleize = require("titleize"); // eslint-disable-line @typescript-eslint/no-var-requires const humanizeString = require("humanize-string"); // eslint-disable-line @typescript-eslint/no-var-requires import * as defaultImage from "./images/defaultImage"; import { YouiAdapter } from "./youi-adapter"; import { YouiEvents } from "./youi-events"; import { IRpc } from "@sap-devx/webview-rpc/out.ext/rpc-common"; import { GeneratorFilter, GeneratorType } from "./filter"; import { IChildLogger } from "@vscode-logging/logger"; import { IPrompt, MessageType } from "@sap-devx/yeoman-ui-types"; import { SWA } from "./swa-tracker/swa-tracker-wrapper"; import { Output } from "./output"; import { resolve } from "path"; import { Env, EnvGen, GeneratorData, GeneratorNotFoundError } from "./utils/env"; import { vscode, getVscode } from "./utils/vscodeProxy"; import * as Generator from "yeoman-generator"; import * as Environment from "yeoman-environment"; import { Questions } from "yeoman-environment/lib/adapter"; import { State } from "./utils/promise"; import { Constants } from "./utils/constants"; import { isEmpty } from "lodash"; export interface IQuestionsPrompt extends IPrompt { questions: any[]; } export class YeomanUI { private static readonly defaultMessage = "Some quick example text of the generator description. This is a long text so that the example will look good."; private static readonly YEOMAN_PNG = "yeoman.png"; private static funcReplacer(key: any, value: any) { return _.isFunction(value) ? "__Function" : value; } private uiOptions: any; // eslint-disable-line @typescript-eslint/prefer-readonly private cwd: string; private readonly rpc: IRpc; private readonly youiEvents: YouiEvents; private readonly output: Output; private readonly logger: IChildLogger; private readonly youiAdapter: YouiAdapter; private gen: Generator | undefined; private promptCount: number; private currentQuestions: Questions<any>; private generatorName: string; private readonly replayUtils: ReplayUtils; // eslint-disable-next-line @typescript-eslint/ban-types private readonly customQuestionEventHandlers: Map<string, Map<string, Function>>; private errorThrown = false; private readonly initialCwd: string; private readonly typesMap: Map<string, string>; private readonly generatorsToIgnoreArray: string[]; private readonly flowState: State<void>; private readonly TARGET_FOLDER_CONFIG_PROP = "ApplicationWizard.TargetFolder"; private readonly SELECTED_WORKSPACE_CONFIG_PROP = "ApplicationWizard.Workspace"; constructor( rpc: IRpc, youiEvents: YouiEvents, output: Output, logger: IChildLogger, uiOptions: any, flowState: State<void> ) { this.rpc = rpc; this.flowState = flowState; this.generatorName = ""; this.replayUtils = new ReplayUtils(); this.youiEvents = youiEvents; this.logger = logger; this.output = output; this.rpc.registerMethod({ func: this.receiveIsWebviewReady, thisArg: this, }); this.rpc.registerMethod({ func: this.runGenerator, thisArg: this }); this.rpc.registerMethod({ func: this.evaluateMethod, thisArg: this }); this.rpc.registerMethod({ func: this.toggleOutput, thisArg: this }); this.rpc.registerMethod({ func: this.exploreGenerators, thisArg: this }); this.rpc.registerMethod({ func: this.logError, thisArg: this }); this.rpc.registerMethod({ func: this.back, thisArg: this }); this.rpc.registerMethod({ func: this.executeCommand, thisArg: this }); this.rpc.registerMethod({ func: this.getState, thisArg: this }); this.initialCwd = process.cwd(); this.uiOptions = uiOptions; this.youiAdapter = new YouiAdapter(youiEvents, output); this.youiAdapter.setYeomanUI(this); this.promptCount = 0; this.currentQuestions = {}; this.customQuestionEventHandlers = new Map(); this.typesMap = new Map(); this.generatorsToIgnoreArray = []; } private getState() { return this.uiOptions; } public async _notifyGeneratorsChange(): Promise<void> { const generators: IQuestionsPrompt = await this.getGeneratorsPrompt(); return this.rpc.invoke("updateGeneratorsPrompt", [generators.questions]); } public async _notifyGeneratorsInstall(args: any[], force: boolean) { if (!_.isNil(args)) { const isGeneratorsPrompt: boolean = await this.rpc.invoke("isGeneratorsPrompt"); if (isGeneratorsPrompt || force) { this.showGeneratorsInstallingMessage(args); } } this.uiOptions.installGens = _.isObject(args) && _.isEmpty(args) ? undefined : args; } private showGeneratorsInstallingMessage(args: any[]) { if (_.isEmpty(args)) { this.youiEvents .getAppWizard() .showInformation(this.uiOptions.messages.all_generators_have_been_installed, MessageType.prompt); } else { this.youiEvents .getAppWizard() .showWarning(this.uiOptions.messages.generators_are_being_installed, MessageType.prompt); } } // eslint-disable-next-line @typescript-eslint/ban-types public registerCustomQuestionEventHandler(questionType: string, methodName: string, handler: Function): void { // eslint-disable-next-line @typescript-eslint/ban-types let entry: Map<string, Function> = this.customQuestionEventHandlers.get(questionType); if (entry === undefined) { this.customQuestionEventHandlers.set(questionType, new Map()); entry = this.customQuestionEventHandlers.get(questionType); } entry.set(methodName, handler); } public showProgress(message?: string) { this.youiEvents.showProgress(message); } private logError(error: any, prefixMessage?: string) { const errorObj: any = this.getErrorInfo(error); if (prefixMessage) { errorObj.message = `${prefixMessage} - ${errorObj.message}`; } this.logger.error(errorObj.message, { stack: errorObj.stack }); return JSON.stringify(errorObj); } private async getGeneratorsPrompt(): Promise<any> { const gensData: GeneratorData[] = await Env.getGeneratorsData(); const questions: any[] = await this.createGeneratorPromptQuestions(gensData, this.uiOptions.filter); this.currentQuestions = questions; const normalizedQuestions = this.normalizeFunctions(questions); return { name: "Select Generator", questions: normalizedQuestions }; } private async getChildDirectories(folderPath: string) { const childDirs: string[] = []; const result = { targetFolderPath: folderPath, childDirs }; try { for (const file of await promises.readdir(folderPath)) { const resourcePath: string = path.join(folderPath, file); if ((await promises.stat(resourcePath)).isDirectory()) { result.childDirs.push(resourcePath); } } } catch (error) { result.childDirs = []; } return result; } private wsGet(key: string): string { return _.trim(vscode.workspace.getConfiguration().get(key)); } private async runGenerator(generatorNamespace: string) { this.generatorName = generatorNamespace; // TODO: should create and set target dir only after user has selected a generator; // see issue: https://github.com/yeoman/environment/issues/55 // process.chdir() doesn't work after environment has been created try { const targetFolder = this.getCwd(); await promises.mkdir(targetFolder, { recursive: true }); const dirsBefore = await this.getChildDirectories(targetFolder); const options = { logger: this.logger.getChildLogger({ label: generatorNamespace }), vscode: getVscode(), // TODO: remove this temporary workaround once a better solution is found, data: this.uiOptions.data, swaTracker: SWA.getSWATracker(), appWizard: this.youiEvents.getAppWizard(), }; const envGen: EnvGen = await Env.createEnvAndGen(generatorNamespace, options, this.youiAdapter); // check if generator defined a helper function called setPromptsCallback() const setPromptsCallback = _.get(envGen.gen, "setPromptsCallback"); if (setPromptsCallback) { setPromptsCallback(this.setPromptList.bind(this)); } this.promptCount = 0; this.gen = envGen.gen as Generator; // do not add second parameter with value true // some generators rely on fact that this.env.cwd and // the current working directory is changed. this.gen.destinationRoot(targetFolder); // notifies ui wether generator is in writing state this.setGenInWriting(this.gen); // handles generator install step if exists this.onGenInstall(this.gen); // handles generator errors this.handleErrors(envGen.env, this.gen, generatorNamespace); await envGen.env.runGenerator(envGen.gen); if (!this.errorThrown) { // Without resolve this code worked only for absolute paths without / at the end. // Generator can put a relative path, path including . and .. and / at the end. const dirsAfter = await this.getChildDirectories(resolve(this.getCwd(), this.gen.destinationRoot())); this.onGeneratorSuccess(generatorNamespace, dirsBefore, dirsAfter); } } catch (error) { if (error instanceof GeneratorNotFoundError) { vscode.window.showErrorMessage(error.message); } this.onGeneratorFailure(generatorNamespace, this.getErrorWithAdditionalInfo(error, "runGenerator()")); } } private setInitialProcessDir() { process.chdir(this.initialCwd); } private setGenInWriting(gen: any) { const genMethodName = "writing"; const originalPrototype = Object.getPrototypeOf(gen); const originalGenWriting = _.get(originalPrototype, genMethodName); if (!originalGenWriting) { originalPrototype[genMethodName] = () => ""; } const uiRpcMethodName = "setGenInWriting"; void this.rpc.invoke(uiRpcMethodName, [false]); gen.on(`method:${genMethodName}`, () => this.rpc.invoke(uiRpcMethodName, [true])); } private handleErrors(env: Environment, gen: any, generatorName: string) { const errorEventName = "error"; env.on(errorEventName, (error) => { env.removeAllListeners(errorEventName); this.onGeneratorFailure(generatorName, this.getErrorWithAdditionalInfo(error, `env.on(${errorEventName})`)); env.emit(errorEventName, error); }); gen.on(errorEventName, (error: any) => this.onGeneratorFailure(generatorName, this.getErrorWithAdditionalInfo(error, `gen.on(${errorEventName})`)) ); process.on("uncaughtException", (error) => this.onGeneratorFailure(generatorName, this.getErrorWithAdditionalInfo(error, "process.on(uncaughtException)")) ); } private getErrorWithAdditionalInfo(error: any, additionalInfo: string) { _.set(error, "message", `${additionalInfo} ${_.get(error, "message", "")}`); return error; } /** * * @param answers - partial answers for the current prompt -- the input parameter to the method to be evaluated * @param method */ private async evaluateMethod(params: any[], questionName: string, methodName: string): Promise<any> { try { if (this.currentQuestions) { const relevantQuestion: any = _.find(this.currentQuestions, (question) => { return _.get(question, "name") === questionName; }); if (relevantQuestion) { const guiType = _.get(relevantQuestion, "guiOptions.type", relevantQuestion.guiType); // eslint-disable-next-line @typescript-eslint/ban-types const customQuestionEventHandler: Function = this.getCustomQuestionEventHandler(guiType, methodName); return _.isUndefined(customQuestionEventHandler) ? await relevantQuestion[methodName].apply(this.gen, params) : await customQuestionEventHandler.apply(this.gen, params); } } } catch (error) { const questionInfo = `Could not update method '${methodName}' in '${questionName}' question in generator '${this.gen.options.namespace}'`; const errorMessage = this.logError(this.getErrorWithAdditionalInfo(error, "evaluateMethod()"), questionInfo); this.onGeneratorFailure(this.generatorName, errorMessage); } } private async receiveIsWebviewReady() { try { let generatorId: string = this.uiOptions.generator; if (!generatorId) { const generators: IQuestionsPrompt = await this.getGeneratorsPrompt(); await this._notifyGeneratorsInstall(this.uiOptions.installGens, true); const response: any = await this.rpc.invoke("showPrompt", [generators.questions, "select_generator"]); generatorId = response.generator; } this.replayUtils.clear(); SWA.updateGeneratorStarted(generatorId, this.logger); await this.runGenerator(generatorId); } catch (error) { this.logError(error, "receiveIsWebviewReady"); } } private toggleOutput() { this.output.show(); } private exploreGenerators() { SWA.updateExploreAndInstallGeneratorsLinkClicked(this.logger); return vscode.commands.executeCommand("exploreGenerators"); } private getCwd(): string { const targetFolderConfig = this.wsGet(this.TARGET_FOLDER_CONFIG_PROP); if (!isEmpty(targetFolderConfig)) { return targetFolderConfig; } return Constants.IS_IN_BAS ? Constants.HOMEDIR_PROJECTS : _.get(vscode, "workspace.workspaceFolders[0].uri.fsPath", Constants.HOMEDIR_PROJECTS); } public async showPrompt(questions: Questions<any>): Promise<inquirer.Answers> { this.promptCount++; const promptName = this.getPromptName(questions); if (this.replayUtils.getReplayState() === ReplayState.Replaying) { return this.replayUtils.next(this.promptCount, promptName); } else if (this.replayUtils.getReplayState() === ReplayState.EndingReplay) { const prompts: IPrompt[] = this.replayUtils.stop(questions); void this.setPromptList(prompts); } this.replayUtils.recall(questions); this.currentQuestions = questions; const mappedQuestions: Questions<any> = this.normalizeFunctions(questions); if (_.isEmpty(mappedQuestions)) { return {}; } const answers = await this.rpc.invoke("showPrompt", [mappedQuestions, promptName]); this.replayUtils.remember(questions, answers); return answers; } private async back(partialAnswers: Environment.Answers, numOfSteps: number): Promise<void> { SWA.updateOneOfPreviousStepsClicked(this.generatorName, this.logger); this.replayUtils.start(this.currentQuestions, partialAnswers, numOfSteps); return this.runGenerator(this.generatorName); } private executeCommand(id: string, ...args: any[]): void { void this.youiEvents.executeCommand(id, args); } // eslint-disable-next-line @typescript-eslint/ban-types private getCustomQuestionEventHandler(questionType: string, methodName: string): Function { // eslint-disable-next-line @typescript-eslint/ban-types const entry: Map<string, Function> = this.customQuestionEventHandlers.get(questionType); if (entry !== undefined) { return entry.get(methodName); } } private getPromptName(questions: Questions<any>): string { const firstQuestionName = _.get(questions, "[0].name"); return firstQuestionName ? _.startCase(firstQuestionName) : `Step ${this.promptCount}`; } private onGeneratorSuccess(generatorName: string, resourcesBeforeGen?: any, resourcesAfterGen?: any) { let targetFolderPath: string = null; // All the paths here absolute normilized paths. const targetFolderPathBeforeGen: string = _.get(resourcesBeforeGen, "targetFolderPath"); const targetFolderPathAfterGen: string = _.get(resourcesAfterGen, "targetFolderPath"); if (targetFolderPathBeforeGen === targetFolderPathAfterGen) { const newDirs: string[] = _.difference( _.get(resourcesAfterGen, "childDirs"), _.get(resourcesBeforeGen, "childDirs") ); if (_.size(newDirs) === 1) { // One folder added by generator and targetFolderPath/destinationRoot was not changed by generator. // ---> Fiori project generator flow. targetFolderPath = newDirs[0]; } //else { //_.size(newDirs) = 0 (0 folders) or _.size(newDirs) > 1 (5 folders) // We don't know what is the correct targetFolderPath ---> no buttons should be shown. // No folder added by generator ---> Fiori module generator flow. // Many folders added by generator ---> // } } else { //(targetFolderPathBeforeGen !== targetFolderPathAfterGen) // Generator changed targetFolderPath/destinationRoot. // ---> FoodQ generator flow. targetFolderPath = targetFolderPathAfterGen; } const type: string = this.typesMap.has(generatorName) ? this.typesMap.get(generatorName) : "files"; // For now - A Fiori project is supposed to create the project and not open it const ignoreGen: boolean = this.generatorsToIgnoreArray.includes(generatorName); const selectedWorkspace: string = type === "files" || type === "module" || ignoreGen ? this.uiOptions.messages.create_and_close : this.wsGet(this.SELECTED_WORKSPACE_CONFIG_PROP); const message = this.uiOptions.messages.artifact_with_name_generated(generatorName); const generatedTemplatePath = targetFolderPath ? targetFolderPath : targetFolderPathBeforeGen; this.logger.debug(`done running yeomanui! ${message} You can find it at ${generatedTemplatePath}`); SWA.updateGeneratorEnded(generatorName, true, this.logger); this.youiEvents.doGeneratorDone(true, message, selectedWorkspace, type, targetFolderPath); this.setInitialProcessDir(); this.flowState.resolve(); } private onGeneratorFailure(generatorName: string, error: any) { this.errorThrown = true; const messagePrefix = `${generatorName} generator failed`; const errorMessage: string = this.logError(error, messagePrefix); SWA.updateGeneratorEnded(generatorName, false, this.logger, errorMessage); this.youiEvents.doGeneratorDone(false, errorMessage, "", "files"); this.setInitialProcessDir(); this.flowState.reject(error); } private onGenInstall(gen: any) { gen.on("method:install", () => { this.youiEvents.doGeneratorInstall(); }); } private getErrorInfo(error: any = "") { if (_.isString(error)) { return { message: error }; } const res = { message: _.get(error, "message", ""), stack: _.get(error, "stack", ""), }; return res; } private async createGeneratorPromptQuestions(gensData: GeneratorData[], genFilter: GeneratorFilter): Promise<any[]> { const generatorChoicePromises = _.map(gensData, (genData) => { return this.getGeneratorChoice(genData, genFilter); }); const questions: any[] = []; if (_.includes(genFilter.types, GeneratorType.project)) { const targetFolderQuestion: any = { type: "input", guiOptions: { type: "label", hint: this.uiOptions.messages.select_target_folder_question_hint, link: { text: "Preferences", command: { id: "workbench.action.openSettings", params: [`ApplicationWizard.TargetFolder`], }, }, }, name: "generator.target.folder", message: "Specify a target folder path", default: this.getCwd(), }; questions.push(targetFolderQuestion); const locationQuestion: any = { type: "label", guiOptions: { hint: this.uiOptions.messages.select_open_workspace_question_hint, link: { text: "Preferences", command: { id: "workbench.action.openSettings", params: [`ApplicationWizard.Workspace`], }, }, }, name: "selectedWorkspace", message: this.uiOptions.messages.select_open_workspace_question_hint, default: this.wsGet(this.SELECTED_WORKSPACE_CONFIG_PROP), }; questions.push(locationQuestion); } const generatorChoices = await Promise.all(generatorChoicePromises); const generatorQuestion: any = { type: "list", guiType: "tiles", guiOptions: { hint: this.uiOptions.messages.select_generator_question_hint, }, name: "generator", message: this.uiOptions.messages.select_generator_question_message, choices: _.compact(generatorChoices), }; questions.push(generatorQuestion); return questions; } private async getGeneratorChoice(genData: GeneratorData, filter: GeneratorFilter) { const packageJson = genData.generatorPackageJson; const genMeta = genData.generatorMeta; const genFilter: GeneratorFilter = GeneratorFilter.create(_.get(packageJson, ["generator-filter"])); const typesHasIntersection: boolean = GeneratorFilter.hasIntersection(filter.types, genFilter.types); const categoriesHasIntersection: boolean = GeneratorFilter.hasIntersection(filter.categories, genFilter.categories); const type = _.includes(genFilter.types, GeneratorType.project) ? "project" : _.includes(genFilter.types, GeneratorType.module) ? "module" : "files"; this.typesMap.set(genMeta.namespace, type); _.includes(genFilter.types, "tools-suite") && this.generatorsToIgnoreArray.push(genMeta.namespace); if (typesHasIntersection && categoriesHasIntersection) { return this.createGeneratorChoice(genMeta.namespace, genMeta.packagePath, packageJson); } } private async createGeneratorChoice(genNamespace: string, genPackagePath: string, packageJson: any): Promise<any> { let genImageUrl; try { genImageUrl = await datauri(path.join(genPackagePath, YeomanUI.YEOMAN_PNG)); } catch (error) { genImageUrl = defaultImage.default; this.logger.debug(error); } const genName = Environment.namespaceToName(genNamespace); const genMessage = _.get(packageJson, "description", YeomanUI.defaultMessage); const genDisplayName = _.get(packageJson, "displayName", ""); const genPrettyName = _.isEmpty(genDisplayName) ? titleize(humanizeString(genName)) : genDisplayName; const genHomepage = _.get(packageJson, "homepage", ""); const filter = _.get(packageJson, "generator-filter", undefined); const isToolsSuiteType = filter ? _.includes(filter.types, "tools-suite") : false; return { genNamespace, value: genNamespace, name: genPrettyName, description: genMessage, homepage: genHomepage, image: genImageUrl, isToolsSuiteType: isToolsSuiteType, }; } /** * * @param questions * returns a deep copy of the original questions, but replaces Function properties with a placeholder * * Functions are lost when being passed to client (using JSON.Stringify) * Also functions cannot be evaluated on client) */ private normalizeFunctions(questions: Questions<any>): Questions<any> { this.addCustomQuestionEventHandlers(questions); return JSON.parse(JSON.stringify(questions, YeomanUI.funcReplacer)); } private setPromptList(prompts: IPrompt[]): Promise<void> { const promptsToDisplay: IPrompt[] = prompts.map((prompt: IPrompt) => { return _.assign({ questions: [], name: "", description: "" }, prompt); }); if (this.replayUtils.isReplaying) { this.replayUtils.setPrompts(promptsToDisplay); } else { return this.rpc.invoke("setPromptList", [promptsToDisplay]); } } private addCustomQuestionEventHandlers(questions: Questions<any>): void { for (const question of questions as any[]) { const guiType = _.get(question, "guiOptions.type", question.guiType); const questionHandlers = this.customQuestionEventHandlers.get(guiType); if (questionHandlers) { questionHandlers.forEach((handler, methodName) => { question[methodName] = handler; }); } } } }
the_stack
import { renderHook } from '@testing-library/react-hooks'; import { useWebSocket } from './use-websocket'; import WS from "jest-websocket-mock"; import { Options } from './types'; import { ReadyState } from './constants'; import { parseSocketIOUrl } from './socket-io'; let server: WS; const URL = 'ws://localhost:1234'; const SOCKET_IO_URL = parseSocketIOUrl(URL); const noop = () => {}; const DEFAULT_OPTIONS: Options = {}; let options: Options; const sleep = (duration: number): Promise<void> => new Promise(resolve => setTimeout(() => resolve(), duration)); console.error = noop; beforeEach(() => { server = new WS(URL); options = { ...DEFAULT_OPTIONS }; }); afterEach(() => { WS.clean(); }); test('useWebsocket should work with just a url provided', () => { expect(() => { renderHook(() => useWebSocket(URL)); }).not.toThrow(); }) test('readyState changes across readyState transitions', async (done) => { const { result, rerender, waitForNextUpdate, } = renderHook(({ initialValue }) => useWebSocket(URL, options, initialValue), { initialProps: { initialValue: false } }) expect(result.current.readyState).toEqual(ReadyState.UNINSTANTIATED); rerender({ initialValue: true }); expect(result.current.readyState).toEqual(ReadyState.CONNECTING); await server.connected; expect(result.current.readyState).toEqual(ReadyState.OPEN); waitForNextUpdate() .then(() => { expect(result.current.readyState).toEqual(ReadyState.CLOSED); done(); }) server.close(); }) test('a function-promise based url works the same as a string-based url', async (done) => { const getUrl = () => { return new Promise<string>(resolve => { setTimeout(() => resolve(URL), 1000); }); } const { result, rerender, waitForNextUpdate, } = renderHook(({ initialValue }) => useWebSocket(getUrl, options, initialValue), { initialProps: { initialValue: false } }) expect(result.current.readyState).toEqual(ReadyState.UNINSTANTIATED); rerender({ initialValue: true }); expect(result.current.readyState).toEqual(ReadyState.CONNECTING); await server.connected; expect(result.current.readyState).toEqual(ReadyState.OPEN); waitForNextUpdate() .then(() => { expect(result.current.readyState).toEqual(ReadyState.CLOSED); done(); }) server.close(); }) test('lastMessage updates when websocket receives a message', async (done) => { const { result, } = renderHook(() => useWebSocket(URL, options)) await server.connected; expect(result.current.lastMessage).toBe(null); server.send('Hello'); expect(result.current.lastMessage?.data).toBe('Hello'); server.send('There'); server.send('Friend'); expect(result.current.lastMessage?.data).toBe('Friend'); done(); }) test('lastJsonMessage updates with a json object when websocket receives a message', async (done) => { const { result, } = renderHook(() => useWebSocket(URL, options)) await server.connected; expect(result.current.lastJsonMessage).toBe(null); server.send(JSON.stringify({ name: 'Bob' })); expect(result.current.lastJsonMessage.name).toBe('Bob'); done(); }) test('sendMessage passes message to websocket and sends to server', async (done) => { const { result, } = renderHook(() => useWebSocket(URL, options)) await server.connected; result.current.sendMessage("Hello"); await expect(server).toReceiveMessage("Hello"); done(); }) test('if sendMessage is called before the websocket opens, the message will be queued and sent when the websocket opens', async (done) => { const { result, } = renderHook(() => useWebSocket(URL, options)) expect(result.current.readyState).not.toEqual(ReadyState.OPEN); result.current.sendMessage("Hello"); await expect(server).toReceiveMessage("Hello"); done(); }) test('sendJsonMessage allows component to pass a json object which is serialized and sent to server', async (done) => { const { result, } = renderHook(() => useWebSocket(URL, options)) await server.connected; result.current.sendJsonMessage({ name: 'Bob' }); await expect(server).toReceiveMessage(JSON.stringify({ name: 'Bob' })); done(); }) test('getWebSocket returns the underlying websocket if unshared', async (done) => { const { result, waitForNextUpdate, } = renderHook(() => useWebSocket(URL, options)) await server.connected; const ws = result.current.getWebSocket(); expect(ws instanceof WebSocket).toBe(true); Promise.race([ waitForNextUpdate(), sleep(500), ]) .then(() => { expect(result.current.readyState).toBe(ReadyState.CLOSED); done(); }) ws?.close(); }) test('getWebSocket returns a protected websocket when shared', async (done) => { options.share = true; const { result, waitForNextUpdate, } = renderHook(() => useWebSocket(URL, options)) await server.connected; const ws = result.current.getWebSocket(); Promise.race([ waitForNextUpdate(), sleep(500), ]) .then(() => { expect(result.current.readyState).toBe(ReadyState.OPEN); done(); }) ws?.close(); }) test('websocket is closed when the component unmounts', async (done) => { const { result, unmount, } = renderHook(() => useWebSocket(URL, options)) await server.connected; const ws = result.current.getWebSocket(); unmount(); expect(ws?.readyState).toBe(ReadyState.CLOSING); await sleep(500); expect(ws?.readyState).toBe(ReadyState.CLOSED); done(); }) test('shared websockets receive updates as if unshared', async (done) => { const { result: component1, } = renderHook(() => useWebSocket(URL, options)) await server.connected; const { result: component2, } = renderHook(() => useWebSocket(URL, options)) await server.connected; const { result: component3, } = renderHook(() => useWebSocket(URL, options)) await server.connected; server.send('Hello all'); expect(component1.current.lastMessage?.data).toBe('Hello all'); expect(component2.current.lastMessage?.data).toBe('Hello all'); expect(component3.current.lastMessage?.data).toBe('Hello all'); done(); }) test('shared websockets each have callbacks invoked as if unshared', async (done) => { const component1OnClose = jest.fn(() => {}); renderHook(() => useWebSocket(URL, { ...options, onClose: component1OnClose, })); await server.connected; const component2OnClose = jest.fn(() => {}); renderHook(() => useWebSocket(URL, { ...options, onClose: component2OnClose, })); await server.connected; const component3OnClose = jest.fn(() => {}); renderHook(() => useWebSocket(URL, { ...options, onClose: component3OnClose, })); await server.connected; expect(component1OnClose).not.toHaveBeenCalled(); expect(component2OnClose).not.toHaveBeenCalled(); expect(component3OnClose).not.toHaveBeenCalled(); server.close(); await sleep(500); expect(component1OnClose).toHaveBeenCalledTimes(1); expect(component2OnClose).toHaveBeenCalledTimes(1); expect(component3OnClose).toHaveBeenCalledTimes(1); done(); }) test('Options#fromSocketIO changes the WS url to support socket.io\'s required query params', async (done) => { options.fromSocketIO = true; const { result, waitForNextUpdate, } = renderHook(() => useWebSocket(URL, options)); await waitForNextUpdate(); const ws = result.current.getWebSocket(); expect(ws?.url).toEqual(SOCKET_IO_URL); done(); }); test('Options#queryParams append object-based params as string to url', async (done) => { options.queryParams = { type: 'user', id: 5 }; const { result, waitForNextUpdate, } = renderHook(() => useWebSocket(URL, options)); await waitForNextUpdate(); const ws = result.current.getWebSocket(); expect(ws?.url).toEqual(`${URL}/?type=user&id=5`); done(); }); test('Options#protocols pass the value on to the instantiated WebSocket', async (done) => { options.protocols = 'chat'; const { result, waitForNextUpdate, } = renderHook(() => useWebSocket(URL, options)); await waitForNextUpdate(); const ws = result.current.getWebSocket(); if (ws instanceof WebSocket) { expect(ws?.protocol).toEqual('chat'); } done(); }); test('Options#share subscribes multiple components to a single WebSocket, so long as the URL is the same', async (done) => { options.share = true; const onConnectionFn = jest.fn(); server.on('connection', onConnectionFn); renderHook(() => useWebSocket(URL, options)); renderHook(() => useWebSocket(URL, options)); renderHook(() => useWebSocket(URL, options)); await sleep(500); expect(onConnectionFn).toHaveBeenCalledTimes(1); done(); }); test('if Options#share is not true, multiple websockets will be opened for the same url', async (done) => { const onConnectionFn = jest.fn(); server.on('connection', onConnectionFn); renderHook(() => useWebSocket(URL, options)); renderHook(() => useWebSocket(URL, options)); renderHook(() => useWebSocket(URL, options)); await sleep(500); expect(onConnectionFn).toHaveBeenCalledTimes(3); done(); }); test('Options#onOpen is called with the open event when the websocket connection opens', async (done) => { const onOpenFn = jest.fn(); options.onOpen = onOpenFn; renderHook(() => useWebSocket(URL, options)); await server.connected; expect(onOpenFn).toHaveBeenCalledTimes(1); expect(onOpenFn.mock.calls[0][0].constructor.name).toBe('Event'); done(); }); test('Options#onClose is called with the close event when the websocket connection closes', async (done) => { const onCloseFn = jest.fn(); options.onClose = onCloseFn; const { waitForNextUpdate } = renderHook(() => useWebSocket(URL, options)); await server.connected; waitForNextUpdate() .then(() => { expect(onCloseFn).toHaveBeenCalledTimes(1); expect(onCloseFn.mock.calls[0][0].constructor.name).toBe('CloseEvent'); done(); }) server.close(); }); test('Options#onMessage is called with the MessageEvent when the websocket receives a message', async (done) => { const onMessageFn = jest.fn(); options.onMessage = onMessageFn; const { waitForNextUpdate } = renderHook(() => useWebSocket(URL, options)); await server.connected; waitForNextUpdate() .then(() => { expect(onMessageFn).toHaveBeenCalledTimes(1); expect(onMessageFn.mock.calls[0][0].constructor.name).toBe('MessageEvent'); done(); }) server.send('Hello'); }); test('Options#onError is called when the websocket connection errors out', async (done) => { const onErrorFn = jest.fn(); options.onError = onErrorFn; const { waitForNextUpdate } = renderHook(() => useWebSocket(URL, options)); await server.connected; waitForNextUpdate() .then(() => { expect(onErrorFn).toHaveBeenCalledTimes(1); expect(onErrorFn.mock.calls[0][0].constructor.name).toBe('MessageEvent'); done(); }) server.error(); }); test('Options#shouldReconnect controls whether a closed websocket should attempt to reconnect', async (done) => { options.shouldReconnect = () => false; options.reconnectInterval = 500; //Default interval is too long for tests const onConnectionFn = jest.fn((ws: any) => ws.close()); server.on('connection', onConnectionFn); renderHook(() => useWebSocket(URL, options)); await sleep(600);//100ms buffer to avoid race condition expect(onConnectionFn).toHaveBeenCalledTimes(1); options.shouldReconnect = () => true; renderHook(() => useWebSocket(URL, options)); await sleep(600); expect(onConnectionFn).toHaveBeenCalledTimes(3); done(); }); test('Options#onReconnectStop is called when the websocket exceeds maximum reconnect attempts provided in options, or 20 by default', async (done) => { options.shouldReconnect = () => true; options.reconnectAttempts = 3; options.reconnectInterval = 500; //Default interval is too long for tests const onReconnectStopFn = jest.fn((numAttempts: number) => {}); options.onReconnectStop = onReconnectStopFn; renderHook(() => useWebSocket(URL, options)); await server.connected; server.close(); expect(onReconnectStopFn).not.toHaveBeenCalled(); await sleep(2000); expect(onReconnectStopFn).toHaveBeenCalled(); expect(onReconnectStopFn.mock.calls[0][0]).toBe(3); done(); }); test('Options#filter accepts all incoming messages, but only where it returns true will the message update a component', async (done) => { options.filter = () => false; const { result } = renderHook(() => useWebSocket(URL, options)); await server.connected; server.send('Hello'); await sleep(500); expect(result.current.lastMessage).toBeNull(); done(); }); test('Options#retryOnError controls whether a websocket should attempt to reconnect after an error event', async (done) => { options.retryOnError = false; options.reconnectAttempts = 3; options.reconnectInterval = 500; const onReconnectStopFn1 = jest.fn(); options.onReconnectStop = onReconnectStopFn1; renderHook(() => useWebSocket(URL, options)); await server.connected; server.error(); await sleep(1600); expect(onReconnectStopFn1).not.toHaveBeenCalled(); options.retryOnError = true; const onReconnectStopFn2 = jest.fn(); options.onReconnectStop = onReconnectStopFn2; renderHook(() => useWebSocket(URL, options)); await server.connected; server.error(); await sleep(1600); expect(onReconnectStopFn2).toHaveBeenCalled(); done(); }); test('Options#eventSourceOptions, if provided, instantiates an EventSource instead of a WebSocket', async (done) => { options.eventSourceOptions = { withCredentials: true }; const { result, waitForNextUpdate } = renderHook(() => useWebSocket(URL, options)); await waitForNextUpdate(); expect(result.current.getWebSocket() instanceof EventSource).toBe(true); done(); }); //TODO: Write companion tests for useSocketIO
the_stack
import * as coreClient from "@azure/core-client"; export interface ErrorModel { status?: number; message?: string; } export interface Widget { integer?: number; string?: string; } /** Optional parameters. */ export interface DictionaryGetNullOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getNull operation. */ export type DictionaryGetNullResponse = { [propertyName: string]: number }; /** Optional parameters. */ export interface DictionaryGetEmptyOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getEmpty operation. */ export type DictionaryGetEmptyResponse = { [propertyName: string]: number }; /** Optional parameters. */ export interface DictionaryPutEmptyOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DictionaryGetNullValueOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getNullValue operation. */ export type DictionaryGetNullValueResponse = { [propertyName: string]: string }; /** Optional parameters. */ export interface DictionaryGetNullKeyOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getNullKey operation. */ export type DictionaryGetNullKeyResponse = { [propertyName: string]: string }; /** Optional parameters. */ export interface DictionaryGetEmptyStringKeyOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getEmptyStringKey operation. */ export type DictionaryGetEmptyStringKeyResponse = { [propertyName: string]: string; }; /** Optional parameters. */ export interface DictionaryGetInvalidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getInvalid operation. */ export type DictionaryGetInvalidResponse = { [propertyName: string]: string }; /** Optional parameters. */ export interface DictionaryGetBooleanTfftOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getBooleanTfft operation. */ export type DictionaryGetBooleanTfftResponse = { [propertyName: string]: boolean; }; /** Optional parameters. */ export interface DictionaryPutBooleanTfftOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DictionaryGetBooleanInvalidNullOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getBooleanInvalidNull operation. */ export type DictionaryGetBooleanInvalidNullResponse = { [propertyName: string]: boolean; }; /** Optional parameters. */ export interface DictionaryGetBooleanInvalidStringOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getBooleanInvalidString operation. */ export type DictionaryGetBooleanInvalidStringResponse = { [propertyName: string]: boolean; }; /** Optional parameters. */ export interface DictionaryGetIntegerValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getIntegerValid operation. */ export type DictionaryGetIntegerValidResponse = { [propertyName: string]: number; }; /** Optional parameters. */ export interface DictionaryPutIntegerValidOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DictionaryGetIntInvalidNullOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getIntInvalidNull operation. */ export type DictionaryGetIntInvalidNullResponse = { [propertyName: string]: number; }; /** Optional parameters. */ export interface DictionaryGetIntInvalidStringOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getIntInvalidString operation. */ export type DictionaryGetIntInvalidStringResponse = { [propertyName: string]: number; }; /** Optional parameters. */ export interface DictionaryGetLongValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getLongValid operation. */ export type DictionaryGetLongValidResponse = { [propertyName: string]: number }; /** Optional parameters. */ export interface DictionaryPutLongValidOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DictionaryGetLongInvalidNullOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getLongInvalidNull operation. */ export type DictionaryGetLongInvalidNullResponse = { [propertyName: string]: number; }; /** Optional parameters. */ export interface DictionaryGetLongInvalidStringOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getLongInvalidString operation. */ export type DictionaryGetLongInvalidStringResponse = { [propertyName: string]: number; }; /** Optional parameters. */ export interface DictionaryGetFloatValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getFloatValid operation. */ export type DictionaryGetFloatValidResponse = { [propertyName: string]: number; }; /** Optional parameters. */ export interface DictionaryPutFloatValidOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DictionaryGetFloatInvalidNullOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getFloatInvalidNull operation. */ export type DictionaryGetFloatInvalidNullResponse = { [propertyName: string]: number; }; /** Optional parameters. */ export interface DictionaryGetFloatInvalidStringOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getFloatInvalidString operation. */ export type DictionaryGetFloatInvalidStringResponse = { [propertyName: string]: number; }; /** Optional parameters. */ export interface DictionaryGetDoubleValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getDoubleValid operation. */ export type DictionaryGetDoubleValidResponse = { [propertyName: string]: number; }; /** Optional parameters. */ export interface DictionaryPutDoubleValidOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DictionaryGetDoubleInvalidNullOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getDoubleInvalidNull operation. */ export type DictionaryGetDoubleInvalidNullResponse = { [propertyName: string]: number; }; /** Optional parameters. */ export interface DictionaryGetDoubleInvalidStringOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getDoubleInvalidString operation. */ export type DictionaryGetDoubleInvalidStringResponse = { [propertyName: string]: number; }; /** Optional parameters. */ export interface DictionaryGetStringValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getStringValid operation. */ export type DictionaryGetStringValidResponse = { [propertyName: string]: string; }; /** Optional parameters. */ export interface DictionaryPutStringValidOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DictionaryGetStringWithNullOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getStringWithNull operation. */ export type DictionaryGetStringWithNullResponse = { [propertyName: string]: string; }; /** Optional parameters. */ export interface DictionaryGetStringWithInvalidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getStringWithInvalid operation. */ export type DictionaryGetStringWithInvalidResponse = { [propertyName: string]: string; }; /** Optional parameters. */ export interface DictionaryGetDateValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getDateValid operation. */ export type DictionaryGetDateValidResponse = { [propertyName: string]: Date }; /** Optional parameters. */ export interface DictionaryPutDateValidOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DictionaryGetDateInvalidNullOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getDateInvalidNull operation. */ export type DictionaryGetDateInvalidNullResponse = { [propertyName: string]: Date; }; /** Optional parameters. */ export interface DictionaryGetDateInvalidCharsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getDateInvalidChars operation. */ export type DictionaryGetDateInvalidCharsResponse = { [propertyName: string]: Date; }; /** Optional parameters. */ export interface DictionaryGetDateTimeValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getDateTimeValid operation. */ export type DictionaryGetDateTimeValidResponse = { [propertyName: string]: Date; }; /** Optional parameters. */ export interface DictionaryPutDateTimeValidOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DictionaryGetDateTimeInvalidNullOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getDateTimeInvalidNull operation. */ export type DictionaryGetDateTimeInvalidNullResponse = { [propertyName: string]: Date; }; /** Optional parameters. */ export interface DictionaryGetDateTimeInvalidCharsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getDateTimeInvalidChars operation. */ export type DictionaryGetDateTimeInvalidCharsResponse = { [propertyName: string]: Date; }; /** Optional parameters. */ export interface DictionaryGetDateTimeRfc1123ValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getDateTimeRfc1123Valid operation. */ export type DictionaryGetDateTimeRfc1123ValidResponse = { [propertyName: string]: Date; }; /** Optional parameters. */ export interface DictionaryPutDateTimeRfc1123ValidOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DictionaryGetDurationValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getDurationValid operation. */ export type DictionaryGetDurationValidResponse = { [propertyName: string]: string; }; /** Optional parameters. */ export interface DictionaryPutDurationValidOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DictionaryGetByteValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getByteValid operation. */ export type DictionaryGetByteValidResponse = { [propertyName: string]: Uint8Array; }; /** Optional parameters. */ export interface DictionaryPutByteValidOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DictionaryGetByteInvalidNullOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getByteInvalidNull operation. */ export type DictionaryGetByteInvalidNullResponse = { [propertyName: string]: Uint8Array; }; /** Optional parameters. */ export interface DictionaryGetBase64UrlOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getBase64Url operation. */ export type DictionaryGetBase64UrlResponse = { [propertyName: string]: Uint8Array; }; /** Optional parameters. */ export interface DictionaryGetComplexNullOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getComplexNull operation. */ export type DictionaryGetComplexNullResponse = { [propertyName: string]: Widget; }; /** Optional parameters. */ export interface DictionaryGetComplexEmptyOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getComplexEmpty operation. */ export type DictionaryGetComplexEmptyResponse = { [propertyName: string]: Widget; }; /** Optional parameters. */ export interface DictionaryGetComplexItemNullOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getComplexItemNull operation. */ export type DictionaryGetComplexItemNullResponse = { [propertyName: string]: Widget | null; }; /** Optional parameters. */ export interface DictionaryGetComplexItemEmptyOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getComplexItemEmpty operation. */ export type DictionaryGetComplexItemEmptyResponse = { [propertyName: string]: Widget; }; /** Optional parameters. */ export interface DictionaryGetComplexValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getComplexValid operation. */ export type DictionaryGetComplexValidResponse = { [propertyName: string]: Widget; }; /** Optional parameters. */ export interface DictionaryPutComplexValidOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DictionaryGetArrayNullOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getArrayNull operation. */ export type DictionaryGetArrayNullResponse = { [propertyName: string]: string[]; }; /** Optional parameters. */ export interface DictionaryGetArrayEmptyOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getArrayEmpty operation. */ export type DictionaryGetArrayEmptyResponse = { [propertyName: string]: string[]; }; /** Optional parameters. */ export interface DictionaryGetArrayItemNullOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getArrayItemNull operation. */ export type DictionaryGetArrayItemNullResponse = { [propertyName: string]: string[] | null; }; /** Optional parameters. */ export interface DictionaryGetArrayItemEmptyOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getArrayItemEmpty operation. */ export type DictionaryGetArrayItemEmptyResponse = { [propertyName: string]: string[]; }; /** Optional parameters. */ export interface DictionaryGetArrayValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getArrayValid operation. */ export type DictionaryGetArrayValidResponse = { [propertyName: string]: string[]; }; /** Optional parameters. */ export interface DictionaryPutArrayValidOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface DictionaryGetDictionaryNullOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getDictionaryNull operation. */ export type DictionaryGetDictionaryNullResponse = { [propertyName: string]: { [propertyName: string]: string }; }; /** Optional parameters. */ export interface DictionaryGetDictionaryEmptyOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getDictionaryEmpty operation. */ export type DictionaryGetDictionaryEmptyResponse = { [propertyName: string]: { [propertyName: string]: string }; }; /** Optional parameters. */ export interface DictionaryGetDictionaryItemNullOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getDictionaryItemNull operation. */ export type DictionaryGetDictionaryItemNullResponse = { [propertyName: string]: { [propertyName: string]: string } | null; }; /** Optional parameters. */ export interface DictionaryGetDictionaryItemEmptyOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getDictionaryItemEmpty operation. */ export type DictionaryGetDictionaryItemEmptyResponse = { [propertyName: string]: { [propertyName: string]: string }; }; /** Optional parameters. */ export interface DictionaryGetDictionaryValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getDictionaryValid operation. */ export type DictionaryGetDictionaryValidResponse = { [propertyName: string]: { [propertyName: string]: string }; }; /** Optional parameters. */ export interface DictionaryPutDictionaryValidOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface BodyDictionaryClientOptionalParams extends coreClient.ServiceClientOptions { /** server parameter */ $host?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import { buildTestingEnvironment } from "../environment/testing/fake"; import { PullRequestReference } from "../github-api/api"; import { LoadedState, ref } from "../storage/loaded-state"; import { MuteConfiguration, NOTHING_MUTED, } from "../storage/mute-configuration"; import { fakePullRequest } from "../testing/fake-pr"; import { Core } from "./core"; describe("Core", () => { it("loads correctly without token", async () => { const env = buildTestingEnvironment(); const core = new Core(env); // No token stored. env.store.token.currentValue = null; // Other things are stored, they should be ignored. env.store.lastError.currentValue = "error"; env.store.currentlyRefreshing.currentValue = true; env.store.lastCheck.currentValue = { userLogin: "fwouts", openPullRequests: [], }; env.store.notifiedPullRequests.currentValue = ["a", "b", "c"]; env.store.muteConfiguration.currentValue = { mutedPullRequests: [ { repo: { owner: "zenclabs", name: "prmonitor", }, number: 1, until: { kind: "next-update", mutedAtTimestamp: 123, }, }, ], }; // Initialise. await core.load(); expect(core.token).toBeNull(); expect(core.lastError).toBeNull(); expect(core.refreshing).toBe(false); expect(core.loadedState).toBeNull(); expect(core.muteConfiguration).toEqual(NOTHING_MUTED); expect(core.notifiedPullRequestUrls.size).toBe(0); }); it("loads with token", async () => { const env = buildTestingEnvironment(); const core = new Core(env); // A valid token is stored. env.store.token.currentValue = "valid-token"; // Other things are stored, they should be restored. const state = { userLogin: "fwouts", repos: [], openPullRequests: [], }; const notifiedPullRequestUrls = ["a", "b", "c"]; const muteConfiguration: MuteConfiguration = { mutedPullRequests: [ { repo: { owner: "zenclabs", name: "prmonitor", }, number: 1, until: { kind: "next-update", mutedAtTimestamp: 123, }, }, ], }; env.store.lastError.currentValue = "error"; env.store.currentlyRefreshing.currentValue = true; env.store.lastCheck.currentValue = state; env.store.notifiedPullRequests.currentValue = notifiedPullRequestUrls; env.store.muteConfiguration.currentValue = muteConfiguration; // Initialise. await core.load(); expect(core.token).toEqual("valid-token"); expect(core.lastError).toEqual("error"); expect(core.refreshing).toBe(true); expect(core.loadedState).toEqual(state); expect(core.muteConfiguration).toEqual(muteConfiguration); expect(Array.from(core.notifiedPullRequestUrls)).toEqual( notifiedPullRequestUrls ); }); it("reloads when receiving a load message", () => { const env = buildTestingEnvironment(); // Initialize the core. // TODO: Consider adding the listener in a separate init() method. new Core(env); expect(env.store.token.loadCount).toBe(0); env.messenger.trigger({ kind: "reload", }); expect(env.store.token.loadCount).toBe(1); }); it("doesn't reload on non-reload message", () => { const env = buildTestingEnvironment(); // Initialize the core. // TODO: Consider adding the listener in a separate init() method. new Core(env); expect(env.store.token.loadCount).toBe(0); env.messenger.trigger({ kind: "refresh", }); expect(env.store.token.loadCount).toBe(0); }); it("opens the pull request when notification is clicked", () => { const env = buildTestingEnvironment(); // Initialize the core. // TODO: Consider adding the listener in a separate init() method. new Core(env); env.notifier.simulateClick("http://some-pr"); expect(env.tabOpener.openedUrls).toEqual(["http://some-pr"]); }); it("opens the pull request when openPullRequest() is called", () => { const env = buildTestingEnvironment(); // Initialize the core. const core = new Core(env); core.openPullRequest("http://some-pr"); expect(env.tabOpener.openedUrls).toEqual(["http://some-pr"]); }); it("resets state and triggers a refresh when a new token is set", async () => { const env = buildTestingEnvironment(); const core = new Core(env); // A valid token is stored. env.store.token.currentValue = "token-fwouts"; const state = { userLogin: "fwouts", repos: [], openPullRequests: [], }; env.store.currentlyRefreshing.currentValue = true; env.store.lastCheck.currentValue = state; // Initialise. await core.load(); expect(core.loadedState && core.loadedState.userLogin).toBe("fwouts"); await core.setNewToken("token-kevin"); expect(core.loadedState).toBeNull(); expect(env.store.token.currentValue).toEqual("token-kevin"); expect(env.store.lastError.currentValue).toEqual(null); expect(env.store.currentlyRefreshing.currentValue).toBe(false); expect(env.store.notifiedPullRequests.currentValue).toEqual([]); expect(env.store.lastCheck.currentValue).toEqual(null); expect(env.store.muteConfiguration.currentValue).toEqual(NOTHING_MUTED); expect(env.messenger.sent).toEqual([{ kind: "refresh" }]); }); it("doesn't refresh when not authenticated", async () => { const env = buildTestingEnvironment(); const core = new Core(env); env.store.token.currentValue = null; // Initialise. await core.load(); expect(core.refreshing).toBe(false); // Refresh. await core.refreshPullRequests(); expect(env.githubLoader).not.toHaveBeenCalled(); expect(core.refreshing).toBe(false); expect(core.lastError).toBeNull(); }); it("doesn't refresh when offline", async () => { const env = buildTestingEnvironment(); const core = new Core(env); env.store.token.currentValue = "valid-token"; env.online = false; // Initialise. await core.load(); expect(core.refreshing).toBe(false); // Refresh. await core.refreshPullRequests(); expect(env.githubLoader).not.toHaveBeenCalled(); expect(core.refreshing).toBe(false); expect(core.lastError).toBeNull(); }); test("successful refresh after no stored state updates badge", async () => { const env = buildTestingEnvironment(); const core = new Core(env); env.store.token.currentValue = "valid-token"; // Initialise. await core.load(); expect(core.refreshing).toBe(false); expect(env.badger.updated).toEqual([ { kind: "initializing", }, ]); // Refresh. env.githubLoader.mockReturnValue( Promise.resolve<LoadedState>({ userLogin: "fwouts", openPullRequests: [], }) ); await core.refreshPullRequests(); expect(env.githubLoader).toHaveBeenCalled(); expect(core.refreshing).toBe(false); expect(env.store.lastError.currentValue).toBeNull(); expect(env.badger.updated).toEqual([ { kind: "initializing", }, { kind: "initializing", }, { kind: "loaded", unreviewedPullRequestCount: 0, }, ]); expect(env.messenger.sent).toEqual([ { kind: "reload" }, { kind: "reload" }, ]); }); test("successful refresh after a previous state updates badge", async () => { const env = buildTestingEnvironment(); const core = new Core(env); env.store.lastCheck.currentValue = { userLogin: "fwouts", openPullRequests: [], }; env.store.token.currentValue = "valid-token"; // Initialise. await core.load(); expect(core.refreshing).toBe(false); expect(env.badger.updated).toEqual([ { kind: "loaded", unreviewedPullRequestCount: 0, }, ]); // Refresh. env.githubLoader.mockReturnValue( Promise.resolve<LoadedState>({ userLogin: "fwouts", openPullRequests: [], }) ); await core.refreshPullRequests(); expect(env.githubLoader).toHaveBeenCalled(); expect(core.refreshing).toBe(false); expect(env.store.lastError.currentValue).toBeNull(); expect(env.badger.updated).toEqual([ { kind: "loaded", unreviewedPullRequestCount: 0, }, { kind: "reloading", unreviewedPullRequestCount: 0, }, { kind: "loaded", unreviewedPullRequestCount: 0, }, ]); expect(env.messenger.sent).toEqual([ { kind: "reload" }, { kind: "reload" }, ]); }); test("successful refresh after a previous error updates badge and clears error", async () => { const env = buildTestingEnvironment(); const core = new Core(env); env.store.lastError.currentValue = "old error"; env.store.token.currentValue = "valid-token"; // Initialise. await core.load(); expect(core.refreshing).toBe(false); expect(env.badger.updated).toEqual([ { kind: "error", }, ]); // Refresh. env.githubLoader.mockReturnValue( Promise.resolve<LoadedState>({ userLogin: "fwouts", openPullRequests: [], }) ); await core.refreshPullRequests(); expect(env.githubLoader).toHaveBeenCalled(); expect(core.refreshing).toBe(false); expect(env.store.lastError.currentValue).toBeNull(); expect(env.badger.updated).toEqual([ { kind: "error", }, { kind: "error", }, { kind: "loaded", unreviewedPullRequestCount: 0, }, ]); expect(env.messenger.sent).toEqual([ { kind: "reload" }, { kind: "reload" }, ]); }); test("failed refresh updates badge and error", async () => { const env = buildTestingEnvironment(); const core = new Core(env); env.store.lastCheck.currentValue = { userLogin: "fwouts", openPullRequests: [], }; env.store.token.currentValue = "valid-token"; // Initialise. await core.load(); expect(core.refreshing).toBe(false); expect(env.badger.updated).toEqual([ { kind: "loaded", unreviewedPullRequestCount: 0, }, ]); // Refresh. env.githubLoader.mockReturnValue(Promise.reject(new Error("Oh noes!"))); await expect(core.refreshPullRequests()).rejects.toEqual( new Error("Oh noes!") ); expect(env.githubLoader).toHaveBeenCalled(); expect(core.refreshing).toBe(false); expect(env.store.lastError.currentValue).toEqual("Oh noes!"); expect(env.badger.updated).toEqual([ { kind: "loaded", unreviewedPullRequestCount: 0, }, { kind: "reloading", unreviewedPullRequestCount: 0, }, { kind: "error", }, ]); expect(env.messenger.sent).toEqual([ { kind: "reload" }, { kind: "reload" }, ]); }); it("notifies of new pull requests and saves notified state", async () => { const env = buildTestingEnvironment(); const core = new Core(env); env.store.token.currentValue = "valid-token"; // Initialise. await core.load(); expect(env.store.lastCheck.currentValue).toBeNull(); // Refresh. env.githubLoader.mockReturnValue( Promise.resolve<LoadedState>({ userLogin: "fwouts", openPullRequests: [ fakePullRequest() .ref("zenclabs", "prmonitor", 1) .author("kevin") .seenAs("fwouts") .reviewRequested(["fwouts"]) .build(), ], }) ); await core.refreshPullRequests(); expect( env.store.lastCheck.currentValue && env.store.lastCheck.currentValue.openPullRequests ).toHaveLength(1); expect(core.unreviewedPullRequests).toHaveLength(1); expect(env.notifier.notified).toEqual([ ["http://github.com/zenclabs/prmonitor/1"], ]); expect(env.store.notifiedPullRequests.currentValue).toEqual([ "http://github.com/zenclabs/prmonitor/1", ]); }); it("updates badge after muting and unmuting a PR", async () => { const env = buildTestingEnvironment(); const core = new Core(env); env.store.token.currentValue = "valid-token"; const pr1 = fakePullRequest() .ref("zenclabs", "prmonitor", 1) .author("kevin") .seenAs("fwouts") .reviewRequested(["fwouts"]) .build(); const pr2 = fakePullRequest() .ref("zenclabs", "prmonitor", 2) .author("kevin") .seenAs("fwouts") .reviewRequested(["fwouts"]) .build(); env.store.lastCheck.currentValue = { userLogin: "fwouts", openPullRequests: [pr1, pr2], }; // Initialise. await core.load(); expect(env.badger.updated).toEqual([ { kind: "loaded", unreviewedPullRequestCount: 2, }, ]); // Mute the PR. await core.mutePullRequest(ref(pr1), "next-update"); expect(env.badger.updated).toEqual([ { kind: "loaded", unreviewedPullRequestCount: 2, }, { kind: "loaded", unreviewedPullRequestCount: 1, }, ]); // Unmute the PR. await core.unmutePullRequest(ref(pr1)); expect(env.badger.updated).toEqual([ { kind: "loaded", unreviewedPullRequestCount: 2, }, { kind: "loaded", unreviewedPullRequestCount: 1, }, { kind: "loaded", unreviewedPullRequestCount: 2, }, ]); }); it("doesn't duplicate muted pull requests", async () => { const env = buildTestingEnvironment(); const core = new Core(env); await core.load(); const pr1: PullRequestReference = { repo: { owner: "zenclabs", name: "prmonitor", }, number: 1, }; const pr2: PullRequestReference = { repo: { owner: "zenclabs", name: "prmonitor", }, number: 2, }; // Mute two PRs (on different dates). env.currentTime = 1; await core.mutePullRequest(pr1, "next-update"); env.currentTime = 2; await core.mutePullRequest(pr2, "next-update"); // Late on, mute the first PR again env.currentTime = 3; await core.mutePullRequest(pr1, "next-update"); expect(core.muteConfiguration.mutedPullRequests).toHaveLength(2); expect(core.muteConfiguration.mutedPullRequests[0]).toEqual({ ...pr2, until: { kind: "next-update", mutedAtTimestamp: 2, }, }); expect(core.muteConfiguration.mutedPullRequests[1]).toEqual({ ...pr1, until: { kind: "next-update", mutedAtTimestamp: 3, }, }); }); });
the_stack
import {NOTE_LENGTH,ACCIDENTAL,CLEF, ARTICULATION, CUE, BRACKET} from './common'; import {HERSHEY,Hershey_entry,ascii_map, get_text_width, FONT} from './hershey'; export interface Element{ tag: string; x: number; y: number; w: number; h: number; [other_options: string]: any } export interface Drawing{ w:number; h:number; elements:Element[]; polylines:[number,number][][]; } export function export_mock_svg(dr:Drawing):string{ let width = dr.w; let height = dr.h; let elements = dr.elements; let o : string = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">`; for (let i = 0; i < elements.length; i++){ let elt = elements[i]; let {tag,x,y,w,h} = elt; if (tag == 'note_head'){ if (elt.stem_dir < 0){ if (elt.twisted){ o += `<rect x="${x}" y="${y-2}" width="${10}" height="${4}" fill="blue"/>`; }else{ o += `<rect x="${x-10}" y="${y-2}" width="${10}" height="${4}" fill="blue"/>`; } }else{ if (!elt.twisted){ o += `<rect x="${x}" y="${y-2}" width="${10}" height="${4}" fill="blue"/>`; }else{ o += `<rect x="${x-10}" y="${y-2}" width="${10}" height="${4}" fill="blue"/>`; } } o += `<text x="${x}" y="${y}" font-size="8" fill="red">${elt.duration}</text>` }else if (tag == 'rest'){ o += `<rect x="${x-w/2}" y="${y-h/2}" width="${w}" height="${h}" fill="rgba(0,255,0,0.2)" stroke="black"/>` o += `<text x="${x-w/2}" y="${y-h/2}" font-size="8">${elt.duration}</text>` }else if (tag == 'accidental' || tag == 'clef' || tag == 'timesig_digit'){ o += `<rect x="${x-w/2}" y="${y-h/2}" width="${w}" height="${h}" fill="rgba(255,255,0,0.2)" stroke="black"/>` }else if (tag == 'beam'){ o += `<line x1="${x}" y1="${y}" x2="${x+w}" y2="${y+h}" stroke="brown" stroke-width="3"/>` }else if (tag == 'line'){ o += `<line x1="${x}" y1="${y}" x2="${x+w}" y2="${y+h}" stroke="black"/>` }else if (tag == 'dbg'){ o += `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="${elt.color}" opacity="0.1"/>` }else{ o += `<rect x="${x}" y="${y}" width="${w||1}" height="${h||1}" fill="rgba(0,0,0,0.2)" stroke="black"/>` o += `<text x="${x}" y="${y}" font-size="5">${tag}</text>` } // } o += `</svg>`; return o; } function xform(polylines:[number,number][][],fn:(x:number,y:number)=>[number,number]):[number,number][][]{ return polylines.map(p=>p.map(xy=>fn(xy[0],xy[1]))); } function cubic_bezier(x0:number,y0:number,x1:number,y1:number,x2:number,y2:number,x3:number,y3:number,t:number):[number,number]{ let s = 1-t; let s2 = s*s; let s3 = s*s2; let t2 = t*t; let t3 = t2*t; return [ s3*x0+3*s2*t*x1+3*s*t2*x2+t3*x3, s3*y0+3*s2*t*y1+3*s*t2*y2+t3*y3, ] } let symbols : Record<string,[number,number][][]> = {}; ;(function make_symbols(){ function note_var(p : [number,number][][],stem_dir:number,twisted:boolean):[number,number][][]{ if (stem_dir < 0){ if (twisted){ p = xform(p,(u,v)=>[u+5,v]); }else{ p = xform(p,(u,v)=>[u-6,v]); } }else{ if (twisted){ p = xform(p,(u,v)=>[u-6,v]); }else{ p = xform(p,(u,v)=>[u+5,v]); } } return p; } let p : [number,number][][]; { p = HERSHEY(2370).polylines; symbols['note_whole_up_twist'] = note_var(p,-1,true); symbols['note_whole_down_twist'] = note_var(p,1,true); symbols['note_whole_up'] = note_var(p,-1,false); symbols['note_whole_down'] = note_var(p,1,false); }{ p = HERSHEY(2371).polylines; p = xform(p,(u,v)=>scale_axis(u,v,1,0.9,0.4634)); p = p.slice(0,1).concat(xform(p.slice(0,1),(u,v)=>scale_axis(u,v,1,0.75,0.4634))); p = xform(p,(u,v)=>[u*0.82+0.5,v]); symbols['note_half_up_twist'] = note_var(p,-1,true); symbols['note_half_down_twist'] = note_var(p,1,true); symbols['note_half_up'] = note_var(p,-1,false); symbols['note_half_down'] = note_var(p,1,false); }{ p = HERSHEY(2372).polylines; // p = p.filter((x,i)=>!(i%2)); p = xform(p,(u,v)=>scale_axis(u,v,1,0.8,0.4634)); symbols['note_fill_up_twist'] = note_var(p,-1,true); symbols['note_fill_down_twist'] = note_var(p,1,true); symbols['note_fill_up'] = note_var(p,-1,false); symbols['note_fill_down'] = note_var(p,1,false); }{ p = HERSHEY(2317).polylines; symbols['dot'] = xform(p,(u,v)=>[u*1.1,v*1.1]); }{ p = HERSHEY(2325).polylines; symbols['acc_flat'] = xform(p,(u,v)=>[u*0.7,v+0.5]); }{ p = HERSHEY(2324).polylines; symbols['acc_nat'] = xform(p,(u,v)=>[u*0.7,v]); }{ p = HERSHEY(2323).polylines; p = xform(p,(u,v)=>[u*0.9,v*1.1-u*0.2]); p[3] = xform(p.slice(3,4),(u,v)=>[u,v+0.15])[0]; p[5] = xform(p.slice(5,6),(u,v)=>[u,v+0.15])[0]; symbols['acc_sharp'] = p; }{ p = HERSHEY(2380).polylines; symbols['clef_g'] = xform(p,(u,v)=>rotate(u,v,-0.15)); }{ p = HERSHEY(2381).polylines; symbols['clef_f'] = xform(p,(u,v)=>[u-9,v]); }{ p = HERSHEY(2382).polylines; symbols['clef_c'] = xform(p,(u,v)=>[u,(v)*0.9]); }{ p = HERSHEY(2376).polylines; symbols['rest_whole'] = xform(p,(u,v)=>[u*0.85,v*1.25+2.25]); }{ p = HERSHEY(2377).polylines; symbols['rest_half'] = xform(p,(u,v)=>[u,v*1.25+1]); }{ p = HERSHEY(2378).polylines; symbols['rest_quarter'] = xform(p,(u,v)=>rotate(u,v,-0.1)); }{ p = HERSHEY(2379).polylines; symbols['rest_8'] = xform(p,(u,v)=>[u,v]); }{ p = HERSHEY(2379).polylines; let q = xform(p,(u,v)=>[u,v]); q[q.length-1][q[q.length-1].length-1][0] += 0.93; q[q.length-1][q[q.length-1].length-1][1] -= 3; p = xform(p,(u,v)=>[u-3.07,v+10]); symbols['rest_16'] = q.concat(p); }{ p = HERSHEY(2379).polylines; let q = xform(p,(u,v)=>[u,v]); q[q.length-1][q[q.length-1].length-1][0] += 0.93; q[q.length-1][q[q.length-1].length-1][1] -= 3; let a = (xform(q,(u,v)=>[u+3.07,v-10])); let c = (xform(p,(u,v)=>[u-3.07,v+10])); symbols['rest_32'] = a.concat(q).concat(c); }{ p = HERSHEY(2379).polylines; let q = xform(p,(u,v)=>[u,v]); q[q.length-1][q[q.length-1].length-1][0] += 0.93; q[q.length-1][q[q.length-1].length-1][1] -= 3; let a = (xform(q,(u,v)=>[u+4.07,v-10])); let b = (xform(q,(u,v)=>[u+1,v])); let c = (xform(p,(u,v)=>[u-2.07,v+10])); let d = (xform(p,(u,v)=>[u-5.14,v+20])); symbols['rest_64'] = a.concat(b).concat(c).concat(d); }{ p = HERSHEY(2368).polylines; p = xform(p,(u,v)=>[u+5,(v+2.5)*1.5]); symbols['flag_up'] = p; p = xform(p,(u,v)=>[u,v]); p[0].pop(); p[0].pop(); p[0][p[0].length-1][1]+=3; symbols['flag_mid_up'] = p; }{ p = HERSHEY(2369).polylines; p = xform(p,(u,v)=>[u+5,(v-2.5)*1.5]); symbols['flag_down'] = p; p = xform(p,(u,v)=>[u,v]); p[p.length-1].shift(); p[p.length-1].shift(); p[p.length-1][0][1]-=3; symbols['flag_mid_down'] = p; }{ for (let i = 0; i < 10; i++){ p = HERSHEY(3200+i).polylines; symbols['timesig_digit_'+i] = xform(p,(u,v)=>[u,v*0.85+1.1]); } }{ for (let i = 0; i < 10; i++){ p = HERSHEY(2200+i).polylines; symbols['tuplet_digit_'+i] = xform(p,(u,v)=>[(u)*0.5,v*0.5]); } }{ p = HERSHEY(3103).polylines; symbols['timesig_c'] = xform(p,(u,v)=>[u,v*1.2-2.5]); }{ p = [[]]; for (let i = 0; i < 8; i++){ let a = i/7*Math.PI; p[0].push([ Math.cos(a)*6, 1-Math.sin(a)*6, ]) } p.push([[-1,1],[0,0],[1,1],[0,2]]) symbols['fermata']=p; }{ p = [] p.push([ [-8,2],[-5,-1],[-2,2],[1,-1],[4,2],[7,-1] ]) p.push([ [-4,-2],[-1,1] ]); p.push([ [2,-2],[5,1] ]); symbols['mordent']=p; }{ p = HERSHEY(2274).polylines.slice(-2); p = xform(p,(u,v)=>rotate(-u*0.4,v*0.6,Math.PI/2)); symbols['turn']=p; }{ p = xform(HERSHEY(2670).polylines,(u,v)=>[u*0.8-4,v*0.8]).concat( xform(HERSHEY(2668).polylines,(u,v)=>[u*0.8+4.5,v*0.8-0.5])); symbols['trill']=p; }{ p = xform(HERSHEY(2218).polylines,(u,v)=>[u,v+8]); symbols['flageolet']=p; }{ p = xform(HERSHEY(3316).polylines,(u,v)=>[u*0.8-11,v*0.8-3]).concat( xform(HERSHEY(3405).polylines,(u,v)=>[u*0.8+0,v*0.8])).concat( xform(HERSHEY(3404).polylines,(u,v)=>[u*0.8+8,v*0.8])).concat( [[[14,6],[15,5],[16,6],[15,7]]] ); symbols['pedal_on']=xform(p,(u,v)=>[u,v+3]); }{ p = []; for (let i = 0; i < 8; i++){ let a = i/8*Math.PI*2; p=p.concat(xform([ [[2,-2],[3,0],[7,-0.5],[9,-2],[11,0],[9,2],[7,0.5],[3,0],[2,2]] ],(u,v)=>rotate(u*0.8,v*0.8,a))); } symbols['pedal_off']=p; }{ p = xform(HERSHEY(2407).polylines,(u,v)=>[(u-5)*1.25,v/78+0.5]) p = xform(p,(u,v)=>{ return v<0.5?[u-2*(v/0.5)-2,v]:[u-2*(1-v)/0.5-2,v]; }) symbols['brace']=p; } })(); function scale_axis(x:number,y:number,sx:number,sy:number,th:number):[number,number]{ let u = x * Math.cos(th) - y * Math.sin(th); let v = x * Math.sin(th) + y * Math.cos(th); u *= sx; v *= sy; return [u * Math.cos(-th) - v * Math.sin(-th), u * Math.sin(-th) + v * Math.cos(-th)]; } function rotate(x:number,y:number,th:number):[number,number]{ let u = x * Math.cos(th) - y * Math.sin(th); let v = x * Math.sin(th) + y * Math.cos(th); return [u,v]; } function build_slur_bezier(elt:Element){ let {tag,x,y,w,h} = elt; elt.pts = []; elt.pts1 = []; let n = 20; let sh = 0;//elt.dir*8; let x0 = elt.x; let y0 = elt.y; let x3 = elt.x+elt.w; let y3 = elt.y1; let a = Math.atan2(y3-y0,x3-x0)+Math.PI/2*elt.dir; let hx = Math.cos(a)*h; let hy = Math.sin(a)*h; let m0x = x0 * 0.8 + x3 * 0.2; let m0y = y0 * 0.8 + y3 * 0.2; let m1x = x0 * 0.2 + x3 * 0.8; let m1y = y0 * 0.2 + y3 * 0.8; let x1a = m0x + hx; let y1a = m0y + hy; let x2a = m1x + hx; let y2a = m1y + hy; let x1b = elt.x+elt.w*0.2; let y1b = elt.y+elt.dir*h; let x2b = elt.x+elt.w*0.8; let y2b = elt.y1+elt.dir*h; let x1 = x1a*0.5 + x1b*0.5; let y1 = y1a*0.5 + y1b*0.5; let x2 = x2a*0.5 + x2b*0.5; let y2 = y2a*0.5 + y2b*0.5; y0 += sh; y1 += sh; y2 += sh; y3 += sh; elt.control = [[x0,y0],[x1,y1],[x2,y2],[x3,y3]]; let p : [number,number][] = []; for (let i = 0; i < n; i++){ let t = i/(n-1); elt.pts.push(cubic_bezier(x0,y0,x1,y1,x2,y2,x3,y3,t)); } p = [] for (let i = 2; i < n-2; i++){ let t = 1-i/(n-1); elt.pts1.push(cubic_bezier(x0,y0,x1,y1-elt.dir,x2,y2-elt.dir,x3,y3,t)); } } function build_cue(elt:Element){ let {tag,x,y,w,h} = elt; elt.pts = []; function push_all(p:[number,number][][]){ for (let i = 0; i < p.length; i++){ if (p[i].length<=1) continue; elt.pts.push(p[i]); } } if (elt.text == CUE.PEDAL_ON){ let p = symbols['pedal_on']; let scl = elt.h/24; push_all(xform(p,(u,v)=>[x+u*scl,y+v*scl+h/2])); }else if (elt.text == CUE.PEDAL_OFF){ let p = symbols['pedal_off']; let scl = elt.h/24; push_all(xform(p,(u,v)=>[x+u*scl,y+v*scl+h/2])); }else if ( elt.text == CUE.PIANISSISSIMO ||elt.text == CUE.PIANISSIMO ||elt.text == CUE.PIANO ||elt.text == CUE.MEZZO_PIANO ||elt.text == CUE.MEZZO_FORTE ||elt.text == CUE.FORTE ||elt.text == CUE.FORTISSIMO ||elt.text == CUE.FORTISSISSIMO ||elt.text == CUE.SFORZANDO ){ let v = get_text_width(elt.text,FONT.TRIPLEX_ITALIC); let scl = elt.h/30; let dx = -v/2*scl; for (let i = 0; i < elt.text.length; i++){ if (elt.text[i] == ' '){ dx += 10*scl; continue; } let a = ascii_map(elt.text[i],FONT.TRIPLEX_ITALIC); if (a === undefined){ continue; } let e = HERSHEY(a); push_all(xform(e.polylines,(u,v)=>[x+dx+(u-e.xmin)*scl,y+(v+14)*scl])); dx += (e.xmax-e.xmin-3)*scl; } }else{ let v = get_text_width(elt.text,FONT.DUPLEX_ITALIC); let scl = elt.h/40; let dx = 0; for (let i = 0; i < elt.text.length; i++){ if (elt.text[i] == ' '){ dx += 10*scl; continue; } let a = ascii_map(elt.text[i],FONT.DUPLEX_ITALIC); if (a === undefined){ continue; } let e = HERSHEY(a); push_all(xform(e.polylines,(u,v)=>[x+dx+(u-e.xmin)*scl,y+(v+18)*scl])); dx += (e.xmax-e.xmin)*scl; } } } export function bounding_box(p:[number,number][][]|[number,number][]):{x:number,y:number,w:number,h:number}{ let xmin = Infinity; let ymin = Infinity; let xmax = -Infinity; let ymax = -Infinity; for (let i = 0; i < p.length; i++){ if (Array.isArray(p[i][0])){ for (let j = 0; j < p[i].length; j++){ xmin = Math.min(xmin,p[i][j][0]); ymin = Math.min(ymin,p[i][j][1]); xmax = Math.max(xmax,p[i][j][0]); ymax = Math.max(ymax,p[i][j][1]); } }else{ xmin = Math.min(xmin,(p[i] as [number,number])[0]); ymin = Math.min(ymin,(p[i] as [number,number])[1]); xmax = Math.max(xmax,(p[i] as [number,number])[0]); ymax = Math.max(ymax,(p[i] as [number,number])[1]); } } // xmin -=1; // ymin -=1; // xmax +=1; // ymax +=1; return {x:xmin,y:ymin,w:xmax-xmin,h:ymax-ymin}; } function box_overlap(a:{x:number,y:number,w:number,h:number},b:{x:number,y:number,w:number,h:number}){ return ( a.x <= b.x + b.w && a.x + a.w>= b.x && a.y <= b.y + b.h && a.y + a.h >= b.y ) } function point_in_box(x,y,b:{x:number,y:number,w:number,h:number}){ // return b.x <= x && x <= (b.x+b.w) && b.y <= y && y <= (b.y+b.h); return b.x <= x && x <= (b.x+b.w) && b.y <= y && y <= (b.y+b.h); } export function cue_evade_slur(elements:Element[]){ let slurs : Element[] = []; let cues : Element[] = []; for (let i = 0; i < elements.length; i++){ if (elements[i].tag == 'cue'){ if (!elements[i].pts){ build_cue(elements[i]); } if (!elements[i].bbox){ elements[i].bbox = bounding_box(elements[i].pts); } cues.push(elements[i]) }else if (elements[i].tag == 'slur'){ if (!elements[i].pts){ build_slur_bezier(elements[i]); } if (!elements[i].bbox){ elements[i].bbox = bounding_box(elements[i].pts); } slurs.push(elements[i]); }else if (elements[i].tag == 'cresc'){ let {x,y,w,h,x1,y1,w1,h1} = elements[i] elements[i].bbox = bounding_box([[x,y],[x+w,y+h],[x1,y1],[x1+w1,y1+h1]]); cues.push(elements[i]) } } function resolve_(cue:Element,depth:number=5){ if (depth <= 0){ return; } for (let j = 0; j < slurs.length; j++){ if (box_overlap(cue.bbox, slurs[j].bbox)){ let hit = false; let dir : number = null; for (let k = 0; k < slurs[j].pts.length; k++){ if (point_in_box(slurs[j].pts[k][0],slurs[j].pts[k][1], cue.bbox)){ hit = true; dir = ((cue.bbox.y + cue.bbox.h/2) < (slurs[j].bbox.y + slurs[j].bbox.h/2))? -1 : 1; break; } } if (hit){ let d = dir*Math.min(4,Math.max(2,depth)); cue.y += d; cue.bbox.y += d; if (cue.y1 != undefined){ cue.y1 += d; } cue.pts = null; return resolve_(cue,depth-1); } } } } for (let i = 0; i < cues.length; i++){ resolve_(cues[i]); } } export function slur_evade_note(elements:Element[]){ let slurs : Element[] = []; let notes : Element[] = []; for (let i = 0; i < elements.length; i++){ if (elements[i].tag == 'note_head'){ let elt = elements[i]; let {x,y,w,h} = elt; x -= 1; y -= 1; w += 2; h += 2; if (!elt.bbox){ if (elt.stem_dir < 0){ if (elt.twisted){ elt.bbox = {x,y:y-h/2,w,h}; }else{ elt.bbox = {x:x-w,y:y-h/2,w,h}; } }else{ if (!elt.twisted){ elt.bbox = {x:x,y:y-h/2,w,h}; }else{ elt.bbox = {x:x-w,y:y-h/2,w,h}; } } } notes.push(elements[i]) }else if (elements[i].tag == 'slur'){ if (!elements[i].pts){ build_slur_bezier(elements[i]); } if (!elements[i].bbox){ elements[i].bbox = bounding_box(elements[i].pts); } slurs.push(elements[i]); } } function resolve_(slur:Element,depth:number=5){ if (depth <= 0){ return; } for (let j = 0; j < notes.length; j++){ if (box_overlap(slur.bbox, notes[j].bbox)){ let hit = false; let dir : number = slur.dir; for (let k = 0; k < slur.pts.length; k++){ if (point_in_box(slur.pts[k][0],slur.pts[k][1], notes[j].bbox)){ hit = true; break; } } if (hit){ let d = dir*Math.min(4,Math.max(2,depth)); slur.y += d; slur.y1 += d; slur.bbox.y += d; slur.pts.forEach((xy:[number,number]) => { xy[1] += d; }); slur.pts1.forEach((xy:[number,number]) => { xy[1] += d; }); return resolve_(slur,depth-1); } } } } for (let i = 0; i < slurs.length; i++){ if (slurs[i].adjacent){ continue; } resolve_(slurs[i]); } } export function hf_drawing_polylines(elements:Element[],width:number,height:number):number[][][]{ let polylines : [number,number][][] = []; function push_all(p:[number,number][][]){ for (let i = 0; i < p.length; i++){ if (p[i].length<=1) continue; polylines.push(p[i]); } } for (let i = 0; i < elements.length; i++){ let elt = elements[i]; let {tag,x,y,w,h} = elt; if (tag == 'note_head'){ let p : [number,number][][]; let key = (elt.stem_dir<0?'_up':'_down') + (elt.twisted?'_twist':''); if (elt.duration >= NOTE_LENGTH.WHOLE){ key = 'note_whole'+key; }else if (elt.duration >= NOTE_LENGTH.HALF){ key = 'note_half'+key; }else{ key = 'note_fill'+key; } p = symbols[key]; if (elt.mini) p = xform(p,(u,v)=>[u/2,v/2]); push_all(xform(p,(u,v)=>[x+u,y+v])); }else if (tag == 'dot'){ let p = symbols['dot']; if (elt.mini) p = xform(p,(u,v)=>[u/2,v/2]); push_all(xform(p,(u,v)=>[x+u,y+v])); }else if (tag == 'accidental'){ let p : [number,number][][]; if (elt.type == ACCIDENTAL.FLAT){ p = symbols['acc_flat']; }else if (elt.type == ACCIDENTAL.NATURAL){ p = symbols['acc_nat']; }else if (elt.type == ACCIDENTAL.SHARP){ p = symbols['acc_sharp']; } if (elt.mini) p = xform(p,(u,v)=>[u/2,v/2]); push_all(xform(p,(u,v)=>[x+u,y+v])); }else if (tag == 'clef'){ let p : [number,number][][]; if (elt.type == CLEF.TREBLE){ p = symbols['clef_g']; }else if (elt.type == CLEF.BASS){ p = symbols['clef_f']; }else{ p = symbols['clef_c']; } push_all(xform(p,(u,v)=>[x+u,y+v])); }else if (tag == 'rest'){ if (elt.duration == NOTE_LENGTH.WHOLE){ let p = symbols['rest_whole']; push_all(xform(p,(u,v)=>[x+u,y+v])); }else if (elt.duration == NOTE_LENGTH.HALF ){ let p = symbols['rest_half']; push_all(xform(p,(u,v)=>[x+u,y+v])); }else if (elt.duration == NOTE_LENGTH.QUARTER){ let p = symbols['rest_quarter']; push_all(xform(p,(u,v)=>[x+u,y+v])); }else if (elt.duration == NOTE_LENGTH.EIGHTH){ let p = symbols['rest_8']; push_all(xform(p,(u,v)=>[x+u,y+v])); }else if (elt.duration == NOTE_LENGTH.SIXTEENTH){ let p = symbols['rest_16']; push_all(xform(p,(u,v)=>[x+u,y+v])); }else if (elt.duration == NOTE_LENGTH.THIRTYSECOND){ let p = symbols['rest_32']; push_all(xform(p,(u,v)=>[x+u,y+v])); }else if (elt.duration == NOTE_LENGTH.SIXTYFOURTH){ let p = symbols['rest_64']; push_all(xform(p,(u,v)=>[x+u,y+v])); } }else if (tag == 'flag'){ if (elt.stem_dir < 0){ let p = elt.is_last? symbols['flag_up']:symbols['flag_mid_up']; if (elt.mini) p = xform(p,(u,v)=>[u/2,v/2]); push_all(xform(p,(u,v)=>[x+u,y+v])); }else{ let p = elt.is_last? symbols['flag_down']:symbols['flag_mid_down']; if (elt.mini) p = xform(p,(u,v)=>[u/2,v/2]); push_all(xform(p,(u,v)=>[x+u,y+v])); } }else if (tag == 'beam'){ for (let j = 0.3; j < 4.66; j+=1.09){ polylines.push([[x,y-j*elt.stem_dir],[x+w,y+h-j*elt.stem_dir]]); } }else if (tag == 'line'){ polylines.push([[x,y],[x+w,y+h]]); }else if (tag == 'cresc'){ // {let p = [[elt.bbox.x,elt.bbox.y],[elt.bbox.x+elt.bbox.w,elt.bbox.y],[elt.bbox.x+elt.bbox.w,elt.bbox.y+elt.bbox.h],[elt.bbox.x,elt.bbox.y+elt.bbox.h]]; polylines.push(p as any);} let p : [number,number][][] = [ [[x,y],[x+w,y+h]], [[elt.x1,elt.y1],[elt.x1+elt.w1,elt.y1+elt.h1]] ]; push_all(p); }else if (tag == 'slur'){ // let p = [[elt.bbox.x,elt.bbox.y],[elt.bbox.x+elt.bbox.w,elt.bbox.y],[elt.bbox.x+elt.bbox.w,elt.bbox.y+elt.bbox.h],[elt.bbox.x,elt.bbox.y+elt.bbox.h]]; polylines.push(p as any); if (!elt.pts){ build_slur_bezier(elt); } polylines.push(elt.pts); polylines.push(elt.pts1); // polylines.push(elt.control); }else if (tag == 'timesig_digit'){ let p = symbols['timesig_digit_'+elt.value]; push_all(xform(p,(u,v)=>[x+u,y+v])); }else if (tag == 'timesig_c'){ // polylines.push([[x-w/2,y-h/2],[x+w/2,y-h/2],[x+w/2,y+h/2],[x-w/2,y+h/2]]); let p = symbols['timesig_c']; push_all(xform(p,(u,v)=>[x+u,y+v])); if (elt.type == 'cut'){ polylines.push([[x,y-14],[x,y+14]]); } }else if (tag == 'tuplet_label'){ let digits : string[] = elt.label.toString().split(''); let mid = x+w/2; let mw = digits.length; let dw = 8; let dp = 4; let ml = mid-mw/2*dw-dp; let mr = mid+mw/2*dw+dp; if (ml >= x && mr <= x+w){ // polylines.push([[x,y],[x,y+h],[x+w,y+h],[x+w,y]]); polylines.push([[x,y],[x,y+h],[ml,y+h]]); polylines.push([[mr,y+h],[x+w,y+h],[x+w,y]]); } for (let i = 0; i < digits.length; i++){ // polylines.push([[ml+dp+dw*i,y+h-i*10],[ml+dp+dw*i+dw,y+h-i*10]]); let p = symbols['tuplet_digit_'+digits[i]]; push_all(xform(p,(u,v)=>[ml+dp+dw*i+u+4,y+h+v])); } }else if (tag == 'lyric'){ let scl = w/get_text_width(elt.text); let dx = -4*scl; for (let i = 0; i < elt.text.length; i++){ if (elt.text[i] == ' '){ dx += 10*scl; continue; } let a = ascii_map(elt.text[i]); if (a === undefined){ continue; } let e = HERSHEY(a); // console.log(e.ymin,e.ymax); push_all(xform(e.polylines,(u,v)=>[x+dx+(u-e.xmin)*scl,y+(v+12)*scl])); dx += (e.xmax-e.xmin)*scl; } }else if (tag == 'bold_text'){ let scl = w/get_text_width(elt.text,FONT.TRIPLEX,-2); if (isNaN(scl)) scl = 1; let dx = 0; for (let i = 0; i < elt.text.length; i++){ if (elt.text[i] == ' '){ dx += 10*scl; continue; } let a = ascii_map(elt.text[i],FONT.TRIPLEX); if (a === undefined){ continue; } let e = HERSHEY(a); push_all(xform(e.polylines,(u,v)=>[x+dx+(u-e.xmin)*scl,y+(v+12)*scl])); dx += (e.xmax-e.xmin-2)*scl; } }else if (tag == 'regular_text'){ let scl = w/get_text_width(elt.text,FONT.DUPLEX,-2); if (isNaN(scl)) scl = 1; let dx = 0; for (let i = 0; i < elt.text.length; i++){ if (elt.text[i] == ' '){ dx += 10*scl; continue; } let a = ascii_map(elt.text[i],FONT.DUPLEX); if (a === undefined){ continue; } let e = HERSHEY(a); push_all(xform(e.polylines,(u,v)=>[x+dx+(u-e.xmin)*scl,y+(v+12)*scl])); dx += (e.xmax-e.xmin-2)*scl; } }else if (tag == 'bracket'){ if (elt.type == BRACKET.BRACE){ let p = symbols['brace']; push_all(xform(p,(u,v)=>[x+u,y+v*h])); }else if (elt.type == BRACKET.BRACKET){ polylines.push([[x+5,y-12],[x-2,y-8],[x-8,y-7],[x-8,y+h+7],[x-2,y+h+8],[x+5,y+h+12]]); polylines.push([[x+5,y-12],[x-1,y-8],[x-7,y-6],[x-7,y+h+6],[x-1,y+h+8],[x+5,y+h+12]]); polylines.push([ [x-6,y-5],[x-6,y+h+5]]); } }else if (tag == 'articulation'){ let a = Math.abs(elt.type); if (a == ARTICULATION.STACCATO){ let p = symbols['dot']; push_all(xform(p,(u,v)=>[x+u,y+v])); }else if (a == ARTICULATION.ACCENT){ let p : [number,number][] = [[x-5,y-3],[x+5,y],[x-5,y+3]]; polylines.push(p); }else if (a == ARTICULATION.SPICCATO){ let p : [number,number][] = [[x-1,y-3],[x,y+3],[x+1,y-3],[x-1,y-3]] polylines.push(p); }else if (a == ARTICULATION.TENUTO){ let p : [number,number][] = [[x-4,y],[x+4,y]] polylines.push(p); }else if (a == ARTICULATION.MARCATO){ let p : [number,number][] = [[x-3,y+3],[x,y-3],[x+3,y+3]] polylines.push(p); }else if (a == ARTICULATION.UP_BOW){ let p : [number,number][] = [[x-3,y-3],[x,y+3],[x+3,y-3]] polylines.push(p); }else if (a == ARTICULATION.TREMBLEMENT){ let p : [number,number][][] = [ [[x-4,y],[x+4,y]], [[x,y-4],[x,y+4]], ] push_all(p); }else if (a == ARTICULATION.FERMATA){ let p = symbols['fermata']; push_all(xform(p,(u,v)=>[x+u,y+v*elt.dir])); }else if (a == ARTICULATION.MORDENT){ let p = symbols['mordent']; push_all(xform(p,(u,v)=>[x+u,y+v])); }else if (a == ARTICULATION.TURN){ let p = symbols['turn']; push_all(xform(p,(u,v)=>[x+u,y+v])); }else if (a == ARTICULATION.TRILL){ let p = symbols['trill']; push_all(xform(p,(u,v)=>[x+u,y+v])); }else if (a == ARTICULATION.FLAGEOLET){ let p = symbols['flageolet']; push_all(xform(p,(u,v)=>[x+u,y+v])); }else{ let p = HERSHEY(ascii_map(elt.type.toString(),FONT.TRIPLEX)).polylines; push_all(xform(p,(u,v)=>[x+u/2,y+v/2])); } if (elt.type < 0){ let p : [number,number][] = [[x,y-5],[x,y+5]]; polylines.push(p); } }else if (tag == 'squiggle'){ let p : [number,number][] = []; let q : [number,number][][] = []; let f = false; let h2 = Math.ceil(h/8)*8; let y2 = y - (h2-h)/2; for (let i = 0; i < h2; i += 4){ p.push([f?(x+2):(x-2),y2+i]); if (f && i + 4 < h2){ q.push([[x+2.8,i+y2+0.8],[x-1.2,i+y2+4.8]]); } f = !f; } polylines.push(p); push_all(q); }else if (tag == 'cue'){ // let p = [[elt.bbox.x,elt.bbox.y],[elt.bbox.x+elt.bbox.w,elt.bbox.y],[elt.bbox.x+elt.bbox.w,elt.bbox.y+elt.bbox.h],[elt.bbox.x,elt.bbox.y+elt.bbox.h]]; polylines.push(p as any); // let p = [[x-10,y],[x+10,y],[x+10,y+h],[x-10,y+h]]; polylines.push(p as any); // let p = [[x,y],[x+w,y],[x+w,y+h],[x,y+h]]; polylines.push(p as any); if (!elt.pts){ build_cue(elt); } push_all(elt.pts); } } return polylines; } export function round_polylines(polylines:number[][][],accuracy:number=2){ let n = Math.pow(10,accuracy); for (let i = 0; i < polylines.length; i++){ for (let j = 0; j <polylines[i].length; j++){ let [x,y] = polylines[i][j]; x = Math.round(x * n)/n; y = Math.round(y * n)/n; polylines[i][j][0] = x; polylines[i][j][1] = y; } } } export function export_svg(dr: Drawing, {background="white"} : {background?:string}={}): string{ let o : string = `<svg xmlns="http://www.w3.org/2000/svg" width="${dr.w}" height="${dr.h}">`; if (background){ o += `<rect x="0" y="0" width="${dr.w}" height="${dr.h}" fill="${background}"></rect>`; } o += `<path stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none" d="`; for (let i = 0; i < dr.polylines.length; i++){ o += 'M '; for (let j = 0; j < dr.polylines[i].length; j++){ o += dr.polylines[i][j] + ' '; } } o += `"/>`; o += `</svg>`; return o; } export function export_animated_svg(dr:Drawing,{background="white",speed=0.001} : {background?:string, speed?:number}={}): string{ let width = dr.w; let height = dr.h; let polylines = dr.polylines; let o : string = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">`; if (background){ o += `<rect x="0" y="0" width="${dr.w}" height="${dr.h}" fill="${background}"></rect>`; } let lengths : number[] = []; let acc_lengths : number[] = []; let total_l = 0; for (let i = 0; i < polylines.length; i++){ let l = 0; for (let j = 1; j < polylines[i].length; j++){ l += Math.hypot( polylines[i][j-1][0]-polylines[i][j][0], polylines[i][j-1][1]-polylines[i][j][1] ); } lengths.push(l); acc_lengths.push(total_l); total_l+=l; } for (let i = 0; i < polylines.length; i++){ let l = lengths[i]; o += ` <path stroke="black" stroke-width="1.5" fill="none" stroke-dasharray="${l}" stroke-dashoffset="${l}" d="M`; for (let j = 0; j < polylines[i].length; j++){ o += polylines[i][j] + ' '; } let t = speed*l; o += `"> <animate id="a${i}" attributeName="stroke-dashoffset" fill="freeze" from="${l}" to="${0}" dur="${t}s" begin="${(acc_lengths[i])*speed}s;a${i}.end+${1+speed*total_l}s"/> /> <animate id="b${i}" attributeName="stroke-dashoffset" fill="freeze" from="${0}" to="${l}" dur="${1}s" begin="${speed*total_l}s;b${i}.end+${speed*total_l}s"/> /> </path>`; } //begin="${i}s;a${i}.end+${polylines.length-i}s" /> o += `</svg>`; return o; } export function export_pdf(dr:Drawing):string { let width = dr.w; let height = dr.h; let polylines = dr.polylines; var head = `%PDF-1.1\n%%¥±ë\n1 0 obj\n<< /Type /Catalog\n/Pages 2 0 R\n>>endobj 2 0 obj\n<< /Type /Pages\n/Kids [3 0 R]\n/Count 1\n/MediaBox [0 0 ${width} ${height}]\n>>\nendobj 3 0 obj\n<< /Type /Page\n/Parent 2 0 R\n/Resources\n<< /Font\n<< /F1\n<< /Type /Font /Subtype /Type1\n/BaseFont /Times-Roman\n>>\n>>\n>>\n/Contents [`; var pdf = ""; var count = 4; for (var i = 0; i < polylines.length; i++) { pdf += `${count} 0 obj \n<< /Length 0 >>\n stream\n 1 j 1 J 1.5 w\n`; for (var j = 0; j < polylines[i].length; j++){ var [x,y] = polylines[i][j]; pdf += `${x} ${height-y} ${j?'l':'m'} `; } pdf += "\nS\nendstream\nendobj\n"; head += `${count} 0 R `; count ++; } head += "]\n>>\nendobj\n"; pdf += "\ntrailer\n<< /Root 1 0 R \n /Size 0\n >>startxref\n\n%%EOF\n"; return head+pdf; } function xiaolinwu(data:number[],w:number,h:number,x0:number,y0:number,x1:number,y1:number){ //https://en.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorithm function plot(x:number, y:number, c:number){ data[y*w+x]=1-(1-data[y*w+x])*(1-c); } function ipart (x:number){return Math.floor(x)} function round (x:number){return ipart(x + 0.5)} function fpart (x:number){return x - Math.floor(x)} function rfpart(x:number){return 1 - fpart(x)} function drawline(x0:number,y0:number,x1:number,y1:number){ let steep = Math.abs(y1 - y0) > Math.abs(x1 - x0); if (steep){ [x0,y0] = [y0,x0]; [x1,y1] = [y1,x1]; } if (x0 > x1){ [x0,x1] = [x1,x0]; [y0,y1] = [y1,y0]; } let dx = x1 - x0; let dy = y1 - y0; let gradient = dy / dx; if (dx == 0.0){ gradient = 1.0; } let xend = round(x0); let yend = y0 + gradient * (xend - x0); let xgap = rfpart(x0 + 0.5); let xpxl1 = xend; let ypxl1 = ipart(yend); if (steep){ plot(ypxl1, xpxl1, rfpart(yend) * xgap); plot(ypxl1+1, xpxl1, fpart(yend) * xgap); }else{ plot(xpxl1, ypxl1 , rfpart(yend) * xgap); plot(xpxl1, ypxl1+1, fpart(yend) * xgap); } let intery = yend + gradient; xend = round(x1); yend = y1 + gradient * (xend - x1); xgap = fpart(x1 + 0.5); let xpxl2 = xend; let ypxl2 = ipart(yend); if (steep){ plot(ypxl2 , xpxl2, rfpart(yend) * xgap); plot(ypxl2+1, xpxl2, fpart(yend) * xgap); }else{ plot(xpxl2, ypxl2, rfpart(yend) * xgap); plot(xpxl2, ypxl2+1, fpart(yend) * xgap); } if (steep){ for (let x = xpxl1+1; x <= xpxl2-1; x++){ plot(ipart(intery) , x, rfpart(intery)); plot(ipart(intery)+1, x, fpart(intery)); intery = intery + gradient; } }else{ for (let x = xpxl1 +1; x<= xpxl2-1; x++){ plot(x, ipart(intery), rfpart(intery)); plot(x, ipart(intery)+1, fpart(intery)); intery = intery + gradient; } } } drawline(x0,y0,x1,y1); } function encode_gif(data:number[],w:number,h:number){ let bytes = []; bytes.push(0x47,0x49,0x46,0x38,0x39,0x61); bytes.push(w&0xff); bytes.push((w>>8)&0xff); bytes.push(h&0xff); bytes.push((h>>8)&0xff); bytes.push(0xf6); bytes.push(0,0); for (let i = 0; i < 127; i++){ bytes.push(i*2,i*2,i*2); } bytes.push(0xff,0xff,0xff); bytes.push(0x2c,0,0,0,0); bytes.push(w&0xff); bytes.push((w>>8)&0xff); bytes.push(h&0xff); bytes.push((h>>8)&0xff); bytes.push(0,7); let n = ~~(w*h/126); let inc = n*126; let exc = w*h-inc; for (let i = 0; i < n; i++){ bytes.push(0x7f); bytes.push(0x80); for (let j = 0; j < 126; j++){ bytes.push(~~(data[i*126+j]*127)); } } if (exc){ bytes.push(exc+1); bytes.push(0x80); for (let i = 0; i < exc; i++){ bytes.push(~~(data[inc+i]*127)); } } bytes.push(0x01,0x81,0x00,0x3B); return bytes; } export function export_gif(dr:Drawing,{scale=1.0,iter=2} : {scale?:number,iter?:number}={}):number[] { let scl = 1/scale; let w = ~~(dr.w/scl); let h = ~~(dr.h/scl); let polylines = dr.polylines; // console.log(w,h); let data = new Array(w*h).fill(0); for (var i = 0; i < polylines.length; i++) { // console.log(polylines[i]) for (var j = 0; j < polylines[i].length-1; j++){ let x0 = polylines[i][j][0]/scl; let y0 = polylines[i][j][1]/scl; let x1 = polylines[i][j+1][0]/scl; let y1 = polylines[i][j+1][1]/scl; for (let k = 0; k < iter; k++) xiaolinwu(data,w,h,x0,y0,x1,y1); } } for (let i = 0; i < data.length; i++){ data[i] = 1-data[i]; } // console.log(data); let bytes = encode_gif(data,w,h); return bytes; }
the_stack
import * as async from "../async" import * as path from "path" import * as crypto from "crypto" import { Dictionary } from "../dictionary" import { PuppetASTParser, PuppetASTClass, PuppetASTFunction, Resolver, PuppetASTDefinedType, PuppetASTEnvironment, PuppetASTResource, HieraSourceResolveCallback, ResolvedFunction, PuppetASTContainerContext, PuppetASTObject, EncryptedVariable } from "./ast" import { GlobalVariableResolver, GlobalVariableResolverResults, CompilationError } from "./util" import { Environment } from "./environment" import { CompiledHierarchy, EYamlKeyPair, EYaml } from "./hiera" import { ClassDump, ResourceDump, NodeDump, ClassInfoDump, DefiledTypeInfoDump, NodeDefinedTypeDump } from "../ipc/objects" import { rubyBridge } from "../global" import { CERTIFICATE_EXTENSIONS } from "./cert" import { isString } from "util"; const parseDomain = require('domain-name-parser'); const ENC_PATTERN = /ENC\[\s*([A-Z0-9]+)\s*,\s*(.+)\s*\]/; class NodeContextResolver implements Resolver { private context: NodeContext; private global: GlobalVariableResolver; constructor (context: NodeContext, global: GlobalVariableResolver) { this.context = context; this.global = global; } public getNodeName(): string { return this.context.name; } public resolveDefinedType(definedTypeName: string, public_: boolean): Promise<PuppetASTDefinedType> { return this.context.resolveDefinedType(definedTypeName, this.global, public_); } public resolveClass(className: string, public_: boolean): Promise<PuppetASTClass> { return this.context.resolveClass(className, this.global, public_); } public resolveFunction(context: PuppetASTContainerContext, resolver: Resolver, name: string): Promise<ResolvedFunction> { return this.context.resolveFunction(context, resolver, name, this.global); } public async resolveHieraSource(kind: string, key: string, resolve: HieraSourceResolveCallback): Promise<void> { await this.context.registerHieraSource(kind, key, resolve); } public registerResource(resource: PuppetASTResource): void { this.context.registerResource(resource); } public getGlobalVariable(name: string): any { return this.global.get(name); } /* This method should return: GlobalVariableResolverResults.MISSING when global cannot be found GlobalVariableResolverResults.EXISTS when it exists but hierarchy is unknown 0 and above then it exists with hierarchy as value */ public hasGlobalVariable(name: string): number { return this.global.has(name); } } export class NodeContext { public readonly name: string; public readonly env: Environment; public readonly ast: PuppetASTEnvironment; private _facts: any; private _trusted_facts: any; private _hierarchy: CompiledHierarchy; private readonly _compiledClasses: Dictionary<string, PuppetASTClass>; private readonly _compiledFunctions: Dictionary<string, ResolvedFunction>; private readonly _compiledDefinedTypes: Dictionary<string, PuppetASTDefinedType>; private readonly _registeredResources: Dictionary<string, Dictionary<string, PuppetASTResource>>; private readonly _hieraIncludes: Dictionary<string, [number, HieraSourceResolveCallback]>; private readonly _hieraResources: Dictionary<string, [number, HieraSourceResolveCallback]>; private readonly _extensions: { [key: string]: string }; constructor (certname: string, env: Environment) { this.name = certname; this.env = env; this._extensions = {}; this._facts = {}; this._compiledClasses = new Dictionary(); this._compiledDefinedTypes = new Dictionary(); this._registeredResources = new Dictionary(); this._compiledFunctions = new Dictionary(); this._hieraIncludes = new Dictionary(); this._hieraResources = new Dictionary(); this.ast = new PuppetASTEnvironment(env.name); const d = parseDomain(certname); this._trusted_facts = { "authenticated": "local", "certname": certname, "domain": d.domain, "hostname": d.host, "extensions": this._extensions }; } public get facts() { return this._facts; } public get rootFacts(): any { return { "facts": this._facts, "trusted": this._trusted_facts } } public compilePropertyPath(className: string, propertyName: string): string { return className + "::" + propertyName; } public async hasClassProperty(className: string, propertyName: string): Promise<boolean> { const classInfo = this.env.findClassInfo(className); if (classInfo == null) return false; const compiled = await this.acquireClass(className, false); if (!compiled) return false; const propertyPath = this.compilePropertyPath(className, propertyName); return this.hasGlobal(propertyPath) >= 0; } public async removeProperty(hierarchy: number, property: string): Promise<any> { const hierarchyEntry = this.hierarchy.get(hierarchy); if (hierarchyEntry == null) return; const file = hierarchyEntry.file; if (file == null) return; delete file.config[property]; await file.save(); } public async removeClassProperty(className: string, hierarchy: number, propertyName: string): Promise<any> { const classInfo = this.env.findClassInfo(className); if (classInfo == null) return; const compiled = await this.acquireClass(className); if (!compiled) return; const hierarchyEntry = this.hierarchy.get(hierarchy); if (hierarchyEntry == null) return; const propertyPath = this.compilePropertyPath(className, propertyName); const file = hierarchyEntry.file; if (file == null) return; delete file.config[propertyPath]; await file.save(); } public async dumpClass(className: string): Promise<ClassDump> { const classInfo = this.env.findClassInfo(className); if (classInfo == null) return null; const compiled = await this.acquireClass(className, true); const types: any = {}; const errors: any = {}; const hints: any = {}; const fields: string[] = []; const requiredFields: string[] = []; const encrypted: string[] = []; const values: any = {}; const modified: any = {}; const classHints: any = compiled.hints; for (const name of compiled.resolvedFields.getKeys()) { const property = compiled.getResolvedProperty(name); fields.push(name); if (classInfo.defaults.indexOf(name) < 0) { requiredFields.push(name); } if (property.hasType) { types[name] = { "type": property.type.constructor.name, "data": property.type }; } if (property.hasValue) { values[name] = property.value; if (property.value instanceof EncryptedVariable) { encrypted.push(name); } } if (property.hasError) { errors[name] = { message: property.error.message, stack: property.error.stack }; } if (property.hasHints) { hints[name] = property.hints; } modified[name] = property.hierarchy; } return { "icon": classInfo.options.icon, "values": values, "classInfo": classInfo.dump(), "modified": modified, "types": types, "errors": errors, "propertyHints": hints, "hints": classHints, "fields": fields, "encrypted": encrypted, "requiredFields": requiredFields, "hierarchy": this.hierarchy.dump() } } public registerResource(resource: PuppetASTResource): void { const definedTypeName = resource.definedType.name; let titles = this._registeredResources.get(definedTypeName); if (titles == null) { titles = new Dictionary(); this._registeredResources.put(definedTypeName, titles); } titles.put(resource.getTitle(), resource); } public async dumpResource(definedTypeName: string, title: string): Promise<ResourceDump> { const definedTypeInfo = this.env.findDefineTypeInfo(definedTypeName); if (definedTypeInfo == null) return null; if (!this._registeredResources.has(definedTypeName)) return null; const titles = this._registeredResources.get(definedTypeName); if (!titles.has(title)) return null; const compiled = titles.get(title); const defaultValues: any = {}; const types: any = {}; const fields: string[] = []; const modified: any = {}; const requiredFields: string[] = []; const errors: any = {}; const hints: any = {}; const values: any = {}; const options: any = {}; for (const name of compiled.resolvedFields.getKeys()) { const property = compiled.resolvedFields.get(name); if (definedTypeInfo.defaults.indexOf(name) < 0) { requiredFields.push(name); } if (property.hasType) { types[name] = { "type": property.type.constructor.name, "data": property.type }; } if (property.hasError) { errors[name] = { message: property.error.message, stack: property.error.stack }; } if (property.hasValue) { values[name] = property.value; }; if (property.hasHints) { hints[name] = property.hints; } if (property.hasValue) { defaultValues[name] = property.value; } modified[name] = property.hierarchy; fields.push(name); } for (const option of compiled.options) { options[option] = compiled.getOption(option); } return { "icon": definedTypeInfo.options.icon, "values": values, "definedTypeInfo": definedTypeInfo.dump(), "types": types, "errors": errors, "options": options, "hierarchyLevel": compiled.hierarchy, "encrypted": [], "propertyHints": hints, "fields": fields, "modified": modified, "hints": hints, "requiredFields": requiredFields, "hierarchy": this.hierarchy.dump() } } public async setResourceProperty(definedTypeName: string, title: string, hierarchy: number, key: string, propertyName: string, value: any): Promise<any> { if (propertyName == "title") return; const hierarchyEntry = this.hierarchy.get(hierarchy); if (hierarchyEntry == null) return; let file = hierarchyEntry.file; if (file == null) { file = await hierarchyEntry.create(this.env, this._hierarchy.source); } let config = file.config[key]; if (config == null) { config = {}; file.config[key] = config; } const d = config[definedTypeName]; if (d[title] == null) d[title] = {}; const t = d[title]; t[propertyName] = value; await file.save(); await this.invalidateResources(key); } public async removeResourceProperty(definedTypeName: string, title: string, hierarchy: number, key: string, propertyName: string): Promise<any> { const hierarchyEntry = this.hierarchy.get(hierarchy); if (hierarchyEntry == null) return; const file = hierarchyEntry.file; if (file == null) return; const config = file.config[key]; if (config == null) return; const d = config[definedTypeName]; if (d == null) return; const t = d[title]; if (t == null) return; delete t[propertyName]; await file.save(); await this.invalidateResources(key); } public async encryptNodeProperty(hierarchy: number, className: string, propertyName: string): Promise<boolean> { const hierarchyEntry = this.hierarchy.get(hierarchy); if (hierarchyEntry == null) return; const file = hierarchyEntry.file; if (file == null) return false; const eyaml = hierarchyEntry.eyaml; if (eyaml == null) return false; const publicKey = this.env.workspace.getEYamlPublicKey(eyaml); if (publicKey == null) return false; const propertyPath = this.compilePropertyPath(className, propertyName); if (!file.config.hasOwnProperty(propertyPath)) return false; const oldValue = file.config[propertyPath]; let encrypted; try { encrypted = eyaml.encrypt(oldValue, publicKey); } catch (e) { return false; } file.config[propertyPath] = encrypted await file.save(); return true; } public async setProperty(hierarchy: number, property: string, value: any): Promise<any> { const hierarchyEntry = this.hierarchy.get(hierarchy); if (hierarchyEntry == null) return; let file = hierarchyEntry.file; if (file == null) { file = await hierarchyEntry.create(this.env, this._hierarchy.source); } file.config[property] = value; await file.save(); } public async setClassProperty(className: string, hierarchy: number, propertyName: string, value: any): Promise<any> { const classInfo = this.env.findClassInfo(className); if (classInfo == null) return; const compiled = await this.acquireClass(className); if (!compiled) return; const hierarchyEntry = this.hierarchy.get(hierarchy); if (hierarchyEntry == null) return; let file = hierarchyEntry.file; if (file == null) { file = await hierarchyEntry.create(this.env, this._hierarchy.source); } const propertyPath = this.compilePropertyPath(className, propertyName); file.config[propertyPath] = value; await file.save(); } public async invalidateClass(className: string): Promise<void> { if (this._compiledClasses.has(className)) { const compiled = this._compiledClasses.get(className); this._compiledClasses.remove(className); // invalidate also a direct parent, if any if (compiled.parentName != null) { await this.invalidateClass(compiled.parentName); } } } public async invalidateResources(hieraResourceName: string): Promise<void> { const resouces = this._hieraResources.get(hieraResourceName); if (resouces == null) return; const [hierarchy, resolve] = resouces; // resolve again resouces[0] = await resolve(); } public async isResourceValid(definedTypeName: string, title: string): Promise<boolean> { if (this._registeredResources.has(definedTypeName)) { const titles = this._registeredResources.get(definedTypeName); return titles.has(title); } return false; } public async invalidate(): Promise<void> { this._compiledClasses.clear(); this._compiledDefinedTypes.clear(); } public async dump(): Promise<NodeDump> { const classes: { [key:string]: ClassInfoDump } = {}; const resources: { [key:string]: NodeDefinedTypeDump } = {}; const hierarchy = []; for (const clazz of this._compiledClasses.getValues()) { if (!clazz.isPublic()) continue; const classInfo = this.env.findClassInfo(clazz.name); if (classInfo == null) continue; const dump = classInfo.dump(); const options: any = dump["options"]; for (const key of clazz.options) { options[key] = clazz.getOption(key); } classes[clazz.name] = dump; } for (const definedTypeName of this._registeredResources.getKeys()) { const definedTypeInfo = this.env.findDefineTypeInfo(definedTypeName); if (definedTypeInfo == null) continue; const dump = definedTypeInfo.dump(); const titles: any = {}; const res: NodeDefinedTypeDump = { definedType: dump, titles: titles }; resources[definedTypeName] = res; const titles_ = this._registeredResources.get(definedTypeName); for (const title of titles_.getKeys()) { const resource = titles_.get(title); const options: any = {}; for (const key of resource.options) { options[key] = resource.getOption(key); } titles[title] = { "options": options }; } } for (const entry of this._hierarchy.hierarhy) { hierarchy.push(entry.dump()); } const hiera_includes: {[key: string]: number} = {}; const hiera_resources: {[key: string]: number} = {}; for (const key of this._hieraIncludes.getKeys()) { const [hierarchy, resolve] = this._hieraIncludes.get(key); hiera_includes[key] = hierarchy; } for (const key of this._hieraResources.getKeys()) { const [hierarchy, resolve] = this._hieraResources.get(key); hiera_resources[key] = hierarchy; } return { classes: classes, resources: resources, hierarchy: hierarchy, hiera_includes: hiera_includes, hiera_resources: hiera_resources }; } public async isClassValid(className: string): Promise<boolean> { return this._compiledClasses.has(className); } public get hierarchy() { return this._hierarchy; } public setFacts(facts: any) { this._facts = facts; } public async assignClass(key: string, className: string, hierarchy: number): Promise<void> { const entry = this.hierarchy.get(hierarchy); let file = entry.file; if (file == null) { file = await entry.create(this.env, this.hierarchy.source); } let classes = file.config[key]; if (classes == null) { classes = []; file.config[key] = classes; } if (classes.indexOf(className) >= 0) return; classes.push(className); await file.save(); } public async createResource(key: string, hierarchy: number, definedTypeName: string, title: string): Promise<boolean> { const entry = this.hierarchy.get(hierarchy); let file = entry.file; if (file == null) { file = await entry.create(this.env, this.hierarchy.source); } let resources = file.config[key]; if (resources == null) { resources = {}; file.config[key] = resources; } let definedType = resources[definedTypeName]; if (definedType == null) { definedType = {} resources[definedTypeName] = definedType; } definedType[title] = {}; await file.save(); return true; } public async removeClass(key: string, className: string, hierarchy: number): Promise<void> { const entry = this.hierarchy.get(hierarchy); let file = entry.file; if (file == null) return; let classes = file.config[key]; if (classes == null) return; const index = classes.indexOf(className); if (index < 0) return; classes.splice(index, 1); await file.save(); } public async removeResource(key: string, hierarchy: number, definedTypeName: string, title: string): Promise<boolean> { const entry = this.hierarchy.get(hierarchy); let file = entry.file; if (file == null) return false; const resources = file.config[key]; if (resources == null) return false; const definedType = resources[definedTypeName]; if (definedType == null) return false; if (!definedType.hasOwnProperty(title)) return false; delete definedType[title]; await file.save(); return true; } public async removeResources(key: string, hierarchy: number, definedTypeName: string): Promise<boolean> { const entry = this.hierarchy.get(hierarchy); let file = entry.file; if (file == null) return false; const resources = file.config[key]; if (resources == null) return false; if (!resources.hasOwnProperty(definedTypeName)) return false; delete resources[definedTypeName]; await file.save(); return true; } public async removeAllResources(key: string, hierarchy: number) { const entry = this.hierarchy.get(hierarchy); let file = entry.file; if (file == null) return false; const resources = file.config[key]; if (resources == null) return false; delete file.config[key]; await file.save(); return true; } public async renameResource(key: string, hierarchy: number, definedTypeName: string, title: string, newTitle: string) { const entry = this.hierarchy.get(hierarchy); let file = entry.file; if (file == null) return false; const resources = file.config[key]; if (resources == null) return false; const definedType = resources[definedTypeName]; if (definedType == null) return false; if (!definedType.hasOwnProperty(title)) return false; const moveTo = definedType[title]; delete definedType[title]; definedType[newTitle] = moveTo; await file.save(); return true; } /* This method should return: GlobalVariableResolverResults.MISSING when global cannot be found GlobalVariableResolverResults.EXISTS when it exists but hierarchy is unknown 0 and above then it exists with hierarchy as value */ public hasGlobal(key: string): number { switch (key) { case "facts": case "environment": case "trusted": { return GlobalVariableResolverResults.EXISTS; } } if (this._trusted_facts.hasOwnProperty(key)) return GlobalVariableResolverResults.EXISTS; if (this._facts.hasOwnProperty(key)) return GlobalVariableResolverResults.EXISTS; if (this.env.global.has(key) || this.env.workspace.global.has(key)) return GlobalVariableResolverResults.EXISTS; for (let hierarchyLevel = 0, t = this._hierarchy.hierarhy.length; hierarchyLevel < t; hierarchyLevel++) { const e = this._hierarchy.hierarhy[hierarchyLevel]; const f = e.file; if (f == null) continue; if (f.has(key)) return hierarchyLevel; } return GlobalVariableResolverResults.MISSING; } public getGlobal(key: string): any { switch (key) { case "facts": { return this._facts; } case "trusted": { return this._trusted_facts; } case "environment": { return this.env.name; } } if (this._trusted_facts.hasOwnProperty(key)) return this._trusted_facts[key]; if (this._facts.hasOwnProperty(key)) return this._facts[key]; if (this.env.global.has(key)) return this.env.global.get(key); if (this.env.workspace.global.has(key)) return this.env.workspace.global.get(key); for (const e of this._hierarchy.hierarhy) { const f = e.file; if (f == null) continue; if (f.has(key)) { const value = f.get(key); if (isString(value)) { const m = value.match(ENC_PATTERN); if (m != null) { const kind = m[1]; const data = m[2]; return new EncryptedVariable(value, data, kind); } } return value; }; } return null; } public async registerHieraSource(kind: string, key: string, resolve: HieraSourceResolveCallback): Promise<void> { const hierarchy = await resolve(); switch (kind) { case "hiera_include": { this._hieraIncludes.put(key, [hierarchy, resolve]); break; } case "hiera_resources": { this._hieraResources.put(key, [hierarchy, resolve]); break; } } } public async acquireClass(className: string, public_: boolean = true): Promise<PuppetASTClass> { const zis = this; return await this.resolveClass(className, { get: (key: string) => zis.getGlobal(key), has: (key: string) => zis.hasGlobal(key) }, public_); } public isClassResolved(className: string): boolean { className = Node.fixClassName(className); return this._compiledClasses.has(className); } public async resolveClass(className: string, global: GlobalVariableResolver, public_: boolean): Promise<PuppetASTClass> { className = Node.fixClassName(className); if (this._compiledClasses.has(className)) { const compiled = this._compiledClasses.get(className); if (public_) { compiled.markPublic(); } return compiled; } console.log("Compiling class " + className + " (for environment " + this.name + ")"); const classInfo = this.env.findClassInfo(className); if (classInfo == null) throw new CompilationError("No such class info: " + className); const compiledPath = classInfo.modulesInfo.getCompiledClassPath(classInfo.file); let parsedJSON = null; try { parsedJSON = await async.readJSON(compiledPath); } catch (e) { throw new CompilationError("Failed to parse class " + className); } const obj = PuppetASTParser.Parse(parsedJSON); if (!(obj instanceof PuppetASTClass)) throw "Not a class"; const clazz: PuppetASTClass = obj; this._compiledClasses.put(className, clazz); try { await clazz.resolve(clazz, new NodeContextResolver(this, global)); } catch (e) { console.log(e); this._compiledClasses.remove(className); throw new CompilationError("Failed to compile class: " + e); } if (public_) { clazz.markPublic(); } return clazz; } public async resolveFunction(context: PuppetASTContainerContext, resolver: Resolver, name: string, global: GlobalVariableResolver): Promise<ResolvedFunction> { name = Node.fixClassName(name); if (this._compiledFunctions.has(name)) { return this._compiledFunctions.get(name); } const functionInfo = this.env.findFunctionInfo(name); if (functionInfo == null) return null; let resolved: ResolvedFunction; if (functionInfo.isPuppet()) { console.log("Compiling function " + name + " (for environment " + this.name + ")"); const compiledPath = functionInfo.modulesInfo.getCompiledFunctionPath(functionInfo.file); let parsedJSON = null; try { parsedJSON = await async.readJSON(compiledPath); } catch (e) { throw new CompilationError("Failed to parse function " + name); } const obj = PuppetASTParser.Parse(parsedJSON); if (!(obj instanceof PuppetASTFunction)) throw "Not a function"; const function_: PuppetASTFunction = obj; resolved = async (args: PuppetASTObject[]) => { return await function_.apply(context, resolver, args); } } else { resolved = async (args: PuppetASTObject[]) => { const resolvedArgs: any[] = []; for (const arg of args) { const a = await arg.resolve(context, resolver); resolvedArgs.push(a); } return await rubyBridge.call(name, resolvedArgs); } } this._compiledFunctions.put(name, resolved); return resolved; } public async resolveDefinedType(definedTypeName: string, global: GlobalVariableResolver, public_: boolean): Promise<PuppetASTDefinedType> { if (this._compiledDefinedTypes.has(definedTypeName)) { const compiled = this._compiledDefinedTypes.get(definedTypeName); if (public_) { compiled.markPublic(); } return compiled; } console.log("Compiling resource " + definedTypeName + " (for environment " + this.name + ")"); const definedTypeInfo = this.env.findDefineTypeInfo(definedTypeName); if (definedTypeInfo == null) { console.log("Cannot resolve defined type: " + definedTypeName + " (not exists)") return; } const compiledPath = definedTypeInfo.modulesInfo.getCompiledClassPath(definedTypeInfo.file); let parsedJSON = null; try { parsedJSON = await async.readJSON(compiledPath); } catch (e) { throw new CompilationError("Failed to parse defined type " + definedTypeName); } const obj = PuppetASTParser.Parse(parsedJSON); if (!(obj instanceof PuppetASTDefinedType)) throw "Not a defined type"; const definedType: PuppetASTDefinedType = obj; if (public_) { definedType.markPublic(); } this._compiledDefinedTypes.put(definedTypeName, definedType); return definedType; } public async resolveManifests(global: GlobalVariableResolver): Promise<void> { console.log("Compiling manifests (for node " + this.name + " / environment " + this.env.name + ")"); if (!await async.fileExists(this.env.manifestsPath)) { console.log("Cannot compile manifests, no such file(s)"); return; } const modulesInfo = this.env.loadModulesInfo(); if (modulesInfo == null) throw new CompilationError("Cannot compile, no module info"); const files_ = await async.listFiles(this.env.manifestsPath); const files = files_.filter((name) => name.endsWith(".pp")); files.sort(); for (const file of files) { const compiledPath = this.env.getCompiledPath(path.join(this.env.manifestsName, file)); let parsedJSON = null; try { parsedJSON = await async.readJSON(compiledPath); } catch (e) { throw new CompilationError("Failed to parse manifest " + path.join(this.env.manifestsName, file)); } const obj = PuppetASTParser.Parse(parsedJSON); const resolver = new NodeContextResolver(this, global); await obj.resolve(this.ast, resolver); await this.ast.resolve(this.ast, resolver); } } public resolver(): NodeContextResolver { return new NodeContextResolver(this, this.globalResolver()); } public globalResolver(): GlobalVariableResolver { const zis = this; return { has: function(key: string): number { return zis.hasGlobal(key); }, get: function(key: string) { return zis.getGlobal(key) } } } public async init(facts?: any): Promise<void> { if (facts != null) { this.setFacts(facts); } const cert = this.env.getCertificate(this.name); if (cert != null) { for (const ext of cert.extensions) { const id = ext.id; const value: string = ext.value; if (CERTIFICATE_EXTENSIONS.hasOwnProperty(id)) { const ext = CERTIFICATE_EXTENSIONS[id]; // cut the fist two characters // https://puppet.com/docs/puppet/6.0/ssl_attributes_extensions.html#manually-checking-for-extensions-in-csrs-and-certificates this._extensions[ext] = value.substr(2); } } } this._hierarchy = await this.env.hierarchy.compile(this, this.env); await this.resolveManifests(this.globalResolver()); } public isEYamlKeysImported(hierarchy: number): boolean { const h = this._hierarchy.get(hierarchy); if (h == null || h.eyaml == null) return false; return this.env.workspace.isEYamlKeysImported(h.eyaml); } public hasEYamlPublickKey(hierarchy: number): boolean { const h = this._hierarchy.get(hierarchy); if (h == null || h.eyaml == null) return false; return this.env.workspace.hasEYamlPublickKey(h.eyaml); } public getEYaml(hierarchy: number): EYaml { const h = this._hierarchy.get(hierarchy); if (h == null) return null; return h.eyaml; } public getEYamlPublicKey(hierarchy: number): string { const h = this._hierarchy.get(hierarchy); if (h == null || h.eyaml == null) return null; return this.env.workspace.getEYamlPublicKey(h.eyaml); } public async updateEYamlKeys(hierarchy: number, updatedPublicKey: string): Promise<boolean> { const h = this._hierarchy.get(hierarchy); if (h == null || h.eyaml == null) return false; return await this.env.workspace.updateEYamlKeys(h.eyaml, updatedPublicKey); } } export class Node { public static fixClassName(className: string): string { const path = className.split("::"); if (path.length < 2) return className; if (path[0] == "") path.splice(0, 1); return path.join("::"); } }
the_stack
import * as vscode from "vscode"; import { LeoNode } from "./leoNode"; /** * * For simple interactions in webviews into vscode API */ export interface IVsCodeApi { postMessage(msg: {}): void; setState(state: {}): void; getState(): { [key: string]: any }; } /** * * Types of the various JSON configuration keys such as treeKeepFocus, defaultReloadIgnore, etc. */ export interface ConfigMembers { checkForChangeExternalFiles: string; defaultReloadIgnore: string; leoTreeBrowse: boolean; treeKeepFocus: boolean; treeKeepFocusWhenAside: boolean; statusBarString: string; statusBarColor: string; treeInExplorer: boolean; showOpenAside: boolean; showEditOnNodes: boolean; showArrowsOnNodes: boolean; showAddOnNodes: boolean; showMarkOnNodes: boolean; showCloneOnNodes: boolean; showCopyOnNodes: boolean; showEditionOnBody: boolean; // clone delete insert(s) showClipboardOnBody: boolean; // cut copy paste(s) showPromoteOnBody: boolean; // promote demote showExecuteOnBody: boolean; // extract(s) showExtractOnBody: boolean; showImportOnBody: boolean; showRefreshOnBody: boolean; showHoistOnBody: boolean; showMarkOnBody: boolean; showSortOnBody: boolean; invertNodeContrast: boolean; leoEditorPath: string; leoPythonCommand: string; startServerAutomatically: boolean; connectToServerAutomatically: boolean; connectionAddress: string; connectionPort: number; setDetached: boolean; limitUsers: number } /** * * Structure for configuration settings changes used along with welcome/settings webview. */ export interface ConfigSetting { code: string; value: any; } export interface FontSettings { zoomLevel: number; fontSize: number; } /** * * When refreshing the outline and getting to Leo's selected node */ export const enum RevealType { NoReveal = 0, // In apToLeoNode conversion, If if the global revealType is "NoReveal" and its the selected node, re-use the old id Reveal, RevealSelect, RevealSelectFocus } /** * * Required Refresh Dictionary of "elements to refresh" flags */ export interface ReqRefresh { node?: boolean; // Reveal received selected node (Navigation only, no tree change) tree?: boolean; // Tree needs refresh body?: boolean; // Body needs refresh scroll?: boolean; // Body needs to scroll to selection states?: boolean; // States needs refresh (changed, canUndo, canRedo, canDemote, canPromote, canDehoist) buttons?: boolean; // Buttons needs refresh documents?: boolean; // Documents needs refresh } /** * * Stackable front end commands */ export interface UserCommand { action: string; // String from Constants.LEOBRIDGE, which are commands for leobridgeserver node?: LeoNode | undefined; // We can START a stack with a targeted command name?: string | undefined; // If a string is required, for headline, etc. refreshType: ReqRefresh; // Minimal refresh level required by this command fromOutline: boolean; // Focus back on outline instead of body keepSelection?: boolean; // Should bring back selection on node prior to command resolveFn?: (result: any) => void; // call that with an answer from python's (or other) side rejectFn?: (reason: any) => void; // call if problem is encountered } /** * * Stackable leoBridge actions to be performed by Leo */ export interface LeoAction { parameter: string; // to pass along with action to python's side deferredPayload?: any | undefined; // Used when the action already has a return value ready but is also waiting for python's side resolveFn: (result: any) => void; // call that with an answer from python's (or other) side rejectFn: (reason: any) => void; // call if problem is encountered } /** * * Simple 'string log entry' package format */ export interface LeoLogEntry { log: string; } /** * * ArchivedPosition format package from Leo's leoflexx.py */ export interface ArchivedPosition { hasBody: boolean; // bool(p.b), hasChildren: boolean; // p.hasChildren() childIndex: number; // p._childIndex cloned: boolean; // p.isCloned() dirty: boolean; // p.isDirty() expanded: boolean; // p.isExpanded() gnx: string; // p.v.gnx level: number; // p.level() headline: string; // p.h marked: boolean; // p.isMarked() atFile: boolean // p.isAnyAtFileNode(): selected: boolean; // p == commander.p u?: any; // User Attributes stack: { gnx: string; // stack_v.gnx childIndex: number; // stack_childIndex headline: string; // stack_v.h }[]; // for (stack_v, stack_childIndex) in p.stack] } /** * * Object sent back from leoInteg's 'getStates' command */ export interface LeoPackageStates { changed: boolean; // Leo document has changed (is dirty) canUndo: boolean; // Leo document can undo the last operation done canRedo: boolean; // Leo document can redo the last operation 'undone' canDemote: boolean; // Currently selected node can have its siblings demoted canPromote: boolean; // Currently selected node can have its children promoted canDehoist: boolean; // Leo Document is currently hoisted and can be de-hoisted } /** * * Main interface for JSON sent from Leo back to leoInteg */ export interface LeoBridgePackage { // * Common to all result packages id: number; // * Possible answers from a "Constants.LEOBRIDGE" command gnx?: string[]; // get_all_gnx len?: number; // get_body_length body?: string; // get_body buttons?: LeoButton[]; // get_buttons commands?: vscode.QuickPickItem[]; // getCommands commander?: { changed: boolean, fileName: string; } filename?: string; // set_opened_file, open_file(s), ?close_file files?: LeoDocument[]; // get_all_open_commanders focus?: string; // find_next, find_previous found?: boolean // find_next, find_previous index?: number; // get_all_open_commanders language?: string; // get_body_states wrap?: boolean; // get_body_states tabWidth?: number | boolean; // get_body_states either the tabwidth or falsy node?: ArchivedPosition; // get_parent, set_opened_file, open_file(s), ?close_file children?: ArchivedPosition[]; // get_children searchSettings?: LeoGuiFindTabManagerSettings // get_search_settings selection?: BodySelectionInfo; // get_body_states states?: LeoPackageStates; // get_ui_states total?: number; // set_opened_file, open_file(s), close_file version?: string; major?: number; minor?: number; patch?: number; } /** * * Leo document structure used in the 'Opened Leo Documents' tree view provider sent back by the server */ export interface LeoDocument { name: string; index: number; changed: boolean; selected: boolean; } /** * * Leo '@button' structure used in the '@buttons' tree view provider sent back by the server */ export interface LeoButton { name: string; index: string; // STRING KEY } /** * * LeoInteg's Enum type for the search scope radio buttons of the find panel. */ export const enum LeoSearchScope { entireOutline = 0, subOutlineOnly, nodeOnly } /** * * LeoInteg search settings structure for use with the 'find' webview */ export interface LeoSearchSettings { //Find/change strings... findText: string; replaceText: string; // Find options... wholeWord: boolean; ignoreCase: boolean; regExp: boolean; markFinds: boolean; markChanges: boolean; searchHeadline: boolean; searchBody: boolean; searchScope: LeoSearchScope; // 0, 1 or 2 for outline, sub-outline, or node. } /** * * Leo's GUI search settings internal structure */ export interface LeoGuiFindTabManagerSettings { //Find/change strings... find_text: string, change_text: string, // Find options... ignore_case: boolean, mark_changes: boolean, mark_finds: boolean, node_only: boolean, pattern_match: boolean, search_body: boolean, search_headline: boolean, suboutline_only: boolean, whole_word: boolean } /** * * Icon path names used in leoNodes for rendering in treeview */ export interface Icon { light: string; dark: string; } /** * * LeoBody virtual file time information object */ export interface BodyTimeInfo { ctime: number; mtime: number; } /** * * Body position * Used in BodySelectionInfo interface */ export interface BodyPosition { line: number; col: number; } /** * * LeoBody cursor active position and text selection state, along with gnx */ export interface BodySelectionInfo { gnx: string; // scroll is stored as-is as the 'scrollBarSpot' in Leo // ! TEST scroll as single number only (for Leo vertical scroll value) scroll: number; // scroll: { // start: BodyPosition; // end: BodyPosition; // } insert: BodyPosition; start: BodyPosition; end: BodyPosition; } /** * * Parameter structure used in the 'runSaveFileDialog' equivalent when asking user input */ export interface showSaveAsDialogParameters { // See TODO in leoAsync.ts initialFile: string; title: string; message: string; filetypes: string[]; defaultExtension: string; } /** * * Parameter structure used in the 'runAskYesNoDialog' equivalent when asking user input */ export interface runAskYesNoDialogParameters { ask: string; message: string; yes_all: boolean; no_all: boolean; } /** * * Parameter structure used in the 'runAskOkDialog' equivalent when showing a warning */ export interface runWarnMessageDialogParameters { warn: string; message: string; } /** * * Parameter structure for non-blocking info message about detected file changes */ export interface runInfoMessageDialogParameters { message: string; } /** * * Used in showAskModalDialog to get answer from user interaction */ export interface AskMessageItem extends vscode.MessageItem { value: string; } /** * * Used in switch Leo document to get answer from user interaction */ export interface ChooseDocumentItem extends vscode.QuickPickItem { value: number; }
the_stack
declare class Bucket { /** * The bucket's name. * @name Bucket#name * @type {string} */ name: string; /** * A reference to the {@link Storage} associated with this {@link Bucket} * instance. * @name Bucket#storage * @type {Storage} */ storage: Storage; /** * A user project to apply to each request from this bucket. * @name Bucket#userProject * @type {string} */ userProject?: string; /** * Cloud Storage uses access control lists (ACLs) to manage object and * bucket access. ACLs are the mechanism you use to share objects with other * users and allow other users to access your buckets and objects. * * An ACL consists of one or more entries, where each entry grants permissions * to an entity. Permissions define the actions that can be performed against * an object or bucket (for example, `READ` or `WRITE`); the entity defines * who the permission applies to (for example, a specific user or group of * users). * * The `acl` object on a Bucket instance provides methods to get you a list of * the ACLs defined on your bucket, as well as set, update, and delete them. * * Buckets also have * [default * ACLs](https://cloud.google.com/storage/docs/access-control/lists#default) * for all created files. Default ACLs specify permissions that all new * objects added to the bucket will inherit by default. You can add, delete, * get, and update entities and permissions for these as well with * {@link Bucket#acl.default}. * * @see [About Access Control Lists]{@link http://goo.gl/6qBBPO} * @see [Default ACLs]{@link https://cloud.google.com/storage/docs/access-control/lists#default} * * @name Bucket#acl * @mixes Acl * @property {Acl} default Cloud Storage Buckets have * [default * ACLs](https://cloud.google.com/storage/docs/access-control/lists#default) * for all created files. You can add, delete, get, and update entities and * permissions for these as well. The method signatures and examples are all * the same, after only prefixing the method call with `default`. * * @example * const {Storage} = require('@google-cloud/storage'); * const storage = new Storage(); * * //- * // Make a bucket's contents publicly readable. * //- * const myBucket = storage.bucket('my-bucket'); * * const options = { * entity: 'allUsers', * role: storage.acl.READER_ROLE * }; * * myBucket.acl.add(options, function(err, aclObject) {}); * * //- * // If the callback is omitted, we'll return a Promise. * //- * myBucket.acl.add(options).then(function(data) { * const aclObject = data[0]; * const apiResponse = data[1]; * }); * * @example <caption>include:samples/acl.js</caption> * region_tag:storage_print_bucket_acl * Example of printing a bucket's ACL: * * @example <caption>include:samples/acl.js</caption> * region_tag:storage_print_bucket_acl_for_user * Example of printing a bucket's ACL for a specific user: * * @example <caption>include:samples/acl.js</caption> * region_tag:storage_add_bucket_owner * Example of adding an owner to a bucket: * * @example <caption>include:samples/acl.js</caption> * region_tag:storage_remove_bucket_owner * Example of removing an owner from a bucket: * * @example <caption>include:samples/acl.js</caption> * region_tag:storage_add_bucket_default_owner * Example of adding a default owner to a bucket: * * @example <caption>include:samples/acl.js</caption> * region_tag:storage_remove_bucket_default_owner * Example of removing a default owner from a bucket: */ acl: Acl; /** * Get and set IAM policies for your bucket. * * @name Bucket#iam * @mixes Iam * * @see [Cloud Storage IAM Management](https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management) * @see [Granting, Changing, and Revoking Access](https://cloud.google.com/iam/docs/granting-changing-revoking-access) * @see [IAM Roles](https://cloud.google.com/iam/docs/understanding-roles) * * @example * const {Storage} = require('@google-cloud/storage'); * const storage = new Storage(); * const bucket = storage.bucket('albums'); * * //- * // Get the IAM policy for your bucket. * //- * bucket.iam.getPolicy(function(err, policy) { * console.log(policy); * }); * * //- * // If the callback is omitted, we'll return a Promise. * //- * bucket.iam.getPolicy().then(function(data) { * const policy = data[0]; * const apiResponse = data[1]; * }); * * @example <caption>include:samples/iam.js</caption> * region_tag:storage_view_bucket_iam_members * Example of retrieving a bucket's IAM policy: * * @example <caption>include:samples/iam.js</caption> * region_tag:storage_add_bucket_iam_member * Example of adding to a bucket's IAM policy: * * @example <caption>include:samples/iam.js</caption> * region_tag:storage_remove_bucket_iam_member * Example of removing from a bucket's IAM policy: */ iam: Iam; /** * Get {@link File} objects for the files currently in the bucket as a * readable object stream. * * @method Bucket#getFilesStream * @param {GetFilesOptions} [query] Query object for listing files. * @returns {ReadableStream} A readable stream that emits {@link File} instances. * * @example * const {Storage} = require('@google-cloud/storage'); * const storage = new Storage(); * const bucket = storage.bucket('albums'); * * bucket.getFilesStream() * .on('error', console.error) * .on('data', function(file) { * // file is a File object. * }) * .on('end', function() { * // All files retrieved. * }); * * //- * // If you anticipate many results, you can end a stream early to prevent * // unnecessary processing and API requests. * //- * bucket.getFilesStream() * .on('data', function(file) { * this.end(); * }); * * //- * // If you're filtering files with a delimiter, you should use * // {@link Bucket#getFiles} and set `autoPaginate: false` in order to * // preserve the `apiResponse` argument. * //- * const prefixes = []; * * function callback(err, files, nextQuery, apiResponse) { * prefixes = prefixes.concat(apiResponse.prefixes); * * if (nextQuery) { * bucket.getFiles(nextQuery, callback); * } else { * // prefixes = The finished array of prefixes. * } * } * * bucket.getFiles({ * autoPaginate: false, * delimiter: '/' * }, callback); */ getFilesStream: Function; signer?: URLSigner; constructor(storage: Storage, name: string, options?: BucketOptions); addLifecycleRule( rule: LifecycleRule, options?: AddLifecycleRuleOptions ): Promise<SetBucketMetadataResponse>; addLifecycleRule( rule: LifecycleRule, options: AddLifecycleRuleOptions, callback: SetBucketMetadataCallback ): void; addLifecycleRule( rule: LifecycleRule, callback: SetBucketMetadataCallback ): void; combine( sources: string[] | File[], destination: string | File, options?: CombineOptions ): Promise<CombineResponse>; combine( sources: string[] | File[], destination: string | File, options: CombineOptions, callback: CombineCallback ): void; combine( sources: string[] | File[], destination: string | File, callback: CombineCallback ): void; createChannel( id: string, config: CreateChannelConfig, options?: CreateChannelOptions ): Promise<CreateChannelResponse>; createChannel( id: string, config: CreateChannelConfig, callback: CreateChannelCallback ): void; createChannel( id: string, config: CreateChannelConfig, options: CreateChannelOptions, callback: CreateChannelCallback ): void; createNotification( topic: string, options?: CreateNotificationOptions ): Promise<CreateNotificationResponse>; createNotification( topic: string, options: CreateNotificationOptions, callback: CreateNotificationCallback ): void; createNotification(topic: string, callback: CreateNotificationCallback): void; deleteFiles(query?: DeleteFilesOptions): Promise<void>; deleteFiles(callback: DeleteFilesCallback): void; deleteFiles(query: DeleteFilesOptions, callback: DeleteFilesCallback): void; deleteLabels(labels?: string | string[]): Promise<DeleteLabelsResponse>; deleteLabels(callback: DeleteLabelsCallback): void; deleteLabels(labels: string | string[], callback: DeleteLabelsCallback): void; disableRequesterPays(): Promise<DisableRequesterPaysResponse>; disableRequesterPays(callback: DisableRequesterPaysCallback): void; enableLogging( config: EnableLoggingOptions ): Promise<SetBucketMetadataResponse>; enableLogging( config: EnableLoggingOptions, callback: SetBucketMetadataCallback ): void; enableRequesterPays(): Promise<EnableRequesterPaysResponse>; enableRequesterPays(callback: EnableRequesterPaysCallback): void; /** * Create a {@link File} object. See {@link File} to see how to handle * the different use cases you may have. * * @param {string} name The name of the file in this bucket. * @param {object} [options] Configuration options. * @param {string|number} [options.generation] Only use a specific revision of * this file. * @param {string} [options.encryptionKey] A custom encryption key. See * [Customer-supplied Encryption * Keys](https://cloud.google.com/storage/docs/encryption#customer-supplied). * @param {string} [options.kmsKeyName] The name of the Cloud KMS key that will * be used to encrypt the object. Must be in the format: * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`. * KMS key ring must use the same location as the bucket. * @returns {File} * * @example * const {Storage} = require('@google-cloud/storage'); * const storage = new Storage(); * const bucket = storage.bucket('albums'); * const file = bucket.file('my-existing-file.png'); */ file(name: string, options?: FileOptions): File; getFiles(query?: GetFilesOptions): Promise<GetFilesResponse>; getFiles(query: GetFilesOptions, callback: GetFilesCallback): void; getFiles(callback: GetFilesCallback): void; getLabels(options: GetLabelsOptions): Promise<GetLabelsResponse>; getLabels(callback: GetLabelsCallback): void; getLabels(options: GetLabelsOptions, callback: GetLabelsCallback): void; getNotifications( options?: GetNotificationsOptions ): Promise<GetNotificationsResponse>; getNotifications(callback: GetNotificationsCallback): void; getNotifications( options: GetNotificationsOptions, callback: GetNotificationsCallback ): void; getSignedUrl(cfg: GetBucketSignedUrlConfig): Promise<GetSignedUrlResponse>; getSignedUrl( cfg: GetBucketSignedUrlConfig, callback: GetSignedUrlCallback ): void; lock(metageneration: number | string): Promise<BucketLockResponse>; lock(metageneration: number | string, callback: BucketLockCallback): void; makePrivate( options?: MakeBucketPrivateOptions ): Promise<MakeBucketPrivateResponse>; makePrivate(callback: MakeBucketPrivateCallback): void; makePrivate( options: MakeBucketPrivateOptions, callback: MakeBucketPrivateCallback ): void; makePublic( options?: MakeBucketPublicOptions ): Promise<MakeBucketPublicResponse>; makePublic(callback: MakeBucketPublicCallback): void; makePublic( options: MakeBucketPublicOptions, callback: MakeBucketPublicCallback ): void; /** * Get a reference to a Cloud Pub/Sub Notification. * * @param {string} id ID of notification. * @returns {Notification} * @see Notification * * @example * const {Storage} = require('@google-cloud/storage'); * const storage = new Storage(); * const bucket = storage.bucket('my-bucket'); * const notification = bucket.notification('1'); */ notification(id: string): Notification; removeRetentionPeriod(): Promise<SetBucketMetadataResponse>; removeRetentionPeriod(callback: SetBucketMetadataCallback): void; request(reqOpts: DecorateRequestOptions): Promise<[ResponseBody, Metadata]>; request( reqOpts: DecorateRequestOptions, callback: BodyResponseCallback ): void; setLabels( labels: Labels, options?: SetLabelsOptions ): Promise<SetLabelsResponse>; setLabels(labels: Labels, callback: SetLabelsCallback): void; setLabels( labels: Labels, options: SetLabelsOptions, callback: SetLabelsCallback ): void; setRetentionPeriod(duration: number): Promise<SetBucketMetadataResponse>; setRetentionPeriod( duration: number, callback: SetBucketMetadataCallback ): void; setCorsConfiguration( corsConfiguration: Cors[] ): Promise<SetBucketMetadataResponse>; setCorsConfiguration( corsConfiguration: Cors[], callback: SetBucketMetadataCallback ): void; setStorageClass( storageClass: string, options?: SetBucketStorageClassOptions ): Promise<SetBucketMetadataResponse>; setStorageClass( storageClass: string, callback: SetBucketStorageClassCallback ): void; setStorageClass( storageClass: string, options: SetBucketStorageClassOptions, callback: SetBucketStorageClassCallback ): void; /** * Set a user project to be billed for all requests made from this Bucket * object and any files referenced from this Bucket object. * * @param {string} userProject The user project. * * @example * const {Storage} = require('@google-cloud/storage'); * const storage = new Storage(); * const bucket = storage.bucket('albums'); * * bucket.setUserProject('grape-spaceship-123'); */ setUserProject(userProject: string): void; upload(pathString: string, options?: UploadOptions): Promise<UploadResponse>; upload( pathString: string, options: UploadOptions, callback: UploadCallback ): void; upload(pathString: string, callback: UploadCallback): void; makeAllFilesPublicPrivate_( options?: MakeAllFilesPublicPrivateOptions ): Promise<MakeAllFilesPublicPrivateResponse>; makeAllFilesPublicPrivate_(callback: MakeAllFilesPublicPrivateCallback): void; makeAllFilesPublicPrivate_( options: MakeAllFilesPublicPrivateOptions, callback: MakeAllFilesPublicPrivateCallback ): void; getId(): string; } /*! firebase-admin v9.4.2 */ declare namespace firebasestorage { /** * The default `Storage` service if no * app is provided or the `Storage` service associated with the provided * app. */ export class Storage { /** * Optional app whose `Storage` service to * return. If not provided, the default `Storage` service will be returned. */ app: app.App; /** * @returns A [Bucket](https://cloud.google.com/nodejs/docs/reference/storage/latest/Bucket) * instance as defined in the `@google-cloud/storage` package. */ bucket(name?: string): Bucket; } }
the_stack
import { VSBuffer, VSBufferReadable, VSBufferReadableStream } from 'vs/base/common/buffer'; import { CancellationToken } from 'vs/base/common/cancellation'; import { ErrorNoTelemetry } from 'vs/base/common/errors'; import { Event } from 'vs/base/common/event'; import { IExpression, IRelativePattern } from 'vs/base/common/glob'; import { IDisposable } from 'vs/base/common/lifecycle'; import { TernarySearchTree } from 'vs/base/common/map'; import { sep } from 'vs/base/common/path'; import { ReadableStreamEvents } from 'vs/base/common/stream'; import { startsWithIgnoreCase } from 'vs/base/common/strings'; import { isNumber } from 'vs/base/common/types'; import { URI } from 'vs/base/common/uri'; import { localize } from 'vs/nls'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; //#region file service & providers export const IFileService = createDecorator<IFileService>('fileService'); export interface IFileService { readonly _serviceBrand: undefined; /** * An event that is fired when a file system provider is added or removed */ readonly onDidChangeFileSystemProviderRegistrations: Event<IFileSystemProviderRegistrationEvent>; /** * An event that is fired when a registered file system provider changes it's capabilities. */ readonly onDidChangeFileSystemProviderCapabilities: Event<IFileSystemProviderCapabilitiesChangeEvent>; /** * An event that is fired when a file system provider is about to be activated. Listeners * can join this event with a long running promise to help in the activation process. */ readonly onWillActivateFileSystemProvider: Event<IFileSystemProviderActivationEvent>; /** * Registers a file system provider for a certain scheme. */ registerProvider(scheme: string, provider: IFileSystemProvider): IDisposable; /** * Returns a file system provider for a certain scheme. */ getProvider(scheme: string): IFileSystemProvider | undefined; /** * Tries to activate a provider with the given scheme. */ activateProvider(scheme: string): Promise<void>; /** * Checks if this file service can handle the given resource by * first activating any extension that wants to be activated * on the provided resource scheme to include extensions that * contribute file system providers for the given resource. */ canHandleResource(resource: URI): Promise<boolean>; /** * Checks if the file service has a registered provider for the * provided resource. * * Note: this does NOT account for contributed providers from * extensions that have not been activated yet. To include those, * consider to call `await fileService.canHandleResource(resource)`. */ hasProvider(resource: URI): boolean; /** * Checks if the provider for the provided resource has the provided file system capability. */ hasCapability(resource: URI, capability: FileSystemProviderCapabilities): boolean; /** * List the schemes and capabilies for registered file system providers */ listCapabilities(): Iterable<{ scheme: string; capabilities: FileSystemProviderCapabilities }>; /** * Allows to listen for file changes. The event will fire for every file within the opened workspace * (if any) as well as all files that have been watched explicitly using the #watch() API. */ readonly onDidFilesChange: Event<FileChangesEvent>; /** * An event that is fired upon successful completion of a certain file operation. */ readonly onDidRunOperation: Event<FileOperationEvent>; /** * Resolve the properties of a file/folder identified by the resource. For a folder, children * information is resolved as well depending on the provided options. Use `stat()` method if * you do not need children information. * * If the optional parameter "resolveTo" is specified in options, the stat service is asked * to provide a stat object that should contain the full graph of folders up to all of the * target resources. * * If the optional parameter "resolveSingleChildDescendants" is specified in options, * the stat service is asked to automatically resolve child folders that only * contain a single element. * * If the optional parameter "resolveMetadata" is specified in options, * the stat will contain metadata information such as size, mtime and etag. */ resolve(resource: URI, options: IResolveMetadataFileOptions): Promise<IFileStatWithMetadata>; resolve(resource: URI, options?: IResolveFileOptions): Promise<IFileStat>; /** * Same as `resolve()` but supports resolving multiple resources in parallel. * * If one of the resolve targets fails to resolve returns a fake `IFileStat` instead of * making the whole call fail. */ resolveAll(toResolve: { resource: URI; options: IResolveMetadataFileOptions }[]): Promise<IFileStatResult[]>; resolveAll(toResolve: { resource: URI; options?: IResolveFileOptions }[]): Promise<IFileStatResult[]>; /** * Same as `resolve()` but without resolving the children of a folder if the * resource is pointing to a folder. */ stat(resource: URI): Promise<IFileStatWithPartialMetadata>; /** * Finds out if a file/folder identified by the resource exists. */ exists(resource: URI): Promise<boolean>; /** * Read the contents of the provided resource unbuffered. */ readFile(resource: URI, options?: IReadFileOptions, token?: CancellationToken): Promise<IFileContent>; /** * Read the contents of the provided resource buffered as stream. */ readFileStream(resource: URI, options?: IReadFileStreamOptions, token?: CancellationToken): Promise<IFileStreamContent>; /** * Updates the content replacing its previous value. * * Emits a `FileOperation.WRITE` file operation event when successful. */ writeFile(resource: URI, bufferOrReadableOrStream: VSBuffer | VSBufferReadable | VSBufferReadableStream, options?: IWriteFileOptions): Promise<IFileStatWithMetadata>; /** * Moves the file/folder to a new path identified by the resource. * * The optional parameter overwrite can be set to replace an existing file at the location. * * Emits a `FileOperation.MOVE` file operation event when successful. */ move(source: URI, target: URI, overwrite?: boolean): Promise<IFileStatWithMetadata>; /** * Find out if a move operation is possible given the arguments. No changes on disk will * be performed. Returns an Error if the operation cannot be done. */ canMove(source: URI, target: URI, overwrite?: boolean): Promise<Error | true>; /** * Copies the file/folder to a path identified by the resource. A folder is copied * recursively. * * Emits a `FileOperation.COPY` file operation event when successful. */ copy(source: URI, target: URI, overwrite?: boolean): Promise<IFileStatWithMetadata>; /** * Find out if a copy operation is possible given the arguments. No changes on disk will * be performed. Returns an Error if the operation cannot be done. */ canCopy(source: URI, target: URI, overwrite?: boolean): Promise<Error | true>; /** * Clones a file to a path identified by the resource. Folders are not supported. * * If the target path exists, it will be overwritten. */ cloneFile(source: URI, target: URI): Promise<void>; /** * Creates a new file with the given path and optional contents. The returned promise * will have the stat model object as a result. * * The optional parameter content can be used as value to fill into the new file. * * Emits a `FileOperation.CREATE` file operation event when successful. */ createFile(resource: URI, bufferOrReadableOrStream?: VSBuffer | VSBufferReadable | VSBufferReadableStream, options?: ICreateFileOptions): Promise<IFileStatWithMetadata>; /** * Find out if a file create operation is possible given the arguments. No changes on disk will * be performed. Returns an Error if the operation cannot be done. */ canCreateFile(resource: URI, options?: ICreateFileOptions): Promise<Error | true>; /** * Creates a new folder with the given path. The returned promise * will have the stat model object as a result. * * Emits a `FileOperation.CREATE` file operation event when successful. */ createFolder(resource: URI): Promise<IFileStatWithMetadata>; /** * Deletes the provided file. The optional useTrash parameter allows to * move the file to trash. The optional recursive parameter allows to delete * non-empty folders recursively. * * Emits a `FileOperation.DELETE` file operation event when successful. */ del(resource: URI, options?: Partial<IFileDeleteOptions>): Promise<void>; /** * Find out if a delete operation is possible given the arguments. No changes on disk will * be performed. Returns an Error if the operation cannot be done. */ canDelete(resource: URI, options?: Partial<IFileDeleteOptions>): Promise<Error | true>; /** * An event that signals an error when watching for file changes. */ readonly onDidWatchError: Event<Error>; /** * Allows to start a watcher that reports file/folder change events on the provided resource. * * Note: recursive file watching is not supported from this method. Only events from files * that are direct children of the provided resource will be reported. */ watch(resource: URI, options?: IWatchOptions): IDisposable; /** * Frees up any resources occupied by this service. */ dispose(): void; } export interface IFileOverwriteOptions { /** * Set to `true` to overwrite a file if it exists. Will * throw an error otherwise if the file does exist. */ readonly overwrite: boolean; } export interface IFileUnlockOptions { /** * Set to `true` to try to remove any write locks the file might * have. A file that is write locked will throw an error for any * attempt to write to unless `unlock: true` is provided. */ readonly unlock: boolean; } export interface IFileAtomicReadOptions { /** * The optional `atomic` flag can be used to make sure * the `readFile` method is not running in parallel with * any `write` operations in the same process. * * Typically you should not need to use this flag but if * for example you are quickly reading a file right after * a file event occurred and the file changes a lot, there * is a chance that a read returns an empty or partial file * because a pending write has not finished yet. * * Note: this does not prevent the file from being written * to from a different process. If you need such atomic * operations, you better use a real database as storage. */ readonly atomic: true; } export interface IFileReadStreamOptions { /** * Is an integer specifying where to begin reading from in the file. If position is undefined, * data will be read from the current file position. */ readonly position?: number; /** * Is an integer specifying how many bytes to read from the file. By default, all bytes * will be read. */ readonly length?: number; /** * If provided, the size of the file will be checked against the limits. */ limits?: { readonly size?: number; readonly memory?: number; }; } export interface IFileWriteOptions extends IFileOverwriteOptions, IFileUnlockOptions { /** * Set to `true` to create a file when it does not exist. Will * throw an error otherwise if the file does not exist. */ readonly create: boolean; } export type IFileOpenOptions = IFileOpenForReadOptions | IFileOpenForWriteOptions; export function isFileOpenForWriteOptions(options: IFileOpenOptions): options is IFileOpenForWriteOptions { return options.create === true; } export interface IFileOpenForReadOptions { /** * A hint that the file should be opened for reading only. */ readonly create: false; } export interface IFileOpenForWriteOptions extends IFileUnlockOptions { /** * A hint that the file should be opened for reading and writing. */ readonly create: true; } export interface IFileDeleteOptions { /** * Set to `true` to recursively delete any children of the file. This * only applies to folders and can lead to an error unless provided * if the folder is not empty. */ readonly recursive: boolean; /** * Set to `true` to attempt to move the file to trash * instead of deleting it permanently from disk. This * option maybe not be supported on all providers. */ readonly useTrash: boolean; } export enum FileType { /** * File is unknown (neither file, directory nor symbolic link). */ Unknown = 0, /** * File is a normal file. */ File = 1, /** * File is a directory. */ Directory = 2, /** * File is a symbolic link. * * Note: even when the file is a symbolic link, you can test for * `FileType.File` and `FileType.Directory` to know the type of * the target the link points to. */ SymbolicLink = 64 } export enum FilePermission { /** * File is readonly. */ Readonly = 1 } export interface IStat { /** * The file type. */ readonly type: FileType; /** * The last modification date represented as millis from unix epoch. */ readonly mtime: number; /** * The creation date represented as millis from unix epoch. */ readonly ctime: number; /** * The size of the file in bytes. */ readonly size: number; /** * The file permissions. */ readonly permissions?: FilePermission; } export interface IWatchOptions { /** * Set to `true` to watch for changes recursively in a folder * and all of its children. */ readonly recursive: boolean; /** * A set of glob patterns or paths to exclude from watching. */ excludes: string[]; /** * An optional set of glob patterns or paths to include for * watching. If not provided, all paths are considered for * events. */ includes?: Array<string | IRelativePattern>; } export const enum FileSystemProviderCapabilities { /** * Provider supports unbuffered read/write. */ FileReadWrite = 1 << 1, /** * Provider supports open/read/write/close low level file operations. */ FileOpenReadWriteClose = 1 << 2, /** * Provider supports stream based reading. */ FileReadStream = 1 << 4, /** * Provider supports copy operation. */ FileFolderCopy = 1 << 3, /** * Provider is path case sensitive. */ PathCaseSensitive = 1 << 10, /** * All files of the provider are readonly. */ Readonly = 1 << 11, /** * Provider supports to delete via trash. */ Trash = 1 << 12, /** * Provider support to unlock files for writing. */ FileWriteUnlock = 1 << 13, /** * Provider support to read files atomically. This implies the * provider provides the `FileReadWrite` capability too. */ FileAtomicRead = 1 << 14, /** * Provider support to clone files atomically. */ FileClone = 1 << 15 } export interface IFileSystemProvider { readonly capabilities: FileSystemProviderCapabilities; readonly onDidChangeCapabilities: Event<void>; readonly onDidChangeFile: Event<readonly IFileChange[]>; readonly onDidWatchError?: Event<string>; watch(resource: URI, opts: IWatchOptions): IDisposable; stat(resource: URI): Promise<IStat>; mkdir(resource: URI): Promise<void>; readdir(resource: URI): Promise<[string, FileType][]>; delete(resource: URI, opts: IFileDeleteOptions): Promise<void>; rename(from: URI, to: URI, opts: IFileOverwriteOptions): Promise<void>; copy?(from: URI, to: URI, opts: IFileOverwriteOptions): Promise<void>; readFile?(resource: URI): Promise<Uint8Array>; writeFile?(resource: URI, content: Uint8Array, opts: IFileWriteOptions): Promise<void>; readFileStream?(resource: URI, opts: IFileReadStreamOptions, token: CancellationToken): ReadableStreamEvents<Uint8Array>; open?(resource: URI, opts: IFileOpenOptions): Promise<number>; close?(fd: number): Promise<void>; read?(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number>; write?(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number>; cloneFile?(from: URI, to: URI): Promise<void>; } export interface IFileSystemProviderWithFileReadWriteCapability extends IFileSystemProvider { readFile(resource: URI): Promise<Uint8Array>; writeFile(resource: URI, content: Uint8Array, opts: IFileWriteOptions): Promise<void>; } export function hasReadWriteCapability(provider: IFileSystemProvider): provider is IFileSystemProviderWithFileReadWriteCapability { return !!(provider.capabilities & FileSystemProviderCapabilities.FileReadWrite); } export interface IFileSystemProviderWithFileFolderCopyCapability extends IFileSystemProvider { copy(from: URI, to: URI, opts: IFileOverwriteOptions): Promise<void>; } export function hasFileFolderCopyCapability(provider: IFileSystemProvider): provider is IFileSystemProviderWithFileFolderCopyCapability { return !!(provider.capabilities & FileSystemProviderCapabilities.FileFolderCopy); } export interface IFileSystemProviderWithFileCloneCapability extends IFileSystemProvider { cloneFile(from: URI, to: URI): Promise<void>; } export function hasFileCloneCapability(provider: IFileSystemProvider): provider is IFileSystemProviderWithFileCloneCapability { return !!(provider.capabilities & FileSystemProviderCapabilities.FileClone); } export interface IFileSystemProviderWithOpenReadWriteCloseCapability extends IFileSystemProvider { open(resource: URI, opts: IFileOpenOptions): Promise<number>; close(fd: number): Promise<void>; read(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number>; write(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number>; } export function hasOpenReadWriteCloseCapability(provider: IFileSystemProvider): provider is IFileSystemProviderWithOpenReadWriteCloseCapability { return !!(provider.capabilities & FileSystemProviderCapabilities.FileOpenReadWriteClose); } export interface IFileSystemProviderWithFileReadStreamCapability extends IFileSystemProvider { readFileStream(resource: URI, opts: IFileReadStreamOptions, token: CancellationToken): ReadableStreamEvents<Uint8Array>; } export function hasFileReadStreamCapability(provider: IFileSystemProvider): provider is IFileSystemProviderWithFileReadStreamCapability { return !!(provider.capabilities & FileSystemProviderCapabilities.FileReadStream); } export interface IFileSystemProviderWithFileAtomicReadCapability extends IFileSystemProvider { readFile(resource: URI, opts?: IFileAtomicReadOptions): Promise<Uint8Array>; } export function hasFileAtomicReadCapability(provider: IFileSystemProvider): provider is IFileSystemProviderWithFileAtomicReadCapability { if (!hasReadWriteCapability(provider)) { return false; // we require the `FileReadWrite` capability too } return !!(provider.capabilities & FileSystemProviderCapabilities.FileAtomicRead); } export enum FileSystemProviderErrorCode { FileExists = 'EntryExists', FileNotFound = 'EntryNotFound', FileNotADirectory = 'EntryNotADirectory', FileIsADirectory = 'EntryIsADirectory', FileExceedsMemoryLimit = 'EntryExceedsMemoryLimit', FileTooLarge = 'EntryTooLarge', FileWriteLocked = 'EntryWriteLocked', NoPermissions = 'NoPermissions', Unavailable = 'Unavailable', Unknown = 'Unknown' } export class FileSystemProviderError extends Error { constructor(message: string, readonly code: FileSystemProviderErrorCode) { super(message); } } export function createFileSystemProviderError(error: Error | string, code: FileSystemProviderErrorCode): FileSystemProviderError { const providerError = new FileSystemProviderError(error.toString(), code); markAsFileSystemProviderError(providerError, code); return providerError; } export function ensureFileSystemProviderError(error?: Error): Error { if (!error) { return createFileSystemProviderError(localize('unknownError', "Unknown Error"), FileSystemProviderErrorCode.Unknown); // https://github.com/microsoft/vscode/issues/72798 } return error; } export function markAsFileSystemProviderError(error: Error, code: FileSystemProviderErrorCode): Error { error.name = code ? `${code} (FileSystemError)` : `FileSystemError`; return error; } export function toFileSystemProviderErrorCode(error: Error | undefined | null): FileSystemProviderErrorCode { // Guard against abuse if (!error) { return FileSystemProviderErrorCode.Unknown; } // FileSystemProviderError comes with the code if (error instanceof FileSystemProviderError) { return error.code; } // Any other error, check for name match by assuming that the error // went through the markAsFileSystemProviderError() method const match = /^(.+) \(FileSystemError\)$/.exec(error.name); if (!match) { return FileSystemProviderErrorCode.Unknown; } switch (match[1]) { case FileSystemProviderErrorCode.FileExists: return FileSystemProviderErrorCode.FileExists; case FileSystemProviderErrorCode.FileIsADirectory: return FileSystemProviderErrorCode.FileIsADirectory; case FileSystemProviderErrorCode.FileNotADirectory: return FileSystemProviderErrorCode.FileNotADirectory; case FileSystemProviderErrorCode.FileNotFound: return FileSystemProviderErrorCode.FileNotFound; case FileSystemProviderErrorCode.FileExceedsMemoryLimit: return FileSystemProviderErrorCode.FileExceedsMemoryLimit; case FileSystemProviderErrorCode.FileTooLarge: return FileSystemProviderErrorCode.FileTooLarge; case FileSystemProviderErrorCode.FileWriteLocked: return FileSystemProviderErrorCode.FileWriteLocked; case FileSystemProviderErrorCode.NoPermissions: return FileSystemProviderErrorCode.NoPermissions; case FileSystemProviderErrorCode.Unavailable: return FileSystemProviderErrorCode.Unavailable; } return FileSystemProviderErrorCode.Unknown; } export function toFileOperationResult(error: Error): FileOperationResult { // FileSystemProviderError comes with the result already if (error instanceof FileOperationError) { return error.fileOperationResult; } // Otherwise try to find from code switch (toFileSystemProviderErrorCode(error)) { case FileSystemProviderErrorCode.FileNotFound: return FileOperationResult.FILE_NOT_FOUND; case FileSystemProviderErrorCode.FileIsADirectory: return FileOperationResult.FILE_IS_DIRECTORY; case FileSystemProviderErrorCode.FileNotADirectory: return FileOperationResult.FILE_NOT_DIRECTORY; case FileSystemProviderErrorCode.FileWriteLocked: return FileOperationResult.FILE_WRITE_LOCKED; case FileSystemProviderErrorCode.NoPermissions: return FileOperationResult.FILE_PERMISSION_DENIED; case FileSystemProviderErrorCode.FileExists: return FileOperationResult.FILE_MOVE_CONFLICT; case FileSystemProviderErrorCode.FileExceedsMemoryLimit: return FileOperationResult.FILE_EXCEEDS_MEMORY_LIMIT; case FileSystemProviderErrorCode.FileTooLarge: return FileOperationResult.FILE_TOO_LARGE; default: return FileOperationResult.FILE_OTHER_ERROR; } } export interface IFileSystemProviderRegistrationEvent { readonly added: boolean; readonly scheme: string; readonly provider?: IFileSystemProvider; } export interface IFileSystemProviderCapabilitiesChangeEvent { readonly provider: IFileSystemProvider; readonly scheme: string; } export interface IFileSystemProviderActivationEvent { readonly scheme: string; join(promise: Promise<void>): void; } export const enum FileOperation { CREATE, DELETE, MOVE, COPY, WRITE } export interface IFileOperationEvent { readonly resource: URI; readonly operation: FileOperation; isOperation(operation: FileOperation.DELETE | FileOperation.WRITE): boolean; isOperation(operation: FileOperation.CREATE | FileOperation.MOVE | FileOperation.COPY): this is IFileOperationEventWithMetadata; } export interface IFileOperationEventWithMetadata extends IFileOperationEvent { readonly target: IFileStatWithMetadata; } export class FileOperationEvent implements IFileOperationEvent { constructor(resource: URI, operation: FileOperation.DELETE | FileOperation.WRITE); constructor(resource: URI, operation: FileOperation.CREATE | FileOperation.MOVE | FileOperation.COPY, target: IFileStatWithMetadata); constructor(readonly resource: URI, readonly operation: FileOperation, readonly target?: IFileStatWithMetadata) { } isOperation(operation: FileOperation.DELETE | FileOperation.WRITE): boolean; isOperation(operation: FileOperation.CREATE | FileOperation.MOVE | FileOperation.COPY): this is IFileOperationEventWithMetadata; isOperation(operation: FileOperation): boolean { return this.operation === operation; } } /** * Possible changes that can occur to a file. */ export const enum FileChangeType { UPDATED, ADDED, DELETED } /** * Identifies a single change in a file. */ export interface IFileChange { /** * The type of change that occurred to the file. */ readonly type: FileChangeType; /** * The unified resource identifier of the file that changed. */ readonly resource: URI; } export class FileChangesEvent { private readonly added: TernarySearchTree<URI, IFileChange> | undefined = undefined; private readonly updated: TernarySearchTree<URI, IFileChange> | undefined = undefined; private readonly deleted: TernarySearchTree<URI, IFileChange> | undefined = undefined; constructor(changes: readonly IFileChange[], ignorePathCasing: boolean) { this.rawChanges = changes; const entriesByType = new Map<FileChangeType, [URI, IFileChange][]>(); for (const change of changes) { const array = entriesByType.get(change.type); if (array) { array.push([change.resource, change]); } else { entriesByType.set(change.type, [[change.resource, change]]); } switch (change.type) { case FileChangeType.ADDED: this.rawAdded.push(change.resource); break; case FileChangeType.UPDATED: this.rawUpdated.push(change.resource); break; case FileChangeType.DELETED: this.rawDeleted.push(change.resource); break; } } for (const [key, value] of entriesByType) { switch (key) { case FileChangeType.ADDED: this.added = TernarySearchTree.forUris<IFileChange>(() => ignorePathCasing); this.added.fill(value); break; case FileChangeType.UPDATED: this.updated = TernarySearchTree.forUris<IFileChange>(() => ignorePathCasing); this.updated.fill(value); break; case FileChangeType.DELETED: this.deleted = TernarySearchTree.forUris<IFileChange>(() => ignorePathCasing); this.deleted.fill(value); break; } } } /** * Find out if the file change events match the provided resource. * * Note: when passing `FileChangeType.DELETED`, we consider a match * also when the parent of the resource got deleted. */ contains(resource: URI, ...types: FileChangeType[]): boolean { return this.doContains(resource, { includeChildren: false }, ...types); } /** * Find out if the file change events either match the provided * resource, or contain a child of this resource. */ affects(resource: URI, ...types: FileChangeType[]): boolean { return this.doContains(resource, { includeChildren: true }, ...types); } private doContains(resource: URI, options: { includeChildren: boolean }, ...types: FileChangeType[]): boolean { if (!resource) { return false; } const hasTypesFilter = types.length > 0; // Added if (!hasTypesFilter || types.includes(FileChangeType.ADDED)) { if (this.added?.get(resource)) { return true; } if (options.includeChildren && this.added?.findSuperstr(resource)) { return true; } } // Updated if (!hasTypesFilter || types.includes(FileChangeType.UPDATED)) { if (this.updated?.get(resource)) { return true; } if (options.includeChildren && this.updated?.findSuperstr(resource)) { return true; } } // Deleted if (!hasTypesFilter || types.includes(FileChangeType.DELETED)) { if (this.deleted?.findSubstr(resource) /* deleted also considers parent folders */) { return true; } if (options.includeChildren && this.deleted?.findSuperstr(resource)) { return true; } } return false; } /** * Returns if this event contains added files. */ gotAdded(): boolean { return !!this.added; } /** * Returns if this event contains deleted files. */ gotDeleted(): boolean { return !!this.deleted; } /** * Returns if this event contains updated files. */ gotUpdated(): boolean { return !!this.updated; } /** * @deprecated use the `contains` or `affects` method to efficiently find * out if the event relates to a given resource. these methods ensure: * - that there is no expensive lookup needed (by using a `TernarySearchTree`) * - correctly handles `FileChangeType.DELETED` events */ readonly rawChanges: readonly IFileChange[] = []; /** * @deprecated use the `contains` or `affects` method to efficiently find * out if the event relates to a given resource. these methods ensure: * - that there is no expensive lookup needed (by using a `TernarySearchTree`) * - correctly handles `FileChangeType.DELETED` events */ readonly rawAdded: URI[] = []; /** * @deprecated use the `contains` or `affects` method to efficiently find * out if the event relates to a given resource. these methods ensure: * - that there is no expensive lookup needed (by using a `TernarySearchTree`) * - correctly handles `FileChangeType.DELETED` events */ readonly rawUpdated: URI[] = []; /** * @deprecated use the `contains` or `affects` method to efficiently find * out if the event relates to a given resource. these methods ensure: * - that there is no expensive lookup needed (by using a `TernarySearchTree`) * - correctly handles `FileChangeType.DELETED` events */ readonly rawDeleted: URI[] = []; } export function isParent(path: string, candidate: string, ignoreCase?: boolean): boolean { if (!path || !candidate || path === candidate) { return false; } if (candidate.length > path.length) { return false; } if (candidate.charAt(candidate.length - 1) !== sep) { candidate += sep; } if (ignoreCase) { return startsWithIgnoreCase(path, candidate); } return path.indexOf(candidate) === 0; } interface IBaseFileStat { /** * The unified resource identifier of this file or folder. */ readonly resource: URI; /** * The name which is the last segment * of the {{path}}. */ readonly name: string; /** * The size of the file. * * The value may or may not be resolved as * it is optional. */ readonly size?: number; /** * The last modification date represented as millis from unix epoch. * * The value may or may not be resolved as * it is optional. */ readonly mtime?: number; /** * The creation date represented as millis from unix epoch. * * The value may or may not be resolved as * it is optional. */ readonly ctime?: number; /** * A unique identifier thet represents the * current state of the file or directory. * * The value may or may not be resolved as * it is optional. */ readonly etag?: string; /** * The file is read-only. */ readonly readonly?: boolean; } export interface IBaseFileStatWithMetadata extends Required<IBaseFileStat> { } /** * A file resource with meta information and resolved children if any. */ export interface IFileStat extends IBaseFileStat { /** * The resource is a file. */ readonly isFile: boolean; /** * The resource is a directory. */ readonly isDirectory: boolean; /** * The resource is a symbolic link. Note: even when the * file is a symbolic link, you can test for `FileType.File` * and `FileType.Directory` to know the type of the target * the link points to. */ readonly isSymbolicLink: boolean; /** * The children of the file stat or undefined if none. */ children: IFileStat[] | undefined; } export interface IFileStatWithMetadata extends IFileStat, IBaseFileStatWithMetadata { readonly mtime: number; readonly ctime: number; readonly etag: string; readonly size: number; readonly readonly: boolean; readonly children: IFileStatWithMetadata[] | undefined; } export interface IFileStatResult { readonly stat?: IFileStat; readonly success: boolean; } export interface IFileStatResultWithMetadata extends IFileStatResult { readonly stat?: IFileStatWithMetadata; } export interface IFileStatWithPartialMetadata extends Omit<IFileStatWithMetadata, 'children'> { } export interface IFileContent extends IBaseFileStatWithMetadata { /** * The content of a file as buffer. */ readonly value: VSBuffer; } export interface IFileStreamContent extends IBaseFileStatWithMetadata { /** * The content of a file as stream. */ readonly value: VSBufferReadableStream; } export interface IBaseReadFileOptions extends IFileReadStreamOptions { /** * The optional etag parameter allows to return early from resolving the resource if * the contents on disk match the etag. This prevents accumulated reading of resources * that have been read already with the same etag. * It is the task of the caller to makes sure to handle this error case from the promise. */ readonly etag?: string; } export interface IReadFileStreamOptions extends IBaseReadFileOptions { } export interface IReadFileOptions extends IBaseReadFileOptions { /** * The optional `atomic` flag can be used to make sure * the `readFile` method is not running in parallel with * any `write` operations in the same process. * * Typically you should not need to use this flag but if * for example you are quickly reading a file right after * a file event occurred and the file changes a lot, there * is a chance that a read returns an empty or partial file * because a pending write has not finished yet. * * Note: this does not prevent the file from being written * to from a different process. If you need such atomic * operations, you better use a real database as storage. */ readonly atomic?: boolean; } export interface IWriteFileOptions { /** * The last known modification time of the file. This can be used to prevent dirty writes. */ readonly mtime?: number; /** * The etag of the file. This can be used to prevent dirty writes. */ readonly etag?: string; /** * Whether to attempt to unlock a file before writing. */ readonly unlock?: boolean; } export interface IResolveFileOptions { /** * Automatically continue resolving children of a directory until the provided resources * are found. */ readonly resolveTo?: readonly URI[]; /** * Automatically continue resolving children of a directory if the number of children is 1. */ readonly resolveSingleChildDescendants?: boolean; /** * Will resolve mtime, ctime, size and etag of files if enabled. This can have a negative impact * on performance and thus should only be used when these values are required. */ readonly resolveMetadata?: boolean; } export interface IResolveMetadataFileOptions extends IResolveFileOptions { readonly resolveMetadata: true; } export interface ICreateFileOptions { /** * Overwrite the file to create if it already exists on disk. Otherwise * an error will be thrown (FILE_MODIFIED_SINCE). */ readonly overwrite?: boolean; } export class FileOperationError extends ErrorNoTelemetry { constructor( message: string, readonly fileOperationResult: FileOperationResult, readonly options?: IReadFileOptions & IWriteFileOptions & ICreateFileOptions ) { super(message); } } export class NotModifiedSinceFileOperationError extends FileOperationError { constructor( message: string, readonly stat: IFileStatWithMetadata, options?: IReadFileOptions ) { super(message, FileOperationResult.FILE_NOT_MODIFIED_SINCE, options); } } export const enum FileOperationResult { FILE_IS_DIRECTORY, FILE_NOT_FOUND, FILE_NOT_MODIFIED_SINCE, FILE_MODIFIED_SINCE, FILE_MOVE_CONFLICT, FILE_WRITE_LOCKED, FILE_PERMISSION_DENIED, FILE_TOO_LARGE, FILE_INVALID_PATH, FILE_EXCEEDS_MEMORY_LIMIT, FILE_NOT_DIRECTORY, FILE_OTHER_ERROR } //#endregion //#region Settings export const AutoSaveConfiguration = { OFF: 'off', AFTER_DELAY: 'afterDelay', ON_FOCUS_CHANGE: 'onFocusChange', ON_WINDOW_CHANGE: 'onWindowChange' }; export const HotExitConfiguration = { OFF: 'off', ON_EXIT: 'onExit', ON_EXIT_AND_WINDOW_CLOSE: 'onExitAndWindowClose' }; export const FILES_ASSOCIATIONS_CONFIG = 'files.associations'; export const FILES_EXCLUDE_CONFIG = 'files.exclude'; export interface IFilesConfiguration { files: { associations: { [filepattern: string]: string }; exclude: IExpression; watcherExclude: { [filepattern: string]: boolean }; watcherInclude: string[]; encoding: string; autoGuessEncoding: boolean; defaultLanguage: string; trimTrailingWhitespace: boolean; autoSave: string; autoSaveDelay: number; eol: string; enableTrash: boolean; hotExit: string; saveConflictResolution: 'askUser' | 'overwriteFileOnDisk'; }; } //#endregion //#region Utilities export enum FileKind { FILE, FOLDER, ROOT_FOLDER } /** * A hint to disable etag checking for reading/writing. */ export const ETAG_DISABLED = ''; export function etag(stat: { mtime: number; size: number }): string; export function etag(stat: { mtime: number | undefined; size: number | undefined }): string | undefined; export function etag(stat: { mtime: number | undefined; size: number | undefined }): string | undefined { if (typeof stat.size !== 'number' || typeof stat.mtime !== 'number') { return undefined; } return stat.mtime.toString(29) + stat.size.toString(31); } export async function whenProviderRegistered(file: URI, fileService: IFileService): Promise<void> { if (fileService.hasProvider(URI.from({ scheme: file.scheme }))) { return; } return new Promise(resolve => { const disposable = fileService.onDidChangeFileSystemProviderRegistrations(e => { if (e.scheme === file.scheme && e.added) { disposable.dispose(); resolve(); } }); }); } /** * Native only: limits for memory sizes */ export const MIN_MAX_MEMORY_SIZE_MB = 2048; export const FALLBACK_MAX_MEMORY_SIZE_MB = 4096; /** * Helper to format a raw byte size into a human readable label. */ export class ByteSize { static readonly KB = 1024; static readonly MB = ByteSize.KB * ByteSize.KB; static readonly GB = ByteSize.MB * ByteSize.KB; static readonly TB = ByteSize.GB * ByteSize.KB; static formatSize(size: number): string { if (!isNumber(size)) { size = 0; } if (size < ByteSize.KB) { return localize('sizeB', "{0}B", size.toFixed(0)); } if (size < ByteSize.MB) { return localize('sizeKB', "{0}KB", (size / ByteSize.KB).toFixed(2)); } if (size < ByteSize.GB) { return localize('sizeMB', "{0}MB", (size / ByteSize.MB).toFixed(2)); } if (size < ByteSize.TB) { return localize('sizeGB', "{0}GB", (size / ByteSize.GB).toFixed(2)); } return localize('sizeTB', "{0}TB", (size / ByteSize.TB).toFixed(2)); } } // Native only: Arch limits export interface IArchLimits { readonly maxFileSize: number; readonly maxHeapSize: number; } export const enum Arch { IA32, OTHER } export function getPlatformLimits(arch: Arch): IArchLimits { return { maxFileSize: arch === Arch.IA32 ? 300 * ByteSize.MB : 16 * ByteSize.GB, // https://github.com/microsoft/vscode/issues/30180 maxHeapSize: arch === Arch.IA32 ? 700 * ByteSize.MB : 2 * 700 * ByteSize.MB, // https://github.com/v8/v8/blob/5918a23a3d571b9625e5cce246bdd5b46ff7cd8b/src/heap/heap.cc#L149 }; } //#endregion
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview A jQueryUI plugin that displays the location of an aircraft for the reports. */ namespace VRS { /* * Global options */ export var globalOptions: GlobalOptions = VRS.globalOptions || {}; VRS.globalOptions.reportMapClass = VRS.globalOptions.reportMapClass || 'reportMap'; // The class to use for the map widget container. VRS.globalOptions.reportMapScrollToAircraft = VRS.globalOptions.reportMapScrollToAircraft !== undefined ? VRS.globalOptions.reportMapScrollToAircraft : true; // True if the map should automatically scroll to show the selected aircraft's path. VRS.globalOptions.reportMapShowPath = VRS.globalOptions.reportMapShowPath !== undefined ? VRS.globalOptions.reportMapShowPath : true; // True if a line should be drawn between the start and end points of the aircraft's path. VRS.globalOptions.reportMapStartSelected = VRS.globalOptions.reportMapStartSelected !== undefined ? VRS.globalOptions.reportMapStartSelected : false; // True if the start point should be displayed in the selected colours, false if the end point should show in selected colours. /** * Report map plugin options */ export interface ReportMapPlugin_Options { /** * The name to save state under. */ name?: string; /** * The report whose flights we're going to display. If no report is supplied then aircraft must be manually rendered, if it's supplied then it renders them automatically. */ report?: Report; /** * The mandatory plotter options to use when plotting aircraft. */ plotterOptions: AircraftPlotterOptions; /** * Additional classes to add to the element. */ elementClasses?: string; /** * The unit display preferences to use when displaying the marker. */ unitDisplayPreferences: UnitDisplayPreferences; /** * Overrides to apply to the map. */ mapOptionOverrides?: IMapOptions; /** * A list of controls to add to the map. */ mapControls?: IMapControl[]; /** * True if the map should automatically scroll to show the aircraft's path. */ scrollToAircraft?: boolean; /** * True if a line should be drawn between the start and end points of the aircraft's path. */ showPath?: boolean; /** * True if the start point should be shown in selected colours, false if the end point is shown in selected colours. */ startSelected?: boolean; /** * Called once the map has been loaded. */ loadedCallback?: () => void; } /** * The state carried by the ReportMapPlugin plugin. */ class ReportMapPlugin_State { /** * The element that contains the map. */ mapContainer: JQuery = null; /** * The direct reference to the map plugin. */ mapPlugin: IMap = null; /** * The plotter that this object uses to draw aircraft onto the map. */ aircraftPlotter: AircraftPlotter = null; /** * The list of aircraft that we plot onto the map. It's just the same aircraft twice - once for the marker on * the start position and once for the marker on the end position. */ aircraftList: AircraftCollection = new VRS.AircraftCollection(); /** * The next aircraft ID to assign to a fake VRS.Aircraft object. */ nextAircraftId: number = 1; /** * The ID in the aircraft list of the fake VRS.Aircraft for the first marker to show for the aircraft. */ firstPositionAircraftId: number = 0; /** * The ID in the aircraft list of the fake VRS.Aircraft for the last marker to show for the aircraft. */ lastPositionAircraftId: number = 0; /** * The flight to display to the user, if any. */ selectedFlight: IReportFlight = null; /** * The entry in the aircraft list that pertains to the "selected" aircraft, i.e. the one we show in selected * colours. The end marker is always shown in selected colours. */ selectedAircraft: Aircraft = null; /** * The hook result for the selected flight changed event. */ selectedFlightChangedHookResult: IEventHandle = null; /** * The hook result for the locale changed event. */ localeChangedHookResult: IEventHandle = null; } /* * jQueryUIHelper methods */ export var jQueryUIHelper: JQueryUIHelper = VRS.jQueryUIHelper || {}; VRS.jQueryUIHelper.getReportMapPlugin = function(jQueryElement: JQuery) : ReportMapPlugin { return jQueryElement.data('vrsVrsReportMap'); } VRS.jQueryUIHelper.getReportMapOptions = function(overrides?: ReportMapPlugin_Options) : ReportMapPlugin_Options { return $.extend(<ReportMapPlugin_Options> { name: 'default', report: null, plotterOptions: null, elementClasses: '', unitDisplayPreferences: undefined, mapOptionOverrides: {}, mapControls: [], scrollToAircraft: VRS.globalOptions.reportMapScrollToAircraft, showPath: VRS.globalOptions.reportMapShowPath, startSelected: VRS.globalOptions.reportMapStartSelected, loadedCallback: $.noop }, overrides); } /** * A jQuery widget that can display a single aircraft's location on a map for a report. */ export class ReportMapPlugin extends JQueryUICustomWidget { options: ReportMapPlugin_Options; constructor() { super(); this.options = VRS.jQueryUIHelper.getReportMapOptions(); } private _getState() : ReportMapPlugin_State { var result = this.element.data('reportMapState'); if(result === undefined) { result = new ReportMapPlugin_State(); this.element.data('reportMapState', result); } return result; } _create() { var state = this._getState(); var options = this.options; this.element.addClass(VRS.globalOptions.reportMapClass); if(options.elementClasses) { this.element.addClass(options.elementClasses); } this._createMap(state); } _destroy() { var state = this._getState(); var options = this.options; if(state.selectedFlightChangedHookResult && options.report) { options.report.unhook(state.selectedFlightChangedHookResult); } state.selectedFlightChangedHookResult = null; if(state.localeChangedHookResult && VRS.globalisation) { VRS.globalisation.unhook(state.localeChangedHookResult); } state.localeChangedHookResult = null; if(state.aircraftPlotter) { state.aircraftPlotter.dispose(); } state.aircraftPlotter = null; if(state.mapPlugin) { state.mapPlugin.destroy(); } if(state.mapContainer) { state.mapContainer.remove(); } state.mapPlugin = state.mapContainer = null; this.element.removeClass(VRS.globalOptions.reportMapClass); } isOpen() : boolean { var state = this._getState(); return state.mapPlugin && state.mapPlugin.isOpen(); } getMapWrapper() : IMap { var state = this._getState(); return state.mapPlugin; } /** * Creates the map container and populates it with a map. */ private _createMap(state: ReportMapPlugin_State) { var options = this.options; if(options.report) { state.selectedFlightChangedHookResult = options.report.hookSelectedFlightCHanged(this._selectedFlightChanged, this); } var mapOptions: IMapOptions = { name: 'report-' + options.name, scrollwheel: true, draggable: !VRS.globalOptions.isMobile, useServerDefaults: true, loadMarkerWithLabel: true, loadMarkerCluster: false, autoSaveState: true, useStateOnOpen: true, mapControls: options.mapControls, controlStyle: VRS.MapControlStyle.DropdownMenu }; $.extend(mapOptions, options.mapOptionOverrides); mapOptions.afterOpen = $.proxy(this._mapCreated, this); state.mapContainer = $('<div/>') .appendTo(this.element); state.mapContainer.vrsMap(VRS.jQueryUIHelper.getMapOptions(mapOptions)); } private _mapCreated() { var state = this._getState(); var options = this.options; // It is possible for this to get called on an object that has been destroyed and resurrected. We can detect // when this happens - the container will no longer exist. if(state.mapContainer) { state.mapPlugin = VRS.jQueryUIHelper.getMapPlugin(state.mapContainer); if(!state.mapPlugin.isOpen()) { if(options.mapControls) { $.each(options.mapControls, function(idx, control) { state.mapContainer.children().first().prepend(control.control); }); } } else { state.aircraftPlotter = new VRS.AircraftPlotter({ plotterOptions: options.plotterOptions, map: state.mapContainer, unitDisplayPreferences: options.unitDisplayPreferences, getAircraft: () => this._getAircraft(), getSelectedAircraft: () => this._getSelectedAircraft(), getCustomPinTexts: function(aircraft: Aircraft) { return [ aircraft.id === state.firstPositionAircraftId ? VRS.$$.Start : VRS.$$.End ]; } }); } VRS.globalisation.hookLocaleChanged(this._localeChanged, this); } if(options.loadedCallback) { options.loadedCallback(); } } /** * Constructs a list of aircraft for the selected flight. It is this list that the plotter will end up showing * as markers on the map. The list can only have two entries at most - both for the same aircraft, the first * shows the start position and the second shows its final position. To distinguish between the two "aircraft" * they are given different IDs - ID 1 is the start position of the aircraft, ID 2 is the end position. */ private _buildFakeVrsAircraft(state: ReportMapPlugin_State) { var options = this.options; state.aircraftList = new VRS.AircraftCollection(); state.selectedAircraft = null; var flight = state.selectedFlight; if(flight && ((flight.fLat && flight.fLng) || (flight.lLat && flight.lLng))) { var first = null, last = null; if(flight.fLat && flight.fLng) { first = VRS.Report.convertFlightToVrsAircraft(flight, true); first.id = state.firstPositionAircraftId = state.nextAircraftId++; state.aircraftList[first.id] = first; } if(flight.lLat && flight.lLng) { last = VRS.Report.convertFlightToVrsAircraft(flight, false); last.id = state.lastPositionAircraftId = state.nextAircraftId++; state.aircraftList[last.id] = last; } state.selectedAircraft = options.startSelected ? first : last; if(options.showPath && first && last) { last.fullTrail.arr.push(new VRS.FullTrailValue(first.latitude.val, first.longitude.val, first.heading.val, first.altitude.val, first.speed.val)); last.fullTrail.arr.push(new VRS.FullTrailValue(last.latitude.val, last.longitude.val, last.heading.val, last.altitude.val, last.speed.val)); } } } /** * Returns a collection of aircraft to plot on the map. See _buildFakeVrsAircraft. */ private _getAircraft() : AircraftCollection { var state = this._getState(); return state.aircraftList; } /** * Returns the aircraft to paint in selected colours. See _buildFakeVrsAircraft. */ private _getSelectedAircraft() : Aircraft { var state = this._getState(); return state.selectedAircraft; } /** * Called when the user chooses another language. */ private _localeChanged() { var state = this._getState(); if(state.aircraftPlotter) { state.aircraftPlotter.plot(true, true); } } /** * Called when the report indicates that the selected flight has been changed. */ private _selectedFlightChanged() { this.showFlight(this.options.report.getSelectedFlight()); } /** * Shows the flight's details on the map. */ showFlight(flight: IReportFlight) { var state = this._getState(); state.selectedFlight = flight; var options = this.options; this._buildFakeVrsAircraft(state); var applyWhenReady = function() { var map = state.aircraftPlotter ? state.aircraftPlotter.getMap() : null; if(!map || !map.isReady()) { setTimeout(applyWhenReady, 100); } else { var fromAircraft = state.aircraftList.findAircraftById(state.firstPositionAircraftId); var toAircraft = fromAircraft ? state.aircraftList.findAircraftById(state.lastPositionAircraftId) : null; if(options.scrollToAircraft && (fromAircraft || toAircraft)) { if(fromAircraft.hasPosition() && toAircraft.hasPosition() && (fromAircraft.latitude.val !== toAircraft.latitude.val || fromAircraft.longitude.val !== toAircraft.longitude.val)) { var bounds = VRS.greatCircle.arrangeTwoPointsIntoBounds( !fromAircraft ? null : { lat: fromAircraft.latitude.val, lng: fromAircraft.longitude.val }, !toAircraft ? null : { lat: toAircraft.latitude.val, lng: toAircraft.longitude.val } ); if(bounds) { map.fitBounds(bounds); } } else if(fromAircraft.hasPosition()) { map.panTo(fromAircraft.getPosition()); } else if(toAircraft.hasPosition()) { map.panTo(toAircraft.getPosition()); } } state.aircraftPlotter.plot(true, true); } }; applyWhenReady(); } } $.widget('vrs.vrsReportMap', new ReportMapPlugin()); } declare interface JQuery { vrsReportMap(); vrsReportMap(options: VRS.ReportMapPlugin_Options); vrsReportMap(methodName: string, param1?: any, param2?: any, param3?: any, param4?: any); }
the_stack
import { CancellationToken } from 'vs/base/common/cancellation'; import { Color } from 'vs/base/common/color'; import { IDisposable } from 'vs/base/common/lifecycle'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import * as model from 'vs/editor/common/model'; import * as languages from 'vs/editor/common/languages'; import { LanguageConfiguration } from 'vs/editor/common/languages/languageConfiguration'; import { ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry'; import { ModesRegistry } from 'vs/editor/common/languages/modesRegistry'; import { ILanguageExtensionPoint, ILanguageService } from 'vs/editor/common/languages/language'; import * as standaloneEnums from 'vs/editor/common/standalone/standaloneEnums'; import { StandaloneServices } from 'vs/editor/standalone/browser/standaloneServices'; import { compile } from 'vs/editor/standalone/common/monarch/monarchCompile'; import { MonarchTokenizer } from 'vs/editor/standalone/common/monarch/monarchLexer'; import { IMonarchLanguage } from 'vs/editor/standalone/common/monarch/monarchTypes'; import { IStandaloneThemeService } from 'vs/editor/standalone/common/standaloneTheme'; import { IMarkerData, IMarkerService } from 'vs/platform/markers/common/markers'; import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures'; import { LanguageSelector } from 'vs/editor/common/languageSelector'; /** * Register information about a new language. */ export function register(language: ILanguageExtensionPoint): void { // Intentionally using the `ModesRegistry` here to avoid // instantiating services too quickly in the standalone editor. ModesRegistry.registerLanguage(language); } /** * Get the information of all the registered languages. */ export function getLanguages(): ILanguageExtensionPoint[] { let result: ILanguageExtensionPoint[] = []; result = result.concat(ModesRegistry.getLanguages()); return result; } export function getEncodedLanguageId(languageId: string): number { const languageService = StandaloneServices.get(ILanguageService); return languageService.languageIdCodec.encodeLanguageId(languageId); } /** * An event emitted when a language is needed for the first time (e.g. a model has it set). * @event */ export function onLanguage(languageId: string, callback: () => void): IDisposable { const languageService = StandaloneServices.get(ILanguageService); const disposable = languageService.onDidEncounterLanguage((encounteredLanguageId) => { if (encounteredLanguageId === languageId) { // stop listening disposable.dispose(); // invoke actual listener callback(); } }); return disposable; } /** * Set the editing configuration for a language. */ export function setLanguageConfiguration(languageId: string, configuration: LanguageConfiguration): IDisposable { const languageService = StandaloneServices.get(ILanguageService); if (!languageService.isRegisteredLanguageId(languageId)) { throw new Error(`Cannot set configuration for unknown language ${languageId}`); } const languageConfigurationService = StandaloneServices.get(ILanguageConfigurationService); return languageConfigurationService.register(languageId, configuration, 100); } /** * @internal */ export class EncodedTokenizationSupportAdapter implements languages.ITokenizationSupport { private readonly _languageId: string; private readonly _actual: EncodedTokensProvider; constructor(languageId: string, actual: EncodedTokensProvider) { this._languageId = languageId; this._actual = actual; } public getInitialState(): languages.IState { return this._actual.getInitialState(); } public tokenize(line: string, hasEOL: boolean, state: languages.IState): languages.TokenizationResult { if (typeof this._actual.tokenize === 'function') { return TokenizationSupportAdapter.adaptTokenize(this._languageId, <{ tokenize(line: string, state: languages.IState): ILineTokens }>this._actual, line, state); } throw new Error('Not supported!'); } public tokenizeEncoded(line: string, hasEOL: boolean, state: languages.IState): languages.EncodedTokenizationResult { const result = this._actual.tokenizeEncoded(line, state); return new languages.EncodedTokenizationResult(result.tokens, result.endState); } } /** * @internal */ export class TokenizationSupportAdapter implements languages.ITokenizationSupport { constructor( private readonly _languageId: string, private readonly _actual: TokensProvider, private readonly _languageService: ILanguageService, private readonly _standaloneThemeService: IStandaloneThemeService, ) { } public getInitialState(): languages.IState { return this._actual.getInitialState(); } private static _toClassicTokens(tokens: IToken[], language: string): languages.Token[] { const result: languages.Token[] = []; let previousStartIndex: number = 0; for (let i = 0, len = tokens.length; i < len; i++) { const t = tokens[i]; let startIndex = t.startIndex; // Prevent issues stemming from a buggy external tokenizer. if (i === 0) { // Force first token to start at first index! startIndex = 0; } else if (startIndex < previousStartIndex) { // Force tokens to be after one another! startIndex = previousStartIndex; } result[i] = new languages.Token(startIndex, t.scopes, language); previousStartIndex = startIndex; } return result; } public static adaptTokenize(language: string, actual: { tokenize(line: string, state: languages.IState): ILineTokens }, line: string, state: languages.IState): languages.TokenizationResult { const actualResult = actual.tokenize(line, state); const tokens = TokenizationSupportAdapter._toClassicTokens(actualResult.tokens, language); let endState: languages.IState; // try to save an object if possible if (actualResult.endState.equals(state)) { endState = state; } else { endState = actualResult.endState; } return new languages.TokenizationResult(tokens, endState); } public tokenize(line: string, hasEOL: boolean, state: languages.IState): languages.TokenizationResult { return TokenizationSupportAdapter.adaptTokenize(this._languageId, this._actual, line, state); } private _toBinaryTokens(languageIdCodec: languages.ILanguageIdCodec, tokens: IToken[]): Uint32Array { const languageId = languageIdCodec.encodeLanguageId(this._languageId); const tokenTheme = this._standaloneThemeService.getColorTheme().tokenTheme; const result: number[] = []; let resultLen = 0; let previousStartIndex: number = 0; for (let i = 0, len = tokens.length; i < len; i++) { const t = tokens[i]; const metadata = tokenTheme.match(languageId, t.scopes); if (resultLen > 0 && result[resultLen - 1] === metadata) { // same metadata continue; } let startIndex = t.startIndex; // Prevent issues stemming from a buggy external tokenizer. if (i === 0) { // Force first token to start at first index! startIndex = 0; } else if (startIndex < previousStartIndex) { // Force tokens to be after one another! startIndex = previousStartIndex; } result[resultLen++] = startIndex; result[resultLen++] = metadata; previousStartIndex = startIndex; } const actualResult = new Uint32Array(resultLen); for (let i = 0; i < resultLen; i++) { actualResult[i] = result[i]; } return actualResult; } public tokenizeEncoded(line: string, hasEOL: boolean, state: languages.IState): languages.EncodedTokenizationResult { const actualResult = this._actual.tokenize(line, state); const tokens = this._toBinaryTokens(this._languageService.languageIdCodec, actualResult.tokens); let endState: languages.IState; // try to save an object if possible if (actualResult.endState.equals(state)) { endState = state; } else { endState = actualResult.endState; } return new languages.EncodedTokenizationResult(tokens, endState); } } /** * A token. */ export interface IToken { startIndex: number; scopes: string; } /** * The result of a line tokenization. */ export interface ILineTokens { /** * The list of tokens on the line. */ tokens: IToken[]; /** * The tokenization end state. * A pointer will be held to this and the object should not be modified by the tokenizer after the pointer is returned. */ endState: languages.IState; } /** * The result of a line tokenization. */ export interface IEncodedLineTokens { /** * The tokens on the line in a binary, encoded format. Each token occupies two array indices. For token i: * - at offset 2*i => startIndex * - at offset 2*i + 1 => metadata * Meta data is in binary format: * - ------------------------------------------- * 3322 2222 2222 1111 1111 1100 0000 0000 * 1098 7654 3210 9876 5432 1098 7654 3210 * - ------------------------------------------- * bbbb bbbb bfff ffff ffFF FFTT LLLL LLLL * - ------------------------------------------- * - L = EncodedLanguageId (8 bits): Use `getEncodedLanguageId` to get the encoded ID of a language. * - T = StandardTokenType (2 bits): Other = 0, Comment = 1, String = 2, RegEx = 3. * - F = FontStyle (4 bits): None = 0, Italic = 1, Bold = 2, Underline = 4, Strikethrough = 8. * - f = foreground ColorId (9 bits) * - b = background ColorId (9 bits) * - The color value for each colorId is defined in IStandaloneThemeData.customTokenColors: * e.g. colorId = 1 is stored in IStandaloneThemeData.customTokenColors[1]. Color id = 0 means no color, * id = 1 is for the default foreground color, id = 2 for the default background. */ tokens: Uint32Array; /** * The tokenization end state. * A pointer will be held to this and the object should not be modified by the tokenizer after the pointer is returned. */ endState: languages.IState; } /** * A factory for token providers. */ export interface TokensProviderFactory { create(): languages.ProviderResult<TokensProvider | EncodedTokensProvider | IMonarchLanguage>; } /** * A "manual" provider of tokens. */ export interface TokensProvider { /** * The initial state of a language. Will be the state passed in to tokenize the first line. */ getInitialState(): languages.IState; /** * Tokenize a line given the state at the beginning of the line. */ tokenize(line: string, state: languages.IState): ILineTokens; } /** * A "manual" provider of tokens, returning tokens in a binary form. */ export interface EncodedTokensProvider { /** * The initial state of a language. Will be the state passed in to tokenize the first line. */ getInitialState(): languages.IState; /** * Tokenize a line given the state at the beginning of the line. */ tokenizeEncoded(line: string, state: languages.IState): IEncodedLineTokens; /** * Tokenize a line given the state at the beginning of the line. */ tokenize?(line: string, state: languages.IState): ILineTokens; } function isATokensProvider(provider: TokensProvider | EncodedTokensProvider | IMonarchLanguage): provider is TokensProvider | EncodedTokensProvider { return (typeof provider.getInitialState === 'function'); } function isEncodedTokensProvider(provider: TokensProvider | EncodedTokensProvider): provider is EncodedTokensProvider { return 'tokenizeEncoded' in provider; } function isThenable<T>(obj: any): obj is Thenable<T> { return obj && typeof obj.then === 'function'; } /** * Change the color map that is used for token colors. * Supported formats (hex): #RRGGBB, $RRGGBBAA, #RGB, #RGBA */ export function setColorMap(colorMap: string[] | null): void { const standaloneThemeService = StandaloneServices.get(IStandaloneThemeService); if (colorMap) { const result: Color[] = [null!]; for (let i = 1, len = colorMap.length; i < len; i++) { result[i] = Color.fromHex(colorMap[i]); } standaloneThemeService.setColorMapOverride(result); } else { standaloneThemeService.setColorMapOverride(null); } } /** * @internal */ function createTokenizationSupportAdapter(languageId: string, provider: TokensProvider | EncodedTokensProvider) { if (isEncodedTokensProvider(provider)) { return new EncodedTokenizationSupportAdapter(languageId, provider); } else { return new TokenizationSupportAdapter( languageId, provider, StandaloneServices.get(ILanguageService), StandaloneServices.get(IStandaloneThemeService), ); } } /** * Register a tokens provider factory for a language. This tokenizer will be exclusive with a tokenizer * set using `setTokensProvider` or one created using `setMonarchTokensProvider`, but will work together * with a tokens provider set using `registerDocumentSemanticTokensProvider` or `registerDocumentRangeSemanticTokensProvider`. */ export function registerTokensProviderFactory(languageId: string, factory: TokensProviderFactory): IDisposable { const adaptedFactory: languages.ITokenizationSupportFactory = { createTokenizationSupport: async (): Promise<languages.ITokenizationSupport | null> => { const result = await Promise.resolve(factory.create()); if (!result) { return null; } if (isATokensProvider(result)) { return createTokenizationSupportAdapter(languageId, result); } return new MonarchTokenizer(StandaloneServices.get(ILanguageService), StandaloneServices.get(IStandaloneThemeService), languageId, compile(languageId, result)); } }; return languages.TokenizationRegistry.registerFactory(languageId, adaptedFactory); } /** * Set the tokens provider for a language (manual implementation). This tokenizer will be exclusive * with a tokenizer created using `setMonarchTokensProvider`, or with `registerTokensProviderFactory`, * but will work together with a tokens provider set using `registerDocumentSemanticTokensProvider` * or `registerDocumentRangeSemanticTokensProvider`. */ export function setTokensProvider(languageId: string, provider: TokensProvider | EncodedTokensProvider | Thenable<TokensProvider | EncodedTokensProvider>): IDisposable { const languageService = StandaloneServices.get(ILanguageService); if (!languageService.isRegisteredLanguageId(languageId)) { throw new Error(`Cannot set tokens provider for unknown language ${languageId}`); } if (isThenable<TokensProvider | EncodedTokensProvider>(provider)) { return registerTokensProviderFactory(languageId, { create: () => provider }); } return languages.TokenizationRegistry.register(languageId, createTokenizationSupportAdapter(languageId, provider)); } /** * Set the tokens provider for a language (monarch implementation). This tokenizer will be exclusive * with a tokenizer set using `setTokensProvider`, or with `registerTokensProviderFactory`, but will * work together with a tokens provider set using `registerDocumentSemanticTokensProvider` or * `registerDocumentRangeSemanticTokensProvider`. */ export function setMonarchTokensProvider(languageId: string, languageDef: IMonarchLanguage | Thenable<IMonarchLanguage>): IDisposable { const create = (languageDef: IMonarchLanguage) => { return new MonarchTokenizer(StandaloneServices.get(ILanguageService), StandaloneServices.get(IStandaloneThemeService), languageId, compile(languageId, languageDef)); }; if (isThenable<IMonarchLanguage>(languageDef)) { return registerTokensProviderFactory(languageId, { create: () => languageDef }); } return languages.TokenizationRegistry.register(languageId, create(languageDef)); } /** * Register a reference provider (used by e.g. reference search). */ export function registerReferenceProvider(languageSelector: LanguageSelector, provider: languages.ReferenceProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.referenceProvider.register(languageSelector, provider); } /** * Register a rename provider (used by e.g. rename symbol). */ export function registerRenameProvider(languageSelector: LanguageSelector, provider: languages.RenameProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.renameProvider.register(languageSelector, provider); } /** * Register a signature help provider (used by e.g. parameter hints). */ export function registerSignatureHelpProvider(languageSelector: LanguageSelector, provider: languages.SignatureHelpProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.signatureHelpProvider.register(languageSelector, provider); } /** * Register a hover provider (used by e.g. editor hover). */ export function registerHoverProvider(languageSelector: LanguageSelector, provider: languages.HoverProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.hoverProvider.register(languageSelector, { provideHover: (model: model.ITextModel, position: Position, token: CancellationToken): Promise<languages.Hover | undefined> => { const word = model.getWordAtPosition(position); return Promise.resolve<languages.Hover | null | undefined>(provider.provideHover(model, position, token)).then((value): languages.Hover | undefined => { if (!value) { return undefined; } if (!value.range && word) { value.range = new Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn); } if (!value.range) { value.range = new Range(position.lineNumber, position.column, position.lineNumber, position.column); } return value; }); } }); } /** * Register a document symbol provider (used by e.g. outline). */ export function registerDocumentSymbolProvider(languageSelector: LanguageSelector, provider: languages.DocumentSymbolProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.documentSymbolProvider.register(languageSelector, provider); } /** * Register a document highlight provider (used by e.g. highlight occurrences). */ export function registerDocumentHighlightProvider(languageSelector: LanguageSelector, provider: languages.DocumentHighlightProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.documentHighlightProvider.register(languageSelector, provider); } /** * Register an linked editing range provider. */ export function registerLinkedEditingRangeProvider(languageSelector: LanguageSelector, provider: languages.LinkedEditingRangeProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.linkedEditingRangeProvider.register(languageSelector, provider); } /** * Register a definition provider (used by e.g. go to definition). */ export function registerDefinitionProvider(languageSelector: LanguageSelector, provider: languages.DefinitionProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.definitionProvider.register(languageSelector, provider); } /** * Register a implementation provider (used by e.g. go to implementation). */ export function registerImplementationProvider(languageSelector: LanguageSelector, provider: languages.ImplementationProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.implementationProvider.register(languageSelector, provider); } /** * Register a type definition provider (used by e.g. go to type definition). */ export function registerTypeDefinitionProvider(languageSelector: LanguageSelector, provider: languages.TypeDefinitionProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.typeDefinitionProvider.register(languageSelector, provider); } /** * Register a code lens provider (used by e.g. inline code lenses). */ export function registerCodeLensProvider(languageSelector: LanguageSelector, provider: languages.CodeLensProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.codeLensProvider.register(languageSelector, provider); } /** * Register a code action provider (used by e.g. quick fix). */ export function registerCodeActionProvider(languageSelector: LanguageSelector, provider: CodeActionProvider, metadata?: CodeActionProviderMetadata): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.codeActionProvider.register(languageSelector, { providedCodeActionKinds: metadata?.providedCodeActionKinds, provideCodeActions: (model: model.ITextModel, range: Range, context: languages.CodeActionContext, token: CancellationToken): languages.ProviderResult<languages.CodeActionList> => { const markerService = StandaloneServices.get(IMarkerService); const markers = markerService.read({ resource: model.uri }).filter(m => { return Range.areIntersectingOrTouching(m, range); }); return provider.provideCodeActions(model, range, { markers, only: context.only }, token); }, resolveCodeAction: provider.resolveCodeAction }); } /** * Register a formatter that can handle only entire models. */ export function registerDocumentFormattingEditProvider(languageSelector: LanguageSelector, provider: languages.DocumentFormattingEditProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.documentFormattingEditProvider.register(languageSelector, provider); } /** * Register a formatter that can handle a range inside a model. */ export function registerDocumentRangeFormattingEditProvider(languageSelector: LanguageSelector, provider: languages.DocumentRangeFormattingEditProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.documentRangeFormattingEditProvider.register(languageSelector, provider); } /** * Register a formatter than can do formatting as the user types. */ export function registerOnTypeFormattingEditProvider(languageSelector: LanguageSelector, provider: languages.OnTypeFormattingEditProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.onTypeFormattingEditProvider.register(languageSelector, provider); } /** * Register a link provider that can find links in text. */ export function registerLinkProvider(languageSelector: LanguageSelector, provider: languages.LinkProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.linkProvider.register(languageSelector, provider); } /** * Register a completion item provider (use by e.g. suggestions). */ export function registerCompletionItemProvider(languageSelector: LanguageSelector, provider: languages.CompletionItemProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.completionProvider.register(languageSelector, provider); } /** * Register a document color provider (used by Color Picker, Color Decorator). */ export function registerColorProvider(languageSelector: LanguageSelector, provider: languages.DocumentColorProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.colorProvider.register(languageSelector, provider); } /** * Register a folding range provider */ export function registerFoldingRangeProvider(languageSelector: LanguageSelector, provider: languages.FoldingRangeProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.foldingRangeProvider.register(languageSelector, provider); } /** * Register a declaration provider */ export function registerDeclarationProvider(languageSelector: LanguageSelector, provider: languages.DeclarationProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.declarationProvider.register(languageSelector, provider); } /** * Register a selection range provider */ export function registerSelectionRangeProvider(languageSelector: LanguageSelector, provider: languages.SelectionRangeProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.selectionRangeProvider.register(languageSelector, provider); } /** * Register a document semantic tokens provider. A semantic tokens provider will complement and enhance a * simple top-down tokenizer. Simple top-down tokenizers can be set either via `setMonarchTokensProvider` * or `setTokensProvider`. * * For the best user experience, register both a semantic tokens provider and a top-down tokenizer. */ export function registerDocumentSemanticTokensProvider(languageSelector: LanguageSelector, provider: languages.DocumentSemanticTokensProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.documentSemanticTokensProvider.register(languageSelector, provider); } /** * Register a document range semantic tokens provider. A semantic tokens provider will complement and enhance a * simple top-down tokenizer. Simple top-down tokenizers can be set either via `setMonarchTokensProvider` * or `setTokensProvider`. * * For the best user experience, register both a semantic tokens provider and a top-down tokenizer. */ export function registerDocumentRangeSemanticTokensProvider(languageSelector: LanguageSelector, provider: languages.DocumentRangeSemanticTokensProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.documentRangeSemanticTokensProvider.register(languageSelector, provider); } /** * Register an inline completions provider. */ export function registerInlineCompletionsProvider(languageSelector: LanguageSelector, provider: languages.InlineCompletionsProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.inlineCompletionsProvider.register(languageSelector, provider); } /** * Register an inlay hints provider. */ export function registerInlayHintsProvider(languageSelector: LanguageSelector, provider: languages.InlayHintsProvider): IDisposable { const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService); return languageFeaturesService.inlayHintsProvider.register(languageSelector, provider); } /** * Contains additional diagnostic information about the context in which * a [code action](#CodeActionProvider.provideCodeActions) is run. */ export interface CodeActionContext { /** * An array of diagnostics. */ readonly markers: IMarkerData[]; /** * Requested kind of actions to return. */ readonly only?: string; } /** * The code action interface defines the contract between extensions and * the [light bulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) feature. */ export interface CodeActionProvider { /** * Provide commands for the given document and range. */ provideCodeActions(model: model.ITextModel, range: Range, context: CodeActionContext, token: CancellationToken): languages.ProviderResult<languages.CodeActionList>; /** * Given a code action fill in the edit. Will only invoked when missing. */ resolveCodeAction?(codeAction: languages.CodeAction, token: CancellationToken): languages.ProviderResult<languages.CodeAction>; } /** * Metadata about the type of code actions that a {@link CodeActionProvider} provides. */ export interface CodeActionProviderMetadata { /** * List of code action kinds that a {@link CodeActionProvider} may return. * * This list is used to determine if a given `CodeActionProvider` should be invoked or not. * To avoid unnecessary computation, every `CodeActionProvider` should list use `providedCodeActionKinds`. The * list of kinds may either be generic, such as `["quickfix", "refactor", "source"]`, or list out every kind provided, * such as `["quickfix.removeLine", "source.fixAll" ...]`. */ readonly providedCodeActionKinds?: readonly string[]; } /** * @internal */ export function createMonacoLanguagesAPI(): typeof monaco.languages { return { register: <any>register, getLanguages: <any>getLanguages, onLanguage: <any>onLanguage, getEncodedLanguageId: <any>getEncodedLanguageId, // provider methods setLanguageConfiguration: <any>setLanguageConfiguration, setColorMap: setColorMap, registerTokensProviderFactory: <any>registerTokensProviderFactory, setTokensProvider: <any>setTokensProvider, setMonarchTokensProvider: <any>setMonarchTokensProvider, registerReferenceProvider: <any>registerReferenceProvider, registerRenameProvider: <any>registerRenameProvider, registerCompletionItemProvider: <any>registerCompletionItemProvider, registerSignatureHelpProvider: <any>registerSignatureHelpProvider, registerHoverProvider: <any>registerHoverProvider, registerDocumentSymbolProvider: <any>registerDocumentSymbolProvider, registerDocumentHighlightProvider: <any>registerDocumentHighlightProvider, registerLinkedEditingRangeProvider: <any>registerLinkedEditingRangeProvider, registerDefinitionProvider: <any>registerDefinitionProvider, registerImplementationProvider: <any>registerImplementationProvider, registerTypeDefinitionProvider: <any>registerTypeDefinitionProvider, registerCodeLensProvider: <any>registerCodeLensProvider, registerCodeActionProvider: <any>registerCodeActionProvider, registerDocumentFormattingEditProvider: <any>registerDocumentFormattingEditProvider, registerDocumentRangeFormattingEditProvider: <any>registerDocumentRangeFormattingEditProvider, registerOnTypeFormattingEditProvider: <any>registerOnTypeFormattingEditProvider, registerLinkProvider: <any>registerLinkProvider, registerColorProvider: <any>registerColorProvider, registerFoldingRangeProvider: <any>registerFoldingRangeProvider, registerDeclarationProvider: <any>registerDeclarationProvider, registerSelectionRangeProvider: <any>registerSelectionRangeProvider, registerDocumentSemanticTokensProvider: <any>registerDocumentSemanticTokensProvider, registerDocumentRangeSemanticTokensProvider: <any>registerDocumentRangeSemanticTokensProvider, registerInlineCompletionsProvider: <any>registerInlineCompletionsProvider, registerInlayHintsProvider: <any>registerInlayHintsProvider, // enums DocumentHighlightKind: standaloneEnums.DocumentHighlightKind, CompletionItemKind: standaloneEnums.CompletionItemKind, CompletionItemTag: standaloneEnums.CompletionItemTag, CompletionItemInsertTextRule: standaloneEnums.CompletionItemInsertTextRule, SymbolKind: standaloneEnums.SymbolKind, SymbolTag: standaloneEnums.SymbolTag, IndentAction: standaloneEnums.IndentAction, CompletionTriggerKind: standaloneEnums.CompletionTriggerKind, SignatureHelpTriggerKind: standaloneEnums.SignatureHelpTriggerKind, InlayHintKind: standaloneEnums.InlayHintKind, InlineCompletionTriggerKind: standaloneEnums.InlineCompletionTriggerKind, // classes FoldingRangeKind: languages.FoldingRangeKind, }; }
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * The properties of a DigitalTwinsInstance. */ export interface DigitalTwinsPatchProperties { /** * Public network access for the DigitalTwinsInstance. Possible values include: 'Enabled', * 'Disabled' */ publicNetworkAccess?: PublicNetworkAccess; } /** * The properties of a private endpoint connection. */ export interface ConnectionProperties { /** * The provisioning state. Possible values include: 'Pending', 'Approved', 'Rejected', * 'Disconnected' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: ConnectionPropertiesProvisioningState; privateEndpoint?: ConnectionPropertiesPrivateEndpoint; /** * The list of group ids for the private endpoint connection. */ groupIds?: string[]; privateLinkServiceConnectionState?: ConnectionPropertiesPrivateLinkServiceConnectionState; } /** * An interface representing PrivateEndpointConnectionProperties. */ export interface PrivateEndpointConnectionProperties extends ConnectionProperties { } /** * The private endpoint connection of a Digital Twin. */ export interface PrivateEndpointConnection extends BaseResource { /** * The resource identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; properties: PrivateEndpointConnectionProperties; } /** * The common properties of a DigitalTwinsInstance. */ export interface DigitalTwinsResource extends BaseResource { /** * The resource identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * The resource location. */ location: string; /** * The resource tags. */ tags?: { [propertyName: string]: string }; /** * The managed identity for the DigitalTwinsInstance. */ identity?: DigitalTwinsIdentity; } /** * The description of the DigitalTwins service. */ export interface DigitalTwinsDescription extends DigitalTwinsResource { /** * Time when DigitalTwinsInstance was created. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly createdTime?: Date; /** * Time when DigitalTwinsInstance was updated. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly lastUpdatedTime?: Date; /** * The provisioning state. Possible values include: 'Provisioning', 'Deleting', 'Updating', * 'Succeeded', 'Failed', 'Canceled', 'Deleted', 'Warning', 'Suspending', 'Restoring', 'Moving' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: ProvisioningState; /** * Api endpoint to work with DigitalTwinsInstance. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly hostName?: string; privateEndpointConnections?: PrivateEndpointConnection[]; /** * Public network access for the DigitalTwinsInstance. Possible values include: 'Enabled', * 'Disabled' */ publicNetworkAccess?: PublicNetworkAccess; } /** * The managed identity for the DigitalTwinsInstance. */ export interface DigitalTwinsIdentity { /** * The type of Managed Identity used by the DigitalTwinsInstance. Only SystemAssigned is * supported. Possible values include: 'None', 'SystemAssigned' */ type?: DigitalTwinsIdentityType; /** * The object id of the Managed Identity Resource. This will be sent to the RP from ARM via the * x-ms-identity-principal-id header in the PUT request if the resource has a * systemAssigned(implicit) identity * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly principalId?: string; /** * The tenant id of the Managed Identity Resource. This will be sent to the RP from ARM via the * x-ms-client-tenant-id header in the PUT request if the resource has a systemAssigned(implicit) * identity * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly tenantId?: string; } /** * The description of the DigitalTwins service. */ export interface DigitalTwinsPatchDescription { /** * Instance patch properties */ tags?: { [propertyName: string]: string }; /** * The managed identity for the DigitalTwinsInstance. */ identity?: DigitalTwinsIdentity; /** * Properties for the DigitalTwinsInstance. */ properties?: DigitalTwinsPatchProperties; } /** * Error definition. */ export interface ErrorDefinition { /** * Service specific error code which serves as the substatus for the HTTP error code. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly code?: string; /** * Description of the error. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly message?: string; /** * Internal error details. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly details?: ErrorDefinition[]; } /** * Error response. */ export interface ErrorResponse { /** * Error description */ error?: ErrorDefinition; } /** * The object that represents the operation. */ export interface OperationDisplay { /** * Service provider: Microsoft DigitalTwins * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provider?: string; /** * Resource Type: DigitalTwinsInstances * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly resource?: string; /** * Name of the operation * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly operation?: string; /** * Friendly description for the operation, * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; } /** * DigitalTwins service REST API operation */ export interface Operation { /** * Operation name: {provider}/{resource}/{read | write | action | delete} * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Operation properties display */ display?: OperationDisplay; /** * The intended executor of the operation. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly origin?: string; /** * If the operation is a data action (for data plane rbac). * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly isDataAction?: boolean; } /** * The result returned from a database check name availability request. */ export interface CheckNameRequest { /** * Resource name. */ name: string; } /** * The result returned from a check name availability request. */ export interface CheckNameResult { /** * Specifies a Boolean value that indicates if the name is available. */ nameAvailable?: boolean; /** * Message indicating an unavailable name due to a conflict, or a description of the naming rules * that are violated. */ message?: string; /** * Message providing the reason why the given name is invalid. Possible values include: * 'Invalid', 'AlreadyExists' */ reason?: Reason; } /** * Definition of a resource. */ export interface ExternalResource extends BaseResource { /** * The resource identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Extension resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; } /** * Contains the possible cases for DigitalTwinsEndpointResourceProperties. */ export type DigitalTwinsEndpointResourcePropertiesUnion = DigitalTwinsEndpointResourceProperties | ServiceBus | EventHub | EventGrid; /** * Properties related to Digital Twins Endpoint */ export interface DigitalTwinsEndpointResourceProperties { /** * Polymorphic Discriminator */ endpointType: "DigitalTwinsEndpointResourceProperties"; /** * The provisioning state. Possible values include: 'Provisioning', 'Deleting', 'Succeeded', * 'Failed', 'Canceled', 'Deleted', 'Warning', 'Suspending', 'Restoring', 'Moving', 'Disabled' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: EndpointProvisioningState; /** * Time when the Endpoint was added to DigitalTwinsInstance. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly createdTime?: Date; /** * Specifies the authentication type being used for connecting to the endpoint. Possible values * include: 'KeyBased', 'IdentityBased' */ authenticationType?: AuthenticationType; /** * Dead letter storage secret for key-based authentication. Will be obfuscated during read. */ deadLetterSecret?: string; /** * Dead letter storage URL for identity-based authentication. */ deadLetterUri?: string; } /** * DigitalTwinsInstance endpoint resource. */ export interface DigitalTwinsEndpointResource extends ExternalResource { /** * DigitalTwinsInstance endpoint resource properties. */ properties: DigitalTwinsEndpointResourcePropertiesUnion; } /** * Properties related to ServiceBus. */ export interface ServiceBus { /** * Polymorphic Discriminator */ endpointType: "ServiceBus"; /** * The provisioning state. Possible values include: 'Provisioning', 'Deleting', 'Succeeded', * 'Failed', 'Canceled', 'Deleted', 'Warning', 'Suspending', 'Restoring', 'Moving', 'Disabled' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: EndpointProvisioningState; /** * Time when the Endpoint was added to DigitalTwinsInstance. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly createdTime?: Date; /** * Specifies the authentication type being used for connecting to the endpoint. Possible values * include: 'KeyBased', 'IdentityBased' */ authenticationType?: AuthenticationType; /** * Dead letter storage secret for key-based authentication. Will be obfuscated during read. */ deadLetterSecret?: string; /** * Dead letter storage URL for identity-based authentication. */ deadLetterUri?: string; /** * PrimaryConnectionString of the endpoint for key-based authentication. Will be obfuscated * during read. */ primaryConnectionString?: string; /** * SecondaryConnectionString of the endpoint for key-based authentication. Will be obfuscated * during read. */ secondaryConnectionString?: string; /** * The URL of the ServiceBus namespace for identity-based authentication. It must include the * protocol sb:// */ endpointUri?: string; /** * The ServiceBus Topic name for identity-based authentication */ entityPath?: string; } /** * Properties related to EventHub. */ export interface EventHub { /** * Polymorphic Discriminator */ endpointType: "EventHub"; /** * The provisioning state. Possible values include: 'Provisioning', 'Deleting', 'Succeeded', * 'Failed', 'Canceled', 'Deleted', 'Warning', 'Suspending', 'Restoring', 'Moving', 'Disabled' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: EndpointProvisioningState; /** * Time when the Endpoint was added to DigitalTwinsInstance. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly createdTime?: Date; /** * Specifies the authentication type being used for connecting to the endpoint. Possible values * include: 'KeyBased', 'IdentityBased' */ authenticationType?: AuthenticationType; /** * Dead letter storage secret for key-based authentication. Will be obfuscated during read. */ deadLetterSecret?: string; /** * Dead letter storage URL for identity-based authentication. */ deadLetterUri?: string; /** * PrimaryConnectionString of the endpoint for key-based authentication. Will be obfuscated * during read. */ connectionStringPrimaryKey?: string; /** * SecondaryConnectionString of the endpoint for key-based authentication. Will be obfuscated * during read. */ connectionStringSecondaryKey?: string; /** * The URL of the EventHub namespace for identity-based authentication. It must include the * protocol sb:// */ endpointUri?: string; /** * The EventHub name in the EventHub namespace for identity-based authentication. */ entityPath?: string; } /** * Properties related to EventGrid. */ export interface EventGrid { /** * Polymorphic Discriminator */ endpointType: "EventGrid"; /** * The provisioning state. Possible values include: 'Provisioning', 'Deleting', 'Succeeded', * 'Failed', 'Canceled', 'Deleted', 'Warning', 'Suspending', 'Restoring', 'Moving', 'Disabled' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: EndpointProvisioningState; /** * Time when the Endpoint was added to DigitalTwinsInstance. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly createdTime?: Date; /** * Specifies the authentication type being used for connecting to the endpoint. Possible values * include: 'KeyBased', 'IdentityBased' */ authenticationType?: AuthenticationType; /** * Dead letter storage secret for key-based authentication. Will be obfuscated during read. */ deadLetterSecret?: string; /** * Dead letter storage URL for identity-based authentication. */ deadLetterUri?: string; /** * EventGrid Topic Endpoint */ topicEndpoint: string; /** * EventGrid secondary accesskey. Will be obfuscated during read. */ accessKey1: string; /** * EventGrid secondary accesskey. Will be obfuscated during read. */ accessKey2?: string; } /** * The properties for a group information object. */ export interface GroupIdInformationProperties { /** * The group id */ groupId?: string; /** * The required members for a specific group id. */ requiredMembers?: string[]; /** * The required DNS zones for a specific group id. */ requiredZoneNames?: string[]; } /** * An interface representing GroupIdInformationPropertiesModel. */ export interface GroupIdInformationPropertiesModel extends GroupIdInformationProperties { } /** * The group information for creating a private endpoint on Digital Twin. */ export interface GroupIdInformation { properties: GroupIdInformationPropertiesModel; /** * The resource identifier. */ id?: string; /** * The resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; } /** * The available private link connections for a Digital Twin. */ export interface PrivateEndpointConnectionsResponse { /** * The list of available private link connections for a Digital Twin. */ value?: PrivateEndpointConnection[]; } /** * The available private link resources for a Digital Twin. */ export interface GroupIdInformationResponse { /** * The list of available private link resources for a Digital Twin. */ value?: GroupIdInformation[]; } /** * The current state of a private endpoint connection. */ export interface ConnectionState { /** * The status of a private endpoint connection. Possible values include: 'Pending', 'Approved', * 'Rejected', 'Disconnected' */ status: PrivateLinkServiceConnectionStatus; /** * The description for the current state of a private endpoint connection. */ description: string; /** * Actions required for a private endpoint connection. */ actionsRequired?: string; } /** * The private endpoint property of a private endpoint connection. */ export interface PrivateEndpoint { /** * The resource identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; } /** * An interface representing ConnectionPropertiesPrivateEndpoint. */ export interface ConnectionPropertiesPrivateEndpoint extends PrivateEndpoint { } /** * An interface representing ConnectionPropertiesPrivateLinkServiceConnectionState. */ export interface ConnectionPropertiesPrivateLinkServiceConnectionState extends ConnectionState { } /** * An interface representing AzureDigitalTwinsManagementClientOptions. */ export interface AzureDigitalTwinsManagementClientOptions extends AzureServiceClientOptions { baseUri?: string; } /** * @interface * A list of DigitalTwins description objects with a next link. * @extends Array<DigitalTwinsDescription> */ export interface DigitalTwinsDescriptionListResult extends Array<DigitalTwinsDescription> { /** * The link used to get the next page of DigitalTwins description objects. */ nextLink?: string; } /** * @interface * A list of DigitalTwinsInstance Endpoints with a next link. * @extends Array<DigitalTwinsEndpointResource> */ export interface DigitalTwinsEndpointResourceListResult extends Array<DigitalTwinsEndpointResource> { /** * The link used to get the next page of DigitalTwinsInstance Endpoints. */ nextLink?: string; } /** * @interface * A list of DigitalTwins service operations. It contains a list of operations and a URL link to * get the next set of results. * @extends Array<Operation> */ export interface OperationListResult extends Array<Operation> { /** * The link used to get the next page of DigitalTwins description objects. */ nextLink?: string; } /** * Defines values for PublicNetworkAccess. * Possible values include: 'Enabled', 'Disabled' * @readonly * @enum {string} */ export type PublicNetworkAccess = 'Enabled' | 'Disabled'; /** * Defines values for ProvisioningState. * Possible values include: 'Provisioning', 'Deleting', 'Updating', 'Succeeded', 'Failed', * 'Canceled', 'Deleted', 'Warning', 'Suspending', 'Restoring', 'Moving' * @readonly * @enum {string} */ export type ProvisioningState = 'Provisioning' | 'Deleting' | 'Updating' | 'Succeeded' | 'Failed' | 'Canceled' | 'Deleted' | 'Warning' | 'Suspending' | 'Restoring' | 'Moving'; /** * Defines values for DigitalTwinsIdentityType. * Possible values include: 'None', 'SystemAssigned' * @readonly * @enum {string} */ export type DigitalTwinsIdentityType = 'None' | 'SystemAssigned'; /** * Defines values for Reason. * Possible values include: 'Invalid', 'AlreadyExists' * @readonly * @enum {string} */ export type Reason = 'Invalid' | 'AlreadyExists'; /** * Defines values for EndpointProvisioningState. * Possible values include: 'Provisioning', 'Deleting', 'Succeeded', 'Failed', 'Canceled', * 'Deleted', 'Warning', 'Suspending', 'Restoring', 'Moving', 'Disabled' * @readonly * @enum {string} */ export type EndpointProvisioningState = 'Provisioning' | 'Deleting' | 'Succeeded' | 'Failed' | 'Canceled' | 'Deleted' | 'Warning' | 'Suspending' | 'Restoring' | 'Moving' | 'Disabled'; /** * Defines values for AuthenticationType. * Possible values include: 'KeyBased', 'IdentityBased' * @readonly * @enum {string} */ export type AuthenticationType = 'KeyBased' | 'IdentityBased'; /** * Defines values for PrivateLinkServiceConnectionStatus. * Possible values include: 'Pending', 'Approved', 'Rejected', 'Disconnected' * @readonly * @enum {string} */ export type PrivateLinkServiceConnectionStatus = 'Pending' | 'Approved' | 'Rejected' | 'Disconnected'; /** * Defines values for ConnectionPropertiesProvisioningState. * Possible values include: 'Pending', 'Approved', 'Rejected', 'Disconnected' * @readonly * @enum {string} */ export type ConnectionPropertiesProvisioningState = 'Pending' | 'Approved' | 'Rejected' | 'Disconnected'; /** * Contains response data for the get operation. */ export type DigitalTwinsGetResponse = DigitalTwinsDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsDescription; }; }; /** * Contains response data for the createOrUpdate operation. */ export type DigitalTwinsCreateOrUpdateResponse = DigitalTwinsDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsDescription; }; }; /** * Contains response data for the update operation. */ export type DigitalTwinsUpdateResponse = DigitalTwinsDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsDescription; }; }; /** * Contains response data for the deleteMethod operation. */ export type DigitalTwinsDeleteMethodResponse = DigitalTwinsDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsDescription; }; }; /** * Contains response data for the list operation. */ export type DigitalTwinsListResponse = DigitalTwinsDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsDescriptionListResult; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type DigitalTwinsListByResourceGroupResponse = DigitalTwinsDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsDescriptionListResult; }; }; /** * Contains response data for the checkNameAvailability operation. */ export type DigitalTwinsCheckNameAvailabilityResponse = CheckNameResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CheckNameResult; }; }; /** * Contains response data for the beginCreateOrUpdate operation. */ export type DigitalTwinsBeginCreateOrUpdateResponse = DigitalTwinsDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsDescription; }; }; /** * Contains response data for the beginUpdate operation. */ export type DigitalTwinsBeginUpdateResponse = DigitalTwinsDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsDescription; }; }; /** * Contains response data for the beginDeleteMethod operation. */ export type DigitalTwinsBeginDeleteMethodResponse = DigitalTwinsDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsDescription; }; }; /** * Contains response data for the listNext operation. */ export type DigitalTwinsListNextResponse = DigitalTwinsDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsDescriptionListResult; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type DigitalTwinsListByResourceGroupNextResponse = DigitalTwinsDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsDescriptionListResult; }; }; /** * Contains response data for the list operation. */ export type DigitalTwinsEndpointListResponse = DigitalTwinsEndpointResourceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsEndpointResourceListResult; }; }; /** * Contains response data for the get operation. */ export type DigitalTwinsEndpointGetResponse = DigitalTwinsEndpointResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsEndpointResource; }; }; /** * Contains response data for the createOrUpdate operation. */ export type DigitalTwinsEndpointCreateOrUpdateResponse = DigitalTwinsEndpointResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsEndpointResource; }; }; /** * Contains response data for the deleteMethod operation. */ export type DigitalTwinsEndpointDeleteMethodResponse = DigitalTwinsEndpointResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsEndpointResource; }; }; /** * Contains response data for the beginCreateOrUpdate operation. */ export type DigitalTwinsEndpointBeginCreateOrUpdateResponse = DigitalTwinsEndpointResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsEndpointResource; }; }; /** * Contains response data for the beginDeleteMethod operation. */ export type DigitalTwinsEndpointBeginDeleteMethodResponse = DigitalTwinsEndpointResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsEndpointResource; }; }; /** * Contains response data for the listNext operation. */ export type DigitalTwinsEndpointListNextResponse = DigitalTwinsEndpointResourceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DigitalTwinsEndpointResourceListResult; }; }; /** * Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the list operation. */ export type PrivateLinkResourcesListResponse = GroupIdInformationResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: GroupIdInformationResponse; }; }; /** * Contains response data for the get operation. */ export type PrivateLinkResourcesGetResponse = GroupIdInformation & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: GroupIdInformation; }; }; /** * Contains response data for the list operation. */ export type PrivateEndpointConnectionsListResponse = PrivateEndpointConnectionsResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PrivateEndpointConnectionsResponse; }; }; /** * Contains response data for the get operation. */ export type PrivateEndpointConnectionsGetResponse = PrivateEndpointConnection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PrivateEndpointConnection; }; }; /** * Contains response data for the createOrUpdate operation. */ export type PrivateEndpointConnectionsCreateOrUpdateResponse = PrivateEndpointConnection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PrivateEndpointConnection; }; }; /** * Contains response data for the beginCreateOrUpdate operation. */ export type PrivateEndpointConnectionsBeginCreateOrUpdateResponse = PrivateEndpointConnection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PrivateEndpointConnection; }; };
the_stack
import OrderbookUtils from '../../src/lib/OrderbookUtils'; import { ZERO, Big } from '../../src/lib/types'; import createOrderbookUtils from './createOrderbookUtils'; import assert = require('assert'); describe('OrderbookUtils', () => { describe('objects', () => { let obu: OrderbookUtils = null; beforeEach(() => { const bids = [[100, 10, 1], [99, 5, 1], [98, 1, 1]]; const asks = [[110, 2, 1], [115, 1, 1], [120, 4, 10]]; obu = createOrderbookUtils(bids, asks); }); it('can calculate buy side stats when pre-cached', () => { const stats = obu.calculateMarketOrderStats('buy', 4, ZERO); assert(stats); assert.equal(stats.total_cost.toFixed(1), '455.0'); assert.equal(stats.ave_price.toFixed(2), '113.75'); assert.equal(stats.slippage.toFixed(4), '0.0341'); assert.equal(stats.unfilled.toFixed(4), '0.0000'); assert.equal(stats.first_price.toFixed(2), '110.00'); assert.equal(stats.last_price.toFixed(2), '120.00'); }); it('can calculate sell side stats when pre-cached', () => { const stats = obu.calculateMarketOrderStats('sell', 15.5); assert(stats); assert.equal(stats.total_cost.toFixed(1), '1544.0'); assert.equal(stats.ave_price.toFixed(2), '99.61'); assert.equal(stats.slippage.toFixed(5), '0.00387'); assert.equal(stats.unfilled.toFixed(4), '0.0000'); assert.equal(stats.first_price.toFixed(2), '100.00'); assert.equal(stats.last_price.toFixed(2), '98.00'); }); it('perfect fill case when pre-cached', () => { const stats = obu.calculateMarketOrderStats('sell', 15.0); assert(stats); assert.equal(stats.total_cost.toFixed(1), '1495.0'); assert.equal(stats.ave_price.toFixed(2), '99.67'); assert.equal(stats.slippage.toFixed(5), '0.00333'); assert.equal(stats.unfilled.toFixed(4), '0.0000'); assert.equal(stats.first_price.toFixed(2), '100.00'); assert.equal(stats.last_price.toFixed(2), '99.00'); }); it('can handle too-large orders when pre-cached', () => { const stats = obu.calculateMarketOrderStats('buy', 8); assert(stats); assert.equal(stats.total_cost.toFixed(1), '815.0'); assert.equal(stats.total_size.toFixed(1), '7.0'); assert.equal(stats.ave_price.toFixed(2), '116.43'); assert.equal(stats.slippage.toFixed(4), '0.0584'); assert.equal(stats.unfilled.toFixed(4), '1.0000'); assert.equal(stats.fees.toFixed(2), '0.00'); }); it('can handle zero-size orders when pre-cached', () => { const stats = obu.calculateMarketOrderStats('buy', 0); assert(stats); assert.equal(stats.total_cost.toFixed(1), '0.0'); assert.equal(stats.total_size.toFixed(1), '0.0'); assert.equal(stats.ave_price.toFixed(2), '110.00'); assert.equal(stats.slippage.toFixed(4), '0.0000'); assert.equal(stats.unfilled.toFixed(4), '0.0000'); assert.equal(stats.fees.toFixed(2), '0.00'); }); it('can determine fees when pre-cached', () => { const stats = obu.calculateMarketOrderStats('buy', 4, Big(0.001)); assert(stats); assert.equal(stats.total_cost.toFixed(3), '455.455'); assert.equal(stats.fees.toFixed(3), '0.455'); assert.equal(stats.ave_price.toFixed(3), '113.864'); assert.equal(stats.slippage.toFixed(6), '0.035125'); }); it('can calculate sum of order sizes up to index n', () => { assert.equal(+obu.getCumulativeSize(1, true), 3); assert.equal(+obu.getCumulativeSize(1, false), 15); assert.equal(+obu.getCumulativeSize(0, true), 2); assert.equal(+obu.getCumulativeSize(0, false), 10); assert.equal(+obu.getCumulativeSize(2, true), 7); assert.equal(+obu.getCumulativeSize(3, false), 16); }); it('can calculate sum of costs up to index n', () => { assert.equal(+obu.getCumulativeCost(1, true), 335); assert.equal(+obu.getCumulativeCost(1, false), 1495); assert.equal(+obu.getCumulativeCost(0, true), 220); assert.equal(+obu.getCumulativeCost(0, false), 1000); assert.equal(+obu.getCumulativeCost(2, true), 815); assert.equal(+obu.getCumulativeCost(3, false), 1593); }); }); describe('Partial sums of orderbooks', () => { let obu: OrderbookUtils = null; beforeEach(() => { const bids = [[100, 10, 1], [99, 5, 1], [98, 1, 1], [97, 3, 1]]; const asks = [[110, 2, 1], [115, 1, 1], [120, 4, 10], [125, 2, 3]]; obu = createOrderbookUtils(bids, asks); }); it('calculates sell stats between 10 and 15 BTC', () => { const stats = obu.integrateBetween(Big(10), Big(15), false, Big(0)); assert.equal(+stats.total_size, 5); assert.equal(+stats.first_price, 99); assert.equal(+stats.last_price, 99); assert.equal(+stats.total_cost, 495); assert.equal(+stats.unfilled, 0); }); it('calculates sell stats between 3 and 15.5 BTC', () => { const stats = obu.integrateBetween(Big(3), Big(15.5), false, Big(0)); assert.equal(+stats.total_size, 12.5); assert.equal(+stats.first_price, 100); assert.equal(+stats.last_price, 98); assert.equal(+stats.total_cost, 700 + 495 + 49); assert.equal(+stats.unfilled, 0); }); it('calculates sell stats between 10 and 10.1 BTC', () => { const stats = obu.integrateBetween(Big(10), Big(10.1), false, Big(0)); assert.equal(+stats.total_size, 0.1); assert.equal(+stats.first_price, 99); assert.equal(+stats.last_price, 99); assert.equal(+stats.total_cost, 9.9); assert.equal(+stats.unfilled, 0); }); it('calculates sell stats between 11 and 17 BTC', () => { const stats = obu.integrateBetween(Big(11), Big(17), false, Big(0)); assert.equal(+stats.total_size, 6); assert.equal(+stats.first_price, 99); assert.equal(+stats.last_price, 97); assert.equal(+stats.total_cost, 4 * 99 + 98 + 97); assert.equal(+stats.unfilled, 0); }); it('calculates sell stats between 11 and 17 BTC with fees', () => { const stats = obu.integrateBetween(Big(11), Big(17), false, Big(0.01)); assert.equal(+stats.total_size, 6); assert.equal(+stats.first_price, 99); assert.equal(+stats.last_price, 97); assert.equal(+stats.total_cost, (4 * 99 + 98 + 97) * 1.01); assert.equal(+stats.fees, (4 * 99 + 98 + 97) * 0.01); assert.equal(+stats.unfilled, 0); }); it('calculates sell stats between 16 and 20 BTC', () => { const stats = obu.integrateBetween(Big(16), Big(20), false, Big(0)); assert.equal(+stats.total_size, 3); assert.equal(+stats.first_price, 97); assert.equal(+stats.last_price, 97); assert.equal(+stats.total_cost, 3 * 97); assert.equal(+stats.unfilled, 1); }); it('calculates buy stats between 1 and 3 BTC', () => { const stats = obu.integrateBetween(Big(1), Big(3), true, Big(0)); assert.equal(+stats.total_size, 2); assert.equal(+stats.first_price, 110); assert.equal(+stats.last_price, 115); assert.equal(+stats.total_cost, 110 + 115); assert.equal(+stats.unfilled, 0); }); it('calculates buy stats between 2 and 7 BTC', () => { const stats = obu.integrateBetween(Big(2), Big(7), true, Big(0)); assert.equal(+stats.total_size, 5); assert.equal(+stats.first_price, 115); assert.equal(+stats.last_price, 120); assert.equal(+stats.total_cost, 115 + 4 * 120); assert.equal(+stats.unfilled, 0); }); it('calculates buy stats between 2 and 2 BTC', () => { const stats = obu.integrateBetween(Big(2), Big(2), true, Big(0)); assert.equal(+stats.total_size, 0); assert.equal(+stats.first_price, 115); assert.equal(+stats.last_price, 115); assert.equal(+stats.total_cost, 0); assert.equal(+stats.unfilled, 0); }); it('calculates buy stats between 2.5 and 2.5 BTC', () => { const stats = obu.integrateBetween(Big(2.5), Big(2.5), true, Big(0)); assert.equal(+stats.total_size, 0); assert.equal(+stats.first_price, 115); assert.equal(+stats.last_price, 115); assert.equal(+stats.total_cost, 0); assert.equal(+stats.unfilled, 0); }); }); describe('Sums using quote currency', () => { let obu: OrderbookUtils = null; beforeEach(() => { const bids = [[100, 10, 1], [95, 50, 1], [90, 10, 1], [85, 20, 1]]; const asks = [[110, 2, 1], [115, 1, 1], [120, 4, 10], [125, 100, 1]]; obu = createOrderbookUtils(bids, asks); }); it('calculates sell stats for $550', () => { const stats = obu.getSizeFromCost(Big(0), Big(550), false, Big(0)); assert.equal(+stats.total_size, 5.5); assert.equal(+stats.first_price, 100); assert.equal(+stats.last_price, 100); assert.equal(+stats.total_cost, 550); assert.equal(+stats.unfilled, 0); }); it('calculates buy stats for $165', () => { const stats = obu.getSizeFromCost(Big(0), Big(165), true, Big(0)); assert.equal(+stats.total_size, 1.5); assert.equal(+stats.first_price, 110); assert.equal(+stats.last_price, 110); assert.equal(+stats.total_cost, 165); assert.equal(+stats.unfilled, 0); }); it('calculates sell stats for $1095', () => { const stats = obu.getSizeFromCost(Big(0), Big(1095), false, Big(0)); assert.equal(+stats.total_size, 11); assert.equal(+stats.first_price, 100); assert.equal(+stats.last_price, 95); assert.equal(+stats.total_cost, 1095); assert.equal(+stats.unfilled, 0); }); it('calculates buy stats for $8,000', () => { const stats = obu.getSizeFromCost(Big(0), Big(8000), true, Big(0)); assert.equal(+stats.total_size, 64.48); assert.equal(+stats.first_price, 110); assert.equal(+stats.last_price, 125); assert.equal(+stats.total_cost, 8000); assert.equal(+stats.unfilled, 0); }); it('calculates sell stats for $1000 starting from $500', () => { const stats = obu.getSizeFromCost(Big(500), Big(1000), false, Big(0)); assert.equal(+stats.total_size, 5 + 500 / 95); // 10.26315789 assert.equal(+stats.first_price, 100); assert.equal(+stats.last_price, 95); assert.equal(+stats.total_cost, 1000); assert.equal(+stats.unfilled, 0); }); it('calculates buy stats for $2000 starting from $1000', () => { const stats = obu.getSizeFromCost(Big(1000), Big(2000), true, Big(0)); assert.equal(+stats.total_size.toFixed(6), 16); assert.equal(+stats.first_price, 125); assert.equal(+stats.last_price, 125); assert.equal(+stats.total_cost, 2000); assert.equal(+stats.unfilled, 0); }); it('calculates sell stats for $0 starting from $1200', () => { const stats = obu.getSizeFromCost(Big(5000), Big(0), false, Big(0)); assert.equal(+stats.total_size, 0); assert.equal(+stats.first_price, 95); assert.equal(+stats.last_price, 95); assert.equal(+stats.total_cost, 0); assert.equal(+stats.unfilled, 0); }); it('calculates buy stats for $0 starting from $2500', () => { const stats = obu.getSizeFromCost(Big(2500), Big(0), true, Big(0)); assert.equal(+stats.total_size, 0); assert.equal(+stats.first_price, 125); assert.equal(+stats.last_price, 125); assert.equal(+stats.total_cost, 0); assert.equal(+stats.unfilled, 0); }); it('calculates sell stats for $1000 starting from $500, including fees', () => { const stats = obu.getSizeFromCost(Big(500), Big(1000), false, Big(0.01)); assert.equal(+stats.total_size.toFixed(6), 10.158937); assert.equal(+stats.first_price, 100); assert.equal(+stats.last_price, 95); assert.equal(+stats.total_cost, 1000); assert.equal(+stats.unfilled, 0); }); it('calculates buy stats for $15,000 starting from $750, including fees', () => { const stats = obu.getSizeFromCost(Big(750), Big(15000), true, Big(0.01)); assert.equal(+stats.total_size.toFixed(3), 100.542); assert.equal(+stats.first_price, 120); assert.equal(+stats.last_price, 125); assert.equal(+stats.total_cost, 12690.65); assert.equal(+stats.fees, 125.65); assert.equal(+stats.unfilled, 2309.35); }); }); });
the_stack
import { addAll, extract, flatMap, isDefined } from '../private/javascript'; import { topoSort } from './toposort'; export interface GraphNodeProps<A> { readonly data?: A; } export class GraphNode<A> { public static of<A>(id: string, data: A) { return new GraphNode(id, { data }); } public readonly dependencies: GraphNode<A>[] = []; public readonly data?: A; private _parentGraph?: Graph<A>; constructor(public readonly id: string, props: GraphNodeProps<A> = {}) { this.data = props.data; } /** * A graph-wide unique identifier for this node. Rendered by joining the IDs * of all ancestors with hyphens. */ public get uniqueId(): string { return this.ancestorPath(this.root).map(x => x.id).join('-'); } /** * The union of all dependencies of this node and the dependencies of all * parent graphs. */ public get allDeps(): GraphNode<A>[] { const fromParent = this.parentGraph?.allDeps ?? []; return Array.from(new Set([...this.dependencies, ...fromParent])); } public dependOn(...dependencies: Array<GraphNode<A> | undefined>) { if (dependencies.includes(this)) { throw new Error(`Cannot add dependency on self: ${this}`); } this.dependencies.push(...dependencies.filter(isDefined)); } public ancestorPath(upTo: GraphNode<A>): GraphNode<A>[] { let x: GraphNode<A> = this; const ret = [x]; while (x.parentGraph && x.parentGraph !== upTo) { x = x.parentGraph; ret.unshift(x); } return ret; } public rootPath(): GraphNode<A>[] { let x: GraphNode<A> = this; const ret = [x]; while (x.parentGraph) { x = x.parentGraph; ret.unshift(x); } return ret; } public get root() { let x: GraphNode<A> = this; while (x.parentGraph) { x = x.parentGraph; } return x; } public get parentGraph() { return this._parentGraph; } /** * @internal */ public _setParentGraph(parentGraph: Graph<A>) { if (this._parentGraph) { throw new Error('Node already has a parent'); } this._parentGraph = parentGraph; } public toString() { return `${this.constructor.name}(${this.id})`; } } /** * A dependency set that can be constructed partially and later finished * * It doesn't matter in what order sources and targets for the dependency * relationship(s) get added. This class can serve as a synchronization * point if the order in which graph nodes get added to the graph is not * well-defined. * * Useful utility during graph building. */ export class DependencyBuilder<A> { private readonly targets: GraphNode<A>[] = []; private readonly sources: GraphNode<A>[] = []; public dependOn(...targets: GraphNode<A>[]) { for (const target of targets) { for (const source of this.sources) { source.dependOn(target); } this.targets.push(target); } return this; } public dependBy(...sources: GraphNode<A>[]) { for (const source of sources) { for (const target of this.targets) { source.dependOn(target); } this.sources.push(source); } return this; } } export class DependencyBuilders<K, A> { private readonly builders = new Map<K, DependencyBuilder<A>>(); public get(key: K) { const b = this.builders.get(key); if (b) { return b; } const ret = new DependencyBuilder<A>(); this.builders.set(key, ret); return ret; } } export interface GraphProps<A> extends GraphNodeProps<A> { /** * Initial nodes in the workflow */ readonly nodes?: GraphNode<A>[]; } export class Graph<A> extends GraphNode<A> { public static of<A, B>(id: string, data: A, nodes?: GraphNode<B>[]) { return new Graph<A | B>(id, { data, nodes }); } private readonly children = new Map<string, GraphNode<A>>(); constructor(name: string, props: GraphProps<A>={}) { super(name, props); if (props.nodes) { this.add(...props.nodes); } } public get nodes() { return new Set(this.children.values()); } public tryGetChild(name: string) { return this.children.get(name); } public contains(node: GraphNode<A>) { return this.nodes.has(node); } public add(...nodes: Array<GraphNode<A>>) { for (const node of nodes) { node._setParentGraph(this); if (this.children.has(node.id)) { throw new Error(`Node with duplicate id: ${node.id}`); } this.children.set(node.id, node); } } public absorb(other: Graph<A>) { this.add(...other.nodes); } /** * Return topologically sorted tranches of nodes at this graph level */ public sortedChildren(): GraphNode<A>[][] { // Project dependencies to current children const nodes = this.nodes; const projectedDependencies = projectDependencies(this.deepDependencies(), (node) => { while (!nodes.has(node) && node.parentGraph) { node = node.parentGraph; } return nodes.has(node) ? [node] : []; }); return topoSort(nodes, projectedDependencies); } /** * Return a topologically sorted list of non-Graph nodes in the entire subgraph */ public sortedLeaves(): GraphNode<A>[][] { // Project dependencies to leaf nodes const descendantsMap = new Map<GraphNode<A>, GraphNode<A>[]>(); findDescendants(this); function findDescendants(node: GraphNode<A>): GraphNode<A>[] { const ret: GraphNode<A>[] = []; if (node instanceof Graph) { for (const child of node.nodes) { ret.push(...findDescendants(child)); } } else { ret.push(node); } descendantsMap.set(node, ret); return ret; } const projectedDependencies = projectDependencies(this.deepDependencies(), (node) => descendantsMap.get(node) ?? []); return topoSort(new Set(projectedDependencies.keys()), projectedDependencies); } public consoleLog(indent: number = 0) { process.stdout.write(' '.repeat(indent) + this + depString(this) + '\n'); for (const node of this.nodes) { if (node instanceof Graph) { node.consoleLog(indent + 2); } else { process.stdout.write(' '.repeat(indent + 2) + node + depString(node) + '\n'); } } function depString(node: GraphNode<A>) { if (node.dependencies.length > 0) { return ` -> ${Array.from(node.dependencies).join(', ')}`; } return ''; } } /** * Return the union of all dependencies of the descendants of this graph */ private deepDependencies() { const ret = new Map<GraphNode<A>, Set<GraphNode<A>>>(); for (const node of this.nodes) { recurse(node); } return ret; function recurse(node: GraphNode<A>) { let deps = ret.get(node); if (!deps) { ret.set(node, deps = new Set()); } for (let dep of node.dependencies) { deps.add(dep); } if (node instanceof Graph) { for (const child of node.nodes) { recurse(child); } } } } /** * Return all non-Graph nodes */ public allLeaves(): GraphNodeCollection<A> { const ret: GraphNode<A>[] = []; recurse(this); return new GraphNodeCollection(ret); function recurse(node: GraphNode<A>) { if (node instanceof Graph) { for (const child of node.nodes) { recurse(child); } } else { ret.push(node); } } } } /** * A collection of graph nodes */ export class GraphNodeCollection<A> { public readonly nodes: GraphNode<A>[]; constructor(nodes: Iterable<GraphNode<A>>) { this.nodes = Array.from(nodes); } public dependOn(...dependencies: Array<GraphNode<A> | undefined>) { for (const node of this.nodes) { node.dependOn(...dependencies.filter(isDefined)); } } /** * Returns the graph node that's shared between these nodes */ public commonAncestor() { const paths = new Array<GraphNode<A>[]>(); for (const x of this.nodes) { paths.push(x.rootPath()); } if (paths.length === 0) { throw new Error('Cannot find common ancestor between an empty set of nodes'); } if (paths.length === 1) { const path = paths[0]; if (path.length < 2) { throw new Error(`Cannot find ancestor of node without ancestor: ${path[0]}`); } return path[path.length - 2]; } const originalPaths = [...paths]; // Remove the first element of every path as long as the 2nd elements are all // the same -- this leaves the shared element in first place. // // A, B, C, 1, 2 }---> C // A, B, C, 3 } while (paths.every(path => paths[0].length >= 2 && path.length >= 2 && path[1] === paths[0][1])) { for (const path of paths) { path.shift(); } } // If any of the paths are left with 1 element, there's no shared parent. if (paths.some(path => path.length < 2)) { throw new Error(`Could not determine a shared parent between nodes: ${originalPaths.map(nodes => nodes.map(n => n.id).join('/'))}`); } return paths[0][0]; } } /** * Dependency map of nodes in this graph, taking into account dependencies between nodes in subgraphs * * Guaranteed to return an entry in the map for every node in the current graph. */ function projectDependencies<A>(dependencies: Map<GraphNode<A>, Set<GraphNode<A>>>, project: (x: GraphNode<A>) => GraphNode<A>[]) { // Project keys for (const node of dependencies.keys()) { const projectedNodes = project(node); if (projectedNodes.length === 1 && projectedNodes[0] === node) { continue; } // Nothing to do, just for efficiency const deps = extract(dependencies, node)!; for (const projectedNode of projectedNodes) { addAll(dependencies.get(projectedNode)!, deps); } } // Project values. Ignore self-dependencies, they were just between nodes that were collapsed into the same node. for (const [node, deps] of dependencies.entries()) { const depset = new Set(flatMap(deps, project)); depset.delete(node); dependencies.set(node, depset); } return dependencies; } export function isGraph<A>(x: GraphNode<A>): x is Graph<A> { return x instanceof Graph; }
the_stack
import { Clipboard, commands, env, Uri, window } from 'vscode'; import * as Constants from '../common/constants'; import { HttpRequest } from '../models/httpRequest'; import { HttpClient } from './httpClient'; import { EnvironmentVariableProvider } from './httpVariableProviders/environmentVariableProvider'; /* AppId provisioned to allow users to explicitly consent to permissions that this app can call */ const AadV2TokenProviderClientId = "07f0a107-95c1-41ad-8f13-912eab68b93f"; export class AadV2TokenProvider { private readonly _httpClient: HttpClient; private readonly clipboard: Clipboard; public constructor() { this._httpClient = new HttpClient(); this.clipboard = env.clipboard; } public async acquireToken(name: string): Promise<string> { const authParams = await AuthParameters.parseName(name); if (!authParams.forceNewToken) { const tokenEntry = AadV2TokenCache.getToken(authParams.getCacheKey()); if (tokenEntry?.supportScopes(authParams.scopes)) { return tokenEntry.token; } } if (authParams.appOnly) { return await this.getConfidentialClientToken(authParams); } const deviceCodeResponse: IDeviceCodeResponse = await this.getDeviceCodeResponse(authParams); const isDone = await this.promptForUserCode(deviceCodeResponse); if (isDone) { return await this.getToken(deviceCodeResponse, authParams); } else { return ""; } } private async getDeviceCodeResponse(authParams: AuthParameters): Promise<IDeviceCodeResponse> { const request = this.createUserCodeRequest(authParams.clientId, authParams.tenantId, authParams.scopes); const response = await this._httpClient.send(request); const bodyObject = JSON.parse(response.body); if (response.statusCode !== 200) { // Fail this.processAuthErrorAndThrow(bodyObject); } if (bodyObject.error) { // This is only needed due to an error in AADV2 device code endpoint. An issue is filed. this.processAuthErrorAndThrow(bodyObject); } // Get userCode out of response body return bodyObject as IDeviceCodeResponse; } private async getToken(deviceCodeResponse: IDeviceCodeResponse, authParams: AuthParameters): Promise<string> { const request = this.createAcquireTokenRequest(authParams.clientId, authParams.tenantId, deviceCodeResponse.device_code); const response = await this._httpClient.send(request); const bodyObject = JSON.parse(response.body); if (response.statusCode !== 200) { this.processAuthErrorAndThrow(bodyObject); } const tokenResponse: ITokenResponse = bodyObject; const tokenScopes = tokenResponse.scope.split(' '); for (const scope of authParams.scopes) { if (!tokenScopes.includes(scope)) { tokenScopes.push(scope); } } AadV2TokenCache.setToken(authParams.getCacheKey(), tokenScopes, tokenResponse.access_token); return tokenResponse.access_token; } private async getConfidentialClientToken(authParams: AuthParameters): Promise<string> { const request = this.createAcquireConfidentialClientTokenRequest(authParams.clientId, authParams.tenantId, authParams.clientSecret!, authParams.appUri!); const response = await this._httpClient.send(request); const bodyObject = JSON.parse(response.body); if (response.statusCode !== 200) { this.processAuthErrorAndThrow(bodyObject); } const tokenResponse: ITokenResponse = bodyObject; const scopes: string[] = []; // Confidential Client tokens are limited to scopes defined in the app registration portal AadV2TokenCache.setToken(authParams.getCacheKey(), scopes, tokenResponse.access_token); return tokenResponse.access_token; } private processAuthErrorAndThrow(bodyObject: any) { const errorResponse: IAuthError = bodyObject; throw new Error("Auth call failed. " + errorResponse.error_description); } private createUserCodeRequest(clientId: string, tenantId: string, scopes: string[]): HttpRequest { return new HttpRequest( "POST", `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/devicecode`, { "Content-Type": "application/x-www-form-urlencoded" }, `client_id=${clientId}&scope=${scopes.join("%20")}`); } private createAcquireTokenRequest(clientId: string, tenantId: string, deviceCode: string): HttpRequest { return new HttpRequest("POST", `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`, { "Content-Type": "application/x-www-form-urlencoded" }, `grant_type=urn:ietf:params:oauth:grant-type:device_code&client_id=${clientId}&device_code=${deviceCode}`); } private createAcquireConfidentialClientTokenRequest(clientId: string, tenantId: string, clientSecret: string, appUri: string): HttpRequest { return new HttpRequest("POST", `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`, { "Content-Type": "application/x-www-form-urlencoded" }, `grant_type=client_credentials&client_id=${clientId}&client_secret=${clientSecret}&scope=${appUri}/.default`); } private async promptForUserCode(deviceCodeResponse: IDeviceCodeResponse): Promise<boolean> { const messageBoxOptions = { modal: true }; const signInPrompt = `Sign in to Azure AD with the following code (will be copied to the clipboard) to add a token to your request.\r\n\r\nCode: ${deviceCodeResponse.user_code}`; const donePrompt = `1. Azure AD verification page opened in default browser (you may need to switch apps)\r\n2. Paste code to sign in and authorize VS Code (already copied to the clipboard)\r\n3. Confirm when done\r\n4. Token will be copied to the clipboard when finished\r\n\r\nCode: ${deviceCodeResponse.user_code}`; const signIn = "Sign in"; const tryAgain = "Try again"; const done = "Done"; let value = await window.showInformationMessage(signInPrompt, messageBoxOptions, signIn); if (value === signIn) { do { await this.clipboard.writeText(deviceCodeResponse.user_code); commands.executeCommand("vscode.open", Uri.parse(deviceCodeResponse.verification_uri)); value = await window.showInformationMessage(donePrompt, messageBoxOptions, done, tryAgain); } while (value === tryAgain); } return value === done; } } /* ClientId: We use default clientId for all delegated access unless overridden in $appToken. AppOnly access uses the one in the environment TenantId: If not specified, we use common. If specified in environment, we use that. Value in $aadToken overrides Scopes are always in $aadV2Token for delegated access. They are not used for appOnly. */ class AuthParameters { private readonly aadV2TokenRegex: RegExp = new RegExp(`\\s*\\${Constants.AzureActiveDirectoryV2TokenVariableName}(\\s+(${Constants.AzureActiveDirectoryForceNewOption}))?(\\s+(appOnly))?(\\s+scopes:(\\S+))?(\\s+tenantId:([^\\.]+\\.[^\\}\\s]+|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}))?(\\s+clientId:([^\\.]+\\.[^\\}\\s]+|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}))?\\s*`); public tenantId: string; public clientId: string; public scopes: string[]; public forceNewToken: boolean; public clientSecret?: string; public appOnly: boolean; public appUri?: string; public constructor() { this.clientId = AadV2TokenProviderClientId; this.tenantId = "common"; this.forceNewToken = false; this.appOnly = false; } async readEnvironmentVariable(variableName: string): Promise<string | undefined> { if (await EnvironmentVariableProvider.Instance.has(variableName)) { const { value, error, warning } = await EnvironmentVariableProvider.Instance.get(variableName); if (!warning && !error) { return value as string; } else { return undefined; } } return undefined; } getCacheKey(): string { return this.tenantId + "|" + this.clientId + "|" + this.appOnly + "|" + this.scopes.join(',') as string; } static async parseName(name: string): Promise<AuthParameters> { const authParameters = new AuthParameters(); // Update defaults based on environment authParameters.tenantId = (await authParameters.readEnvironmentVariable("aadV2TenantId")) || authParameters.tenantId; let scopes = "openid,profile"; let explicitClientId: string | undefined = undefined; // Parse variable parameters const groups = authParameters.aadV2TokenRegex.exec(name); if (groups) { authParameters.forceNewToken = groups[2] === Constants.AzureActiveDirectoryForceNewOption; authParameters.appOnly = groups[4] === "appOnly"; scopes = groups[6] || scopes; authParameters.tenantId = groups[8] || authParameters.tenantId; explicitClientId = groups[10]; } else { throw new Error("Failed to parse parameters: " + name); } // if scopes does not contain openid or profile, add it // Using /common endpoint with only organizational scopes causes device code to fail. // Adding openid and/or profile prevents this failure from occuring if (scopes.indexOf("openid") === -1) { scopes += ",openid,profile"; } authParameters.scopes = scopes.split(",").map(s => s.trim()); if (authParameters.appOnly) { authParameters.clientId = explicitClientId || (await authParameters.readEnvironmentVariable("aadV2ClientId")) || authParameters.clientId; authParameters.clientSecret = await authParameters.readEnvironmentVariable("aadV2ClientSecret"); authParameters.appUri = await authParameters.readEnvironmentVariable("aadV2AppUri"); if (!(authParameters.clientSecret && authParameters.appUri)) { throw new Error("For appOnly tokens, environment variables aadV2ClientSecret and aadV2AppUri must be created. aadV2ClientId and aadV2TenantId are optional environment variables."); } } else { authParameters.clientId = explicitClientId || authParameters.clientId; } return authParameters; } } class AadV2TokenCache { private static tokens: Map<string, AadV2TokenCacheEntry> = new Map<string, AadV2TokenCacheEntry>(); public static setToken(cacheKey: string, scopes: string[], token: string) { const entry: AadV2TokenCacheEntry = new AadV2TokenCacheEntry(); entry.token = token; entry.scopes = scopes; this.tokens.set(cacheKey, entry); } public static getToken(cacheKey: string): AadV2TokenCacheEntry | undefined { return this.tokens.get(cacheKey); } } class AadV2TokenCacheEntry { public token: string; public scopes: string[]; public supportScopes(scopes: string[]): boolean { return scopes.every((scope) => this.scopes.includes(scope)); } } interface IAuthError { error: string; error_description: string; error_uri: string; error_codes: number[]; timestamp: string; trace_id: string; correlation_id: string; } interface IDeviceCodeResponse { user_code: string; device_code: string; verification_uri: string; expires_in: string; interval: string; message: string; } interface ITokenResponse { token_type: string; scope: string; expires_in: number; access_token: string; refresh_token: string; id_token: string; }
the_stack
import { OptRow } from '@t/options'; import { data as sampleData } from '../../samples/basic'; const CONTENT_WIDTH = 600; // @TODO: Retrieve scrollbar-width from real browser const SCROLLBAR_WIDTH = 17; const containerStyle = { width: `${CONTENT_WIDTH + SCROLLBAR_WIDTH}px` }; const HALF_WIDTH = 3; function getRside() { return cy.getByCls('rside-area'); } function getRsideHeader() { return cy.getByCls('rside-area', 'header-area'); } function getColumnResizeHandle() { return cy.getByCls('column-resize-handle'); } function assertWidth(width: number) { cy.getByCls('container').invoke('width').should('eql', width); getRside().invoke('width').should('eql', width); getRsideHeader() .invoke('width') .should('eql', width - 17); cy.getRsideBody().invoke('width').should('eql', width); } function assertColumnWidth(widths: number[]) { getRsideHeader().get('th').as('headCols'); cy.getRsideBody().get('tr:first-child td').as('bodyCols'); widths.forEach((width, index) => { cy.get('@headCols').eq(index).invoke('outerWidth').should('eql', width); cy.get('@bodyCols').eq(index).invoke('outerWidth').should('eql', width); }); } function assertHandleOffset(index: number, offsetLeft: number) { getColumnResizeHandle() .eq(index) .invoke('position') // @ts-ignore .its('left') .should('eql', offsetLeft - HALF_WIDTH); } function assertHandleLength(length: number) { getColumnResizeHandle().its('length').should('eql', length); } function assertBodyHeight(height: number) { cy.getByCls('body-area').each(($body) => { expect($body.height()).to.eq(height); }); } interface WidthInfo { width?: number | 'auto'; minWidth?: number; resizable?: boolean; } interface HeightInfo { minBodyHeight?: number; bodyHeight?: number | 'fitToParent'; heightResizable?: boolean; } interface RowHeightInfo { rowHeight?: number; data?: OptRow[]; } function createGridWithWidths(widths: WidthInfo[], commonMinWidth?: number) { const columns = widths.map(({ width, minWidth, resizable }, index) => ({ name: `c${index}`, width, minWidth, resizable, })); const data: OptRow[] = [{}]; columns.forEach(({ name }) => { data[0][name] = name; }); const columnOptions = { minWidth: commonMinWidth }; cy.createGrid({ data, columns, columnOptions }, containerStyle); } function createGridWithBodyHeight(heightInfo: HeightInfo, parentEl?: HTMLElement) { const columns = [{ name: 'c1' }]; const data = [{ c1: 'test' }]; cy.createGrid({ data, columns, ...heightInfo }, containerStyle, parentEl); } function createGridWithRowHeight(rowHeightInfo: RowHeightInfo) { const columns = [{ name: 'c1' }]; const data = [{ c1: 'test1' }, { c1: 'test2' }]; cy.createGrid({ data, columns, ...rowHeightInfo }, containerStyle); } before(() => { cy.visit('/dist'); }); describe('container width', () => { beforeEach(() => { const data = sampleData.slice(10); const columns = [{ name: 'name' }, { name: 'artist' }]; cy.createGrid({ data, columns }, containerStyle); }); it('default width is the same as the DOM width', () => { assertWidth(CONTENT_WIDTH + SCROLLBAR_WIDTH); }); it('setWidth() changes container width', () => { cy.gridInstance().invoke('setWidth', 700); assertWidth(700); }); }); describe('auto calculate column widths (container: 600)', () => { it(`['auto', 'auto'] -> [300, 300]`, () => { createGridWithWidths([ { width: 'auto', minWidth: 300 }, { width: 'auto', minWidth: 300 }, ]); assertColumnWidth([300, 300]); }); it(`[empty, empty] -> [300, 300] (default is 'auto')`, () => { createGridWithWidths([{}, {}]); assertColumnWidth([300, 300]); }); it('[empty, empty, empty] -> [200, 200, 200]', () => { createGridWithWidths([{}, {}, {}]); assertColumnWidth([200, 200, 200]); }); it('[100, 100, empty] -> [100, 100, 400]', () => { createGridWithWidths([{ width: 100 }, { width: 100 }, {}]); assertColumnWidth([100, 100, 400]); }); context('using column[].minWidth', () => { it('[min:100, min:200, empty] -> [200, 200, 200]', () => { createGridWithWidths([{ minWidth: 100 }, { minWidth: 200 }, {}]); assertColumnWidth([200, 200, 200]); }); it('[min:250, min:250, empty] -> [250, 250, 100]', () => { createGridWithWidths([{ minWidth: 250 }, { minWidth: 250 }, {}]); assertColumnWidth([250, 250, 100]); }); it('[min:250, min:250, width:200] -> [250, 250, 200] (larger than container)', () => { createGridWithWidths([{ minWidth: 250 }, { minWidth: 250 }, { width: 200 }]); assertColumnWidth([250, 250, 200]); }); }); context('using columnOption.minWidth', () => { it('[300, 260, empty] (min: default = 50) -> [300, 360, 50]', () => { createGridWithWidths([{ width: 300 }, { width: 260 }, {}]); assertColumnWidth([300, 260, 50]); }); it('[100, 250, empty] (min: 200) -> [200, 250, 200]', () => { createGridWithWidths([{ width: 100 }, { width: 250 }, {}], 200); assertColumnWidth([200, 250, 200]); }); it('[100, min:250, empty] (min: 200) -> [200, 250, 200]', () => { createGridWithWidths([{ width: 100 }, { minWidth: 250 }, {}], 200); // minWidth in each column overrides columnOption.minWidth assertColumnWidth([200, 250, 200]); }); }); context('setWidth : [min:150, min:150, empty]', () => { beforeEach(() => { createGridWithWidths([{ minWidth: 150 }, { minWidth: 150 }, {}]); }); it('setWidth(720) -> [240, 240, 240]', () => { cy.gridInstance().invoke('setWidth', 720 + SCROLLBAR_WIDTH); assertColumnWidth([240, 240, 240]); }); it('setWidth(420) -> [150, 150, 120]', () => { cy.gridInstance().invoke('setWidth', 420 + SCROLLBAR_WIDTH); assertColumnWidth([150, 150, 120]); }); }); context('resetColumnWidths', () => { it('[150, 150, 300]', () => { createGridWithWidths([{}, {}, {}]); cy.gridInstance().invoke('resetColumnWidths', [150, 150, 300]); assertColumnWidth([150, 150, 300]); }); }); context('when window.resize event occur', () => { it('reset container width and column width', () => { createGridWithWidths([{}, {}, {}]); const nextWidth = 720 + SCROLLBAR_WIDTH; cy.getByCls('container').parent().invoke('width', nextWidth); cy.window().trigger('resize'); assertColumnWidth([240, 240, 240]); assertWidth(nextWidth); }); }); context('Resize handle', () => { it('show resize handle if resizable: true', () => { createGridWithWidths([{ resizable: true }, { resizable: true }, {}]); assertHandleOffset(0, 200); assertHandleOffset(1, 400); assertHandleLength(2); }); it('recalculate column width when dragging resize handle', () => { createGridWithWidths([{ resizable: true }, { resizable: true, minWidth: 200 }, {}]); cy.dragColumnResizeHandle(0, 50); assertHandleOffset(0, 250); assertHandleOffset(1, 450); assertColumnWidth([250, 200, 150]); }); }); context('should extend the width with `width: auto` option as text length', () => { function createGrid({ hasLongText = true, hasAutoWidth = true } = {}) { const data: OptRow[] = [{}]; const names = ['c1', 'c2', 'c3', 'c4', 'c5']; const columns = names.map((name) => ({ name, minWidth: 150 })); columns.forEach(({ name }) => { data[0][name] = name; }); if (hasAutoWidth) { // @ts-ignore columns[0].width = 'auto'; } if (hasLongText) { data[0].c1 = 'looooooooooooooong contents'; } cy.createGrid({ data, columns }); } it('initial rendering', () => { createGrid(); assertColumnWidth([197, 150, 150, 150, 150]); }); it('after calling resetData()', () => { createGrid({ hasLongText: false }); cy.gridInstance().invoke('resetData', [{ c1: 'looooooooooooooong contents' }]); assertColumnWidth([197, 150, 150, 150, 150]); }); it('after calling setColumns()', () => { createGrid({ hasAutoWidth: false }); const columns = ['c1', 'c2', 'c3', 'c4', 'c5'].map((name) => ({ name, minWidth: 150 })); // @ts-ignore columns[0].width = 'auto'; cy.gridInstance().invoke('setColumns', columns); assertColumnWidth([197, 150, 150, 150, 150]); }); it('after calling setValue()', () => { createGrid({ hasLongText: false }); cy.gridInstance().invoke('setValue', 0, 'c1', 'looooooooooooooong contents'); assertColumnWidth([197, 150, 150, 150, 150]); }); it('after calling setRow()', () => { createGrid({ hasLongText: false }); cy.gridInstance().invoke('setRow', 0, { c1: 'looooooooooooooong contents' }); assertColumnWidth([197, 150, 150, 150, 150]); }); it('after calling appendRow()', () => { createGrid({ hasLongText: false }); cy.gridInstance().invoke('appendRow', { c1: 'looooooooooooooong contents' }); assertColumnWidth([197, 150, 150, 150, 150]); }); it('after calling removeRow()', () => { createGrid({ hasLongText: false }); cy.gridInstance().invoke('appendRow', { c1: 'looooooooooooooong contents' }); cy.gridInstance().invoke('removeRow', 1); assertColumnWidth([150, 158, 158, 158, 159]); }); it('after calling appendRows()', () => { createGrid({ hasLongText: false }); cy.gridInstance().invoke('appendRows', [{ c1: 'looooooooooooooong contents' }]); assertColumnWidth([197, 150, 150, 150, 150]); }); it('after calling setColumnValues()', () => { createGrid({ hasLongText: false }); cy.gridInstance().invoke('setColumnValues', 'c1', 'looooooooooooooong contents'); assertColumnWidth([197, 150, 150, 150, 150]); }); }); }); describe('body height', () => { function dragHeightReiszeHandle(distance: number) { cy.getByCls('height-resize-handle').within(($el) => { const { top } = $el.offset()!; cy.root() .trigger('mousedown', { pageY: top }) .trigger('mousemove', { pageY: top + distance }) .trigger('mouseup'); }); } it('fitToParent', () => { const PARENT_HEIGHT = 400; const DEF_HEADER_HEIGHT = 40; const BORER_WIDTH = 1; const parentEl = document.createElement('div'); parentEl.style.height = `${PARENT_HEIGHT}px`; createGridWithBodyHeight({ bodyHeight: 'fitToParent' }, parentEl); assertBodyHeight(400 - DEF_HEADER_HEIGHT - BORER_WIDTH); }); it('bodyHeight: 200', () => { createGridWithBodyHeight({ bodyHeight: 200 }); assertBodyHeight(200); }); it('minBodyHeight: 200', () => { createGridWithBodyHeight({ minBodyHeight: 200 }); assertBodyHeight(200); }); it('minBodyHeight takes precedence over bodyHeight', () => { createGridWithBodyHeight({ minBodyHeight: 300, bodyHeight: 200 }); assertBodyHeight(300); }); it('reset bodyHeight when dragging height resize handle', () => { createGridWithBodyHeight({ bodyHeight: 200, heightResizable: true }); dragHeightReiszeHandle(100); assertBodyHeight(300); }); it('setBodyHeight() changes body height', () => { createGridWithBodyHeight({ minBodyHeight: 300, bodyHeight: 200 }); cy.gridInstance().invoke('setBodyHeight', 300); assertBodyHeight(300); }); }); describe('row height', () => { it('rowHeight: 70', () => { createGridWithRowHeight({ rowHeight: 70 }); cy.getRsideBody() .find('tr') .each(($el) => { expect($el.height()).to.eql(70); }); }); it('rowHeight: custom', () => { const data = [{ c1: 'test1', _attributes: { height: 70 } }, { c2: 'test2' }]; createGridWithRowHeight({ data }); cy.getByCls('row-odd').invoke('height').should('eq', 70); cy.getByCls('row-even').invoke('height').should('eq', 40); }); it('rowHeight: auto - The rowHeight changes according to the text longest content.', () => { const data = [ { col1: 'something very long text to exceed with of the cell', col2: 'something very long text to\nexceed with of the cell', col3: 'grid example\ngrid newline example\n\ngrid newline example\n\ngrid newline example\n\n', col4: 'grid example\ngrid newline example\n\ngrid newline example\n\n', col5: 'grid example\ngrid newline example\n\ngrid newline example\n\n', }, ]; const columns = [ { name: 'col1' }, { name: 'col2' }, { name: 'col3', whiteSpace: 'normal', editor: 'text', }, { name: 'col4' }, { name: 'col5' }, ]; cy.createGrid({ data, columns, rowHeight: 'auto' }); cy.getByCls('row-odd').invoke('height').should('eq', 69); cy.gridInstance().invoke('startEditing', 0, 'col3'); cy.getByCls('content-text').type('Kim'); cy.gridInstance().invoke('finishEditing'); cy.getByCls('row-odd').invoke('height').should('eq', 40); }); it('rowHeight: auto - The rowHeight changes properly when showing the hidden column dynamically', () => { const data = [ { col1: 'something very long text to exceed with of the cell', col2: 'something very long text to\nexceed with of the cell', col3: 'grid example\ngrid newline example\n\ngrid newline example\n\ngrid newline example\n\n', col4: 'grid example\ngrid newline example\n\ngrid newline example\n\n', col5: 'grid example\ngrid newline example\n\ngrid newline example\n\n', }, ]; const columns = [ { name: 'col1' }, { name: 'col2', hidden: true }, { name: 'col3', whiteSpace: 'normal', editor: 'text', }, { name: 'col4' }, { name: 'col5' }, ]; cy.createGrid({ data, columns, rowHeight: 'auto', rowHeaders: ['rowNum'], width: 500 }); cy.getByCls('row-odd').invoke('height').should('eq', 84); cy.gridInstance().invoke('showColumn', 'col2'); cy.getByCls('row-odd').invoke('height').should('eq', 114); }); });
the_stack
import * as ui from './utils/ui'; import fs = require('fs'); import path = require('path'); import process = require('process'); import * as api from './api'; import { bold, highlight, JspmUserError, readModuleEnv, isWindows, isURL } from './utils/common'; import globalConfig from './config/global-config-file'; import { DepType } from './install/package'; import { readOptions, readValue, readPropertySetters } from './utils/opts'; import { JSPM_GLOBAL_PATH } from './api'; import { extend, flattenScopes, validateImportMap, rebaseMap } from './map/utils'; import { readJSONStyled, defaultStyle, serializeJson } from './config/config-file'; import publish from './install/publish'; import { getBin } from './install/bin'; import { spawn } from 'child_process'; const installEqualRegEx = /^([@\-_\.a-z\d\/]+)=/i; function readTargetEquals (installArg: string) { let name: string | undefined, target: string; const match = installArg.match(installEqualRegEx); if (match) { name = match[1]; target = installArg.substr(name.length + 1); } else { target = installArg; } return { name, target }; } export default async function cliHandler (projectPaths: string[], cmd: string, args: string[]) { if (typeof projectPaths === 'string') projectPaths = [projectPaths]; if (typeof args === 'string') args = (<string>args).split(' '); let setProjectPath = false; const projects: api.Project[] = []; try { let userInput = true, offline = false, preferOffline = false; // first read global options outer: for (let i = 0; i < args.length; i++) { const arg = args[i]; switch (arg) { case '-y': case '--skip-prompts': args.splice(i--, 1); ui.setUseDefaults(true); userInput = false; break; case '-l': case '--log': const logLevelString = args[i + 1]; const logLevel = ui.LogType[logLevelString]; if (typeof logLevel !== 'number') { ui.warn(`${bold(logLevelString)} is not a valid log level.`); return process.exit(1); } ui.setLogLevel(logLevel); args.splice(i, 2); i -= 2; break; case '-g': setProjectPath = true; projectPaths = [api.JSPM_GLOBAL_PATH]; args.splice(i, 1); break; case '-p': case '--project': setProjectPath = true; projectPaths = args.splice(i).slice(1); break outer; case '-q': case '--prefer-offline': preferOffline = true; args.splice(i--, 1); break; case '--offline': offline = true; args.splice(i--, 1); break; } } const multiProject = projectPaths.length > 1; if (process.env.JSPM_OFFLINE) { offline = true; } if (process.env.JSPM_PREFER_OFFLINE) { preferOffline = true; } if (process.env.JSPM_PROJECT) { setProjectPath = true; projectPaths = (process.env.JSPM_PROJECT.match(/("[^"]+"|'[^']+'|[^ ]+)( |$)/g) || []).map(item => item.trim()); } if (process.env.JSPM_LOG) { const logLevelString = process.env.JSPM_LOG; const logLevel = ui.LogType[logLevelString]; if (typeof logLevel === 'number') ui.setLogLevel(logLevel); } if (process.env.JSPM_SKIP_PROMPTS && process.env.JSPM_SKIP_PROMPTS !== '0' && process.env.JSPM_SKIP_PROMPTS !== 'false') { ui.setUseDefaults(true); userInput = true; } switch (cmd) { case undefined: case '-v': case '--version': case 'version': case 'v': console.log(api.version + '\n' + (process.env.globalJspm === 'true' || process.env.localJspm === 'false' ? 'Running against global jspm install.' : 'Running against local jspm install.')); break; case 'h': case 'help': console.log(`${/*bold('Init')} jspm init <path>? Initialize or validate a jspm project in the current directory ${*/bold('📦 Install')} jspm install [<registry>:]<pkg>[@<version>] jspm install git:<path> | git+https:<path> | https:<path> | file:<path> jspm install --edge Install to latest unstable resolution --lock Do not update any existing installs --latest Resolve all packages to latest versions --dev|peer|optional Install a dev, peer or optional dependency --override (-o) main=x.js Provide a package.json property override jspm update [<name>+] Update packages within package.json ranges jspm uninstall <name>+ Uninstall a top-level package jspm clean Clear unused dependencies jspm link [<name>] <source> Link a custom source as a named package jspm unlink [<name>] Reinstall a package to its registry target jspm checkout <name>+ Copy a package in jspm_packages to modify ${bold('🔥 Execute')} jspm <file> Execute a module with jspm module resolution jspm run <name> Run package.json "scripts" jspm bin <name> [-g] Run an installed bin script --cmd Output the bin script command w/o executing --path [-g] Output the bin path ${bold('🏭 Build')} jspm build <entry>+ [-d <outdir>] [-o <buildmap.json>] --format commonjs|system|amd Set the output module format for the build --external <name>|<map.json> Define build external boundary and aliases --hash-entries Use hash file names for the entry points --exclude-deps Treat project dependencies as externals --clear-dir Clear the output directory before building --source-map Output source maps --banner <file>|<source> Provide a banner for the build files --watch Watch build files for rebuild on change ${/*jspm inspect (TODO) Inspect the installation constraints of a given dependency */''} ${bold('🔎 Inspect')} jspm resolve <module> [<parent>] Resolve a module name with the jspm resolver --browser|bin Resolve a module name in a conditional env --relative Output the path relative to the current cwd jspm trace <module>+ Trace a module graph jspm trace --deps <module>+ Trace the dependencies of modules ${/*jspm trace --format graph|text|csv|json (TODO) Different output formats for trace*/''} ${bold('🔗 Import Maps')} jspm map -o importmap.json Generates an import map for all dependencies jspm map <module>+ Generate a import map for specific modules --flat-scope Flatten scopes for Chrome compatibility --map-base Output absolute paths relative to map base --production Use production resolutions --cdn Generate a import map against the jspm CDN ${bold('🚢 Publish')} jspm publish [<path>] [--otp <otp>] [--tag <tag>] [--public] ${bold('🔧 Configure')} jspm registry-config <name> Run configuration prompts for a registry jspm config <option> <setting> Set jspm global config jspm config --get <option> Get a jspm global config value ${bold('Command Flags')} --offline Run command offline using the jspm cache --prefer-offline (-q) Use cached lookups for fastest install --skip-prompts (-y) Use default options w/o user input --log ok|warn|err|debug|none Set the log level --project (-p) <projectPath> Set the jspm command project directory -p <projectPathA> <projectPathB> Apply a command to multiple jspm projects `); break; case 'init': throw new JspmUserError(`${bold('jspm init')} has not yet been implemented.`); /*const [generator, target = generator] = args[0] && args[0].split('=') || [undefined]; const initPath = args[1] || '.'; if (!generator) { throw new JspmUserError(`jspm init requires a provided ${bold('generator')} name.`); } const generatorName = `jspm-init-${generator}`; const exitCode = await api.run(target || generatorName, [initPath, ...args.slice(2)], { latest: true, userInput, offline }); process.exit(exitCode);*/ case 'r': case 'run': { let exitCode = 0; for (const projectPath of projectPaths) { const project = new api.Project(projectPath, { offline, preferOffline, userInput, cli: true, multiProject }); projects.push(project); exitCode = await project.run(args[0], args.slice(1)); if (exitCode !== 0) break; } process.exit(exitCode); } break; case 'b': case 'bin': { for (const projectPath of projectPaths) { let options; if (args[0] === '--path' || args[0] === '--cmd' || args[0] === '-pc' || args[0] === '-cp') { ({ options } = readOptions([args[0]], ['path', 'cmd'])); args = args.slice(1); } else { options = {}; } const binPath = path.join(projectPath, 'jspm_packages', '.bin'); if (options.path) { if (args.length) throw new JspmUserError(`${bold('jspm bin --path')} doesn't take any arguments.`); // jspm bin --path -> log bin path console.log(binPath); } else { if (args.length === 0) { // jspm bin --cmd -> show Node exec command if (options.cmd) { console.log(getBin()); } // jspm bin -> Node zero arguments form else { const exitCode = await api.exec([]); process.exit(exitCode); } } else { let execPath = path.join(binPath, args[0]); if (isWindows) execPath += '.cmd'; // jspm bin --cmd x -> display exec path if (options.cmd) { console.log(execPath); } // jspm bin x -> run exec path else { const ps = spawn(execPath, args.slice(1), { stdio: 'inherit' }); const exitCode = await new Promise<number>((resolve, reject) => { ps.on('exit', code => resolve(code)); ps.on('error', err => reject(err)); }); process.exit(exitCode); } } } } } break; case 'publish': { let options; ({ args, options } = readOptions(args, ['public'], ['otp', 'tag'])); if (args.length > 1) throw new JspmUserError('Publish only takes one path argument.'); for (const projectPath of projectPaths) { const project = new api.Project(projectPath, { offline, preferOffline, userInput, cli: true, multiProject }); projects.push(project); await publish(project, options); } } break; /* case 'e': case 'exec': { const exitCode = await api.run(args); process.exit(exitCode); } break;*/ case 't': case 'trace': { let options; ({ args, options } = readOptions(args, ['react-native', 'production', 'electron', 'node', 'deps', 'exclude-deps'], ['out'])); for (const projectPath of projectPaths) { const project = new api.Project(projectPath, { offline, preferOffline, userInput, cli: true, multiProject }); // NB: local map should be included in this in the exclude case still const map = (options.excludeDeps || options.deps) ? {} : await api.map(project, options); if (!args.length) throw new JspmUserError('Trace requires a list of module names to trace.'); const traced = await api.trace(project, map, process.cwd(), args, options.excludeDeps || options.deps); if (options.deps) { const deps = new Set(); for (const map of Object.values(traced)) { for (const dep of Object.keys(map)) { if (map[dep] in traced === false && !isURL(dep) && !dep.startsWith('./') && !dep.startsWith('../')) deps.add(dep); } } for (const dep of deps) console.log(dep); return; } const output = await serializeJson(traced, defaultStyle); if (options.out) await new Promise((resolve, reject) => fs.writeFile(options.out, output, err => err ? reject(err) : resolve())); else process.stdout.write(output); } } break; case 'm': case 'map': { for (const projectPath of projectPaths) { let options; ({ args, options } = readOptions(args, ['react-native', 'production', 'electron', 'cdn', 'flat-scope', 'node'], ['out', 'in', 'jspmPackages', 'map-base'])); if (options.node) throw new JspmUserError(`${bold('jspm map')} currently only supports generating package maps for the browser.`); let inputMap, style = defaultStyle; if (options.in) ({ json: inputMap, style } = await readJSONStyled(options.in)); const project = new api.Project(projectPath, { offline, preferOffline, userInput, cli: true, multiProject }); projects.push(project); let map = await api.map(project, options); if (inputMap) map = extend(extend({}, inputMap), map); if (args.length) map = await api.filterMap(project, map, args, options.flatScope); else if (options.flatScope) flattenScopes(map); if (options.cdn && !options.jspmPackages) options.jspmPackages = options.production ? 'https://cdn.jspm.io' : 'https://dev-cdn.jspm.io'; const jspmPackagesURL = options.jspmPackages ? options.jspmPackages : options.out ? path.relative(path.dirname(path.resolve(options.out)), path.resolve(projectPath, 'jspm_packages')).replace(/\\/g, '/') : 'jspm_packages'; if (jspmPackagesURL !== 'jspm_packages') map = api.renormalizeMap(map, jspmPackagesURL, options.cdn); // we dont want input map items filtered so always add them back if (inputMap) extend(map, inputMap); if (options.mapBase) map = rebaseMap(map, options.out ? path.dirname(path.resolve(options.out)) : process.cwd(), path.resolve(options.mapBase), true); const output = await serializeJson(map, style); if (options.out) await new Promise((resolve, reject) => fs.writeFile(options.out, output, err => err ? reject(err) : resolve())); else process.stdout.write(output); } } break; case 're': case 'resolve': { let options; ({ args, options } = readOptions(args, ['format', 'browser', 'react-native', 'production', 'electron', 'relative'])); let env = readModuleEnv(options); for (const projectPath of projectPaths) { let parent; if (args[1]) { let parentFormat; ({ resolved: parent, format: parentFormat } = api.resolveSync(args[1], setProjectPath ? projectPath + path.sep : undefined, env, true)); if (parentFormat === 'builtin') parent = undefined; } else if (setProjectPath) { parent = projectPath + path.sep; } const resolved = api.resolveSync(args[0], parent, env, true); if (options.format) { console.log(resolved.format || '<undefined>'); } else { resolved.resolved = resolved.resolved || '@empty'; console.log(options.relative ? path.relative(process.cwd(), resolved.resolved) : resolved.resolved); } } } break; case 'cl': case 'clean': await Promise.all(projectPaths.map(async projectPath => { const project = new api.Project(projectPath, { offline, preferOffline, userInput, cli: true, multiProject }); projects.push(project); await project.clean(); })); break; case 'co': case 'checkout': await Promise.all(projectPaths.map(async projectPath => { const project = new api.Project(projectPath, { offline, preferOffline, userInput, cli: true, multiProject }); projects.push(project); await project.checkout(args); })); break; case 'un': case 'uninstall': await Promise.all(projectPaths.map(async projectPath => { const project = new api.Project(projectPath, { offline, preferOffline, userInput, cli: true, multiProject }); projects.push(project); await project.uninstall(args); })); break; case 'l': case 'link': { let options; ({ options, args } = readOptions(args, [ // TODO 'force', 'verify' ], [], ['override'])); await Promise.all(projectPaths.map(async projectPath => { const project = new api.Project(projectPath, { offline, preferOffline, userInput, cli: true, multiProject }); projects.push(project); if (args.length === 2) { await project.link(args[0], args[1].indexOf(':') === -1 ? 'file:' + args[1] : args[1], options); } else if (args.length === 1) { const linkSource = 'file:' + path.resolve(args[0]); const target = await project.registryManager.resolveSource(linkSource, project.projectPath, project.projectPath); await project.install([{ name: undefined, parent: undefined, target, type: DepType.primary }], options); } else if (args.length !== 1) { throw new JspmUserError(`Link command takes at most two arguments - an optional package name and a path.`); } })); } break; case 'ug': case 'upgrade': { // TODO: a single-major version upgrade of selected packages ui.warn('Still to be implemented.'); } break; case 'un': case 'up': case 'unlink': case 'update': { // the name given here is not a "TARGET" but a "SELECTOR" let { options, args: selectors } = readOptions(args, [ // install options 'reset', // TODO 'force', 'verify' 'latest' ], [], ['override']); await Promise.all(projectPaths.map(async projectPath => { const project = new api.Project(projectPath, { offline, preferOffline, userInput, cli: true, multiProject }); projects.push(project); await project.update(selectors, options); })); } break; case 'i': case 'install': { let { options, args: installArgs } = readOptions(args, [ // install options 'reset', 'force', // install type 'save-dev', 'dev', 'optional', 'peer', // constraint options 'exact', 'edge', // resolver options 'latest', 'lock', ], [], ['override']); if (options.force) throw new JspmUserError(`${highlight('--force')} flag is yet to be implemented. Use ${bold('jspm cc && jspm install')} for now, although this is only necessary if you have upgraded jspm or modified a globally linked dependency file.`); await Promise.all(projectPaths.map(async projectPath => { const project = new api.Project(projectPath, { offline, preferOffline, userInput, cli: true, multiProject }); projects.push(project); if (options.saveDev) { project.log.warn(`The ${bold(`--save-dev`)} install flag in jspm is just ${bold(`--dev`)}.`); options.dev = true; } let type; if (options.dev) type = DepType.dev; else if (options.peer) type = DepType.peer; else if (options.optional) type = DepType.optional; else type = DepType.primary; if (typeof options.override === 'string') { options.override = readPropertySetters(options.override, true); if (options.override && installArgs.length > 1) throw new JspmUserError(`An override can only be specified through ${highlight(`-o`)} when installing a single dependency at a time.`); } if (projectPath === JSPM_GLOBAL_PATH && !options.lock) { options.latest = true; options.dedupe = false; } const installTargets = installArgs.map(arg => { /* * Assignment target install * jspm install x=y@1.2.3 */ let { name, target } = readTargetEquals(arg); // when name is undefined, install will auto-populate from target if (options.override) return { name, parent: undefined, target, type, override: options.override }; else return { name, parent: undefined, target, type }; }); await project.install(installTargets, options); // TODO: look through install cache of install state for checked out and linked // and log that list so that the user is aware of it // await project.logInstallStates(); })); } break; case 'b': case 'build': { for (const projectPath of projectPaths) { let { options, args: buildArgs } = readOptions(args, [ 'clear-dir', 'mjs', 'node', 'bin', 'react-native', 'production', 'electron', 'show-graph', 'source-map', 'watch', 'exclude-deps', 'hash-entries', 'out', // out can also be boolean 'minify' ], ['map-base', 'dir', 'out', 'format', /* TODO: build map support 'map' */, 'in'], ['external', 'banner']); if (options.out && projectPaths.length > 1) throw new JspmUserError(`${bold('jspm build --out')} does not support execution in multiple projects.`); if (options.node) (options.env = options.env || {}).node = true; if (options.bin) (options.env = options.env || {}).bin = true; if (options['react-native']) (options.env = options.env || {})['react-native'] = true; if (options.production) (options.env = options.env || {}).production = true; if (options.electron) (options.env = options.env || {}).electron = true; options.basePath = path.resolve(projectPath); options.dir = options.dir || 'dist'; let inputMap, style; if (options.in) ({ json: inputMap, style } = await readJSONStyled(options.in)); if (options.map) { let buildMap, buildMapStyle; ({ json: buildMap, style: buildMapStyle } = await readJSONStyled(options.map)); if (buildMap) { if (!style) style = buildMapStyle; validateImportMap(path.relative(process.cwd(), path.resolve(options.map)), buildMap); options.map = buildMap; } else { throw new JspmUserError(`Import map ${path.relative(process.cwd(), path.resolve(options.map))} for build not found.`); } } if (options.external) { let externalMap, externalStyle; const externalsPath = path.resolve(options.external) try { ({ json: externalMap, style: externalStyle } = await readJSONStyled(externalsPath)); } catch (e) { if (e.code !== 'ENOENT') throw e; } if (externalMap) { if (!style) style = externalStyle; validateImportMap(path.relative(process.cwd(), externalsPath), externalMap); // scoped externals not currently supported, but could be (if thats even useful) options.external = rebaseMap(externalMap, path.dirname(externalsPath), path.resolve(options.dir)).imports; } else { const external = {}; options.external.split(' ').forEach(pair => { const aliasIndex = pair.indexOf('='); if (aliasIndex !== -1) { const externalName = pair.substr(0, aliasIndex); const aliasName = pair.substr(aliasIndex + 1); external[externalName] = aliasName; } else { external[pair] = true; } }); if (Object.keys(external).length === 0) throw new JspmUserError(`${bold('jspm build --external')} requires an argument for externals.`); options.external = external; } } if (options.excludeDeps) { options.external = options.external || {}; const project = new api.Project(projectPath, { offline, preferOffline, userInput, cli: true, multiProject }); projects.push(project); for (const dep in project.config.pjson.dependencies) { const depType = project.config.pjson.dependencies[dep].type; if (typeof depType === 'number' && depType !== DepType.dev) { options.external[dep] = true; } } } options.log = true; let absoluteMap = false; // -o with no arguments hides log due to using stdout if ('out' in options && !options.out && !options.showGraph) options.log = false; if (options.mapBase) { options.mapBase = path.resolve(options.mapBase); absoluteMap = true; } else if (options.out) { options.mapBase = path.dirname(path.resolve(options.out)); } let outMap = await api.build(buildArgs, options); if (absoluteMap) outMap = rebaseMap(outMap, options.mapBase, options.mapBase, true); if (inputMap) outMap = extend(inputMap, outMap); if (options.flatScope) flattenScopes(outMap); const output = await serializeJson(outMap, style || defaultStyle); if ('out' in options) { if (options.out) fs.writeFileSync(path.resolve(options.out), output); else process.stdout.write(output); } } } break; case 're': case 'registry': if (args[0] !== 'config') throw new JspmUserError(`Unknown command ${bold(cmd)}.`); args = args.splice(1); case 'rc': case 'registry-config': { if (args.length !== 1) throw new JspmUserError(`Only one argument expected for the registry name to configure.`); const project = new api.Project(projectPaths[0], { offline, preferOffline, userInput, cli: true }); projects.push(project); await project.registryConfig(args[0]); } break; case 'c': case 'config': { let property, value; const unsetIndex = args.indexOf('--unset'); const getIndex = args.indexOf('--get'); if (unsetIndex !== -1) { if (args.length !== 2) throw new JspmUserError(`Only one configuration property is expected to be unset.`); if (unsetIndex === 1) property = args[0]; else property = args[1]; globalConfig.set(property, undefined); } else if (getIndex !== -1) { if (args.length !== 2) throw new JspmUserError(`Only one configuration property is expected to be read.`); if (getIndex === 1) property = args[0]; else property = args[1]; console.log(globalConfig.get(property)); } else { property = args[0]; value = readValue(args.splice(1).join(' ')); if (property === undefined || value === undefined) throw new JspmUserError(`jspm config requires a property and value via ${bold(`jspm config <property> <value>`)}`); globalConfig.set(property, value); } } break; case 'cc': case 'clear-cache': const project = new api.Project(projectPaths[0], { offline, preferOffline, userInput, cli: true }); projects.push(project); await project.clearCache(); break; default: // if the cmd is a valid file, then we execute it directly let isFile = false; try { isFile = fs.statSync(cmd).isFile(); } catch (e) {} if (isFile) { const exitCode = await api.exec([cmd, ...args]); process.exit(exitCode); return; } throw new JspmUserError(`Command or file ${bold([cmd, ...args].join(' '))} does not exist.`); } } catch (err) { if (process.env.globalJspm !== undefined) { if (err && err.hideStack) (projects.length ? projects[0].log.err.bind(projects[0].log) : ui.err)(err.message || err); else (projects.length ? projects[0].log.err : ui.err)(err && err.stack || err); } throw err; } finally { await Promise.all(projects.map(project => project.dispose())); } } if (process.env.globalJspm !== undefined) cliHandler([path.dirname(process.env.jspmConfigPath)], process.argv[2], process.argv.slice(3)) .then(() => process.exit(), _err => process.exit(1));
the_stack
import { toAscii } from "@cosmjs/encoding"; import { firstEvent, toListPromise } from "@cosmjs/stream"; import { sleep } from "@cosmjs/utils"; import { ReadonlyDate } from "readonly-date"; import { Stream } from "xstream"; import { HttpClient, RpcClient, WebsocketClient } from "../rpcclients"; import { buildKvTx, chainIdMatcher, ExpectedValues, pendingWithoutTendermint, randomString, tendermintEnabled, tendermintInstances, tendermintSearchIndexUpdated, } from "../testutil.spec"; import { adaptor33 } from "./adaptor"; import { buildQuery } from "./requests"; import * as responses from "./responses"; import { Tendermint33Client } from "./tendermint33client"; function defaultTestSuite(rpcFactory: () => RpcClient, expected: ExpectedValues): void { describe("create", () => { it("can auto-discover Tendermint version and communicate", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const info = await client.abciInfo(); expect(info).toBeTruthy(); client.disconnect(); }); it("can connect to Tendermint with known version", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); expect(await client.abciInfo()).toBeTruthy(); client.disconnect(); }); }); it("can get genesis", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const genesis = await client.genesis(); expect(genesis).toBeTruthy(); client.disconnect(); }); it("can broadcast a transaction", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const tx = buildKvTx(randomString(), randomString()); const response = await client.broadcastTxCommit({ tx: tx }); expect(response.height).toBeGreaterThan(2); expect(response.hash).toBeTruthy(); // verify success expect(response.checkTx.code).toBeFalsy(); expect(response.deliverTx).toBeTruthy(); if (response.deliverTx) { expect(response.deliverTx.code).toBeFalsy(); } client.disconnect(); }); it("gets the same tx hash from backend as calculated locally", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const tx = buildKvTx(randomString(), randomString()); const calculatedTxHash = adaptor33.hashTx(tx); const response = await client.broadcastTxCommit({ tx: tx }); expect(response.hash).toEqual(calculatedTxHash); client.disconnect(); }); it("can query the state", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const key = randomString(); const value = randomString(); await client.broadcastTxCommit({ tx: buildKvTx(key, value) }); const binKey = toAscii(key); const binValue = toAscii(value); const queryParams = { path: "/key", data: binKey, prove: true }; const response = await client.abciQuery(queryParams); expect(response.key).toEqual(binKey); expect(response.value).toEqual(binValue); expect(response.code).toBeFalsy(); client.disconnect(); }); it("can get a commit", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const response = await client.commit(4); expect(response).toBeTruthy(); expect(response.commit.signatures.length).toBeGreaterThanOrEqual(1); expect(response.commit.signatures[0].blockIdFlag).toEqual(2); expect(response.commit.signatures[0].validatorAddress?.length).toEqual(20); expect(response.commit.signatures[0].timestamp).toBeInstanceOf(Date); expect(response.commit.signatures[0].signature?.length).toEqual(64); client.disconnect(); }); it("can get validators", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const response = await client.validators({}); expect(response).toBeTruthy(); expect(response.blockHeight).toBeGreaterThanOrEqual(1); expect(response.count).toBeGreaterThanOrEqual(1); expect(response.total).toBeGreaterThanOrEqual(1); expect(response.validators.length).toBeGreaterThanOrEqual(1); expect(response.validators[0].address.length).toEqual(20); expect(response.validators[0].pubkey).toBeDefined(); expect(response.validators[0].votingPower).toBeGreaterThanOrEqual(0); expect(response.validators[0].proposerPriority).toBeGreaterThanOrEqual(0); client.disconnect(); }); it("can get all validators", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const response = await client.validatorsAll(); expect(response).toBeTruthy(); expect(response.blockHeight).toBeGreaterThanOrEqual(1); expect(response.count).toBeGreaterThanOrEqual(1); expect(response.total).toBeGreaterThanOrEqual(1); expect(response.validators.length).toBeGreaterThanOrEqual(1); expect(response.validators[0].address.length).toEqual(20); expect(response.validators[0].pubkey).toBeDefined(); expect(response.validators[0].votingPower).toBeGreaterThanOrEqual(0); expect(response.validators[0].proposerPriority).toBeGreaterThanOrEqual(0); client.disconnect(); }); it("can call a bunch of methods", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); expect(await client.block()).toBeTruthy(); expect(await client.genesis()).toBeTruthy(); expect(await client.health()).toBeNull(); client.disconnect(); }); describe("status", () => { it("works", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const status = await client.status(); // node info expect(status.nodeInfo.version).toMatch(expected.version); expect(status.nodeInfo.protocolVersion).toEqual({ p2p: expected.p2pVersion, block: expected.blockVersion, app: expected.appVersion, }); expect(status.nodeInfo.network).toMatch(chainIdMatcher); expect(status.nodeInfo.other.size).toBeGreaterThanOrEqual(2); expect(status.nodeInfo.other.get("tx_index")).toEqual("on"); // sync info expect(status.syncInfo.catchingUp).toEqual(false); expect(status.syncInfo.latestBlockHeight).toBeGreaterThanOrEqual(1); // validator info expect(status.validatorInfo.pubkey).toBeTruthy(); expect(status.validatorInfo.votingPower).toBeGreaterThan(0); client.disconnect(); }); }); describe("blockResults", () => { it("works", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const height = 3; const results = await client.blockResults(height); expect(results.height).toEqual(height); expect(results.results).toEqual([]); expect(results.beginBlockEvents).toEqual([]); expect(results.endBlockEvents).toEqual([]); client.disconnect(); }); }); describe("blockchain", () => { it("returns latest in descending order by default", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); // Run in parallel to increase chance there is no block between the calls const [status, blockchain] = await Promise.all([client.status(), client.blockchain()]); const height = status.syncInfo.latestBlockHeight; expect(blockchain.lastHeight).toEqual(height); expect(blockchain.blockMetas.length).toBeGreaterThanOrEqual(3); expect(blockchain.blockMetas[0].header.height).toEqual(height); expect(blockchain.blockMetas[1].header.height).toEqual(height - 1); expect(blockchain.blockMetas[2].header.height).toEqual(height - 2); client.disconnect(); }); it("can limit by maxHeight", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const height = (await client.status()).syncInfo.latestBlockHeight; const blockchain = await client.blockchain(undefined, height - 1); expect(blockchain.lastHeight).toEqual(height); expect(blockchain.blockMetas.length).toBeGreaterThanOrEqual(2); expect(blockchain.blockMetas[0].header.height).toEqual(height - 1); // upper limit included expect(blockchain.blockMetas[1].header.height).toEqual(height - 2); client.disconnect(); }); it("works with maxHeight in the future", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const height = (await client.status()).syncInfo.latestBlockHeight; const blockchain = await client.blockchain(undefined, height + 20); expect(blockchain.lastHeight).toEqual(height); expect(blockchain.blockMetas.length).toBeGreaterThanOrEqual(2); expect(blockchain.blockMetas[0].header.height).toEqual(height); expect(blockchain.blockMetas[1].header.height).toEqual(height - 1); client.disconnect(); }); it("can limit by minHeight and maxHeight", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const height = (await client.status()).syncInfo.latestBlockHeight; const blockchain = await client.blockchain(height - 2, height - 1); expect(blockchain.lastHeight).toEqual(height); expect(blockchain.blockMetas.length).toEqual(2); expect(blockchain.blockMetas[0].header.height).toEqual(height - 1); // upper limit included expect(blockchain.blockMetas[1].header.height).toEqual(height - 2); // lower limit included client.disconnect(); }); it("contains all the info", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const height = (await client.status()).syncInfo.latestBlockHeight; const blockchain = await client.blockchain(height - 1, height - 1); expect(blockchain.lastHeight).toEqual(height); expect(blockchain.blockMetas.length).toBeGreaterThanOrEqual(1); const meta = blockchain.blockMetas[0]; // TODO: check all the fields expect(meta).toEqual({ blockId: jasmine.objectContaining({}), // block_size: jasmine.stringMatching(nonNegativeIntegerMatcher), // num_txs: jasmine.stringMatching(nonNegativeIntegerMatcher), header: jasmine.objectContaining({ version: { block: expected.blockVersion, app: expected.appVersion, }, chainId: jasmine.stringMatching(chainIdMatcher), }), }); client.disconnect(); }); }); describe("tx", () => { it("can query a tx properly", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const find = randomString(); const me = randomString(); const tx = buildKvTx(find, me); const txRes = await client.broadcastTxCommit({ tx: tx }); expect(responses.broadcastTxCommitSuccess(txRes)).toEqual(true); expect(txRes.height).toBeTruthy(); const height: number = txRes.height || 0; // || 0 for type system expect(txRes.hash.length).not.toEqual(0); const hash = txRes.hash; await tendermintSearchIndexUpdated(); // find by hash - does it match? const r = await client.tx({ hash: hash, prove: true }); // both values come from rpc, so same type (Buffer/Uint8Array) expect(r.hash).toEqual(hash); // force the type when comparing to locally generated value expect(r.tx).toEqual(tx); expect(r.height).toEqual(height); expect(r.proof).toBeTruthy(); // txSearch - you must enable the indexer when running // tendermint, else you get empty results const query = buildQuery({ tags: [{ key: "app.key", value: find }] }); const s = await client.txSearch({ query: query, page: 1, per_page: 30 }); // should find the tx expect(s.totalCount).toEqual(1); // should return same info as querying directly, // except without the proof expect(s.txs[0]).toEqual({ ...r, proof: undefined }); // ensure txSearchAll works as well const sall = await client.txSearchAll({ query: query }); // should find the tx expect(sall.totalCount).toEqual(1); // should return same info as querying directly, // except without the proof expect(sall.txs[0]).toEqual({ ...r, proof: undefined }); // and let's query the block itself to see this transaction const block = await client.block(height); expect(block.block.txs.length).toEqual(1); expect(block.block.txs[0]).toEqual(tx); client.disconnect(); }); }); describe("txSearch", () => { const key = randomString(); beforeAll(async () => { if (tendermintEnabled()) { const client = await Tendermint33Client.create(rpcFactory()); // eslint-disable-next-line no-inner-declarations async function sendTx(): Promise<void> { const me = randomString(); const tx = buildKvTx(key, me); const txRes = await client.broadcastTxCommit({ tx: tx }); expect(responses.broadcastTxCommitSuccess(txRes)).toEqual(true); expect(txRes.height).toBeTruthy(); expect(txRes.hash.length).not.toEqual(0); } // send 3 txs await sendTx(); await sendTx(); await sendTx(); client.disconnect(); await tendermintSearchIndexUpdated(); } }); it("returns transactions in ascending order by default", async () => { // NOTE: The Tendermint docs claim the default ordering is "desc" but it is actually "asc" // Docs: https://docs.tendermint.com/master/rpc/#/Info/tx_search // Code: https://github.com/tendermint/tendermint/blob/v0.33.9/rpc/core/tx.go#L84 pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const query = buildQuery({ tags: [{ key: "app.key", value: key }] }); const s = await client.txSearch({ query: query }); expect(s.totalCount).toEqual(3); s.txs.slice(1).reduce((lastHeight, { height }) => { expect(height).toBeGreaterThanOrEqual(lastHeight); return height; }, s.txs[0].height); client.disconnect(); }); it("can set the order", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const query = buildQuery({ tags: [{ key: "app.key", value: key }] }); const s1 = await client.txSearch({ query: query, order_by: "desc" }); const s2 = await client.txSearch({ query: query, order_by: "asc" }); expect(s1.totalCount).toEqual(s2.totalCount); expect([...s1.txs].reverse()).toEqual(s2.txs); client.disconnect(); }); it("can paginate over txSearch results", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const query = buildQuery({ tags: [{ key: "app.key", value: key }] }); // expect one page of results const s1 = await client.txSearch({ query: query, page: 1, per_page: 2 }); expect(s1.totalCount).toEqual(3); expect(s1.txs.length).toEqual(2); // second page const s2 = await client.txSearch({ query: query, page: 2, per_page: 2 }); expect(s2.totalCount).toEqual(3); expect(s2.txs.length).toEqual(1); client.disconnect(); }); it("can get all search results in one call", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const query = buildQuery({ tags: [{ key: "app.key", value: key }] }); const sall = await client.txSearchAll({ query: query, per_page: 2 }); expect(sall.totalCount).toEqual(3); expect(sall.txs.length).toEqual(3); // make sure there are in order from lowest to highest height const [tx1, tx2, tx3] = sall.txs; expect(tx2.height).toEqual(tx1.height + 1); expect(tx3.height).toEqual(tx2.height + 1); client.disconnect(); }); }); } function websocketTestSuite(rpcFactory: () => RpcClient, expected: ExpectedValues): void { it("can subscribe to block header events", (done) => { pendingWithoutTendermint(); const testStart = ReadonlyDate.now(); (async () => { const events: responses.NewBlockHeaderEvent[] = []; const client = await Tendermint33Client.create(rpcFactory()); const stream = client.subscribeNewBlockHeader(); expect(stream).toBeTruthy(); const subscription = stream.subscribe({ next: (event) => { expect(event.chainId).toMatch(chainIdMatcher); expect(event.height).toBeGreaterThan(0); // seems that tendermint just guarantees within the last second for timestamp expect(event.time.getTime()).toBeGreaterThan(testStart - 1000); // Tendermint clock is sometimes ahead of test clock. Add 10ms tolerance expect(event.time.getTime()).toBeLessThanOrEqual(ReadonlyDate.now() + 10); expect(event.lastBlockId).toBeTruthy(); // merkle roots for proofs expect(event.appHash).toBeTruthy(); expect(event.consensusHash).toBeTruthy(); expect(event.dataHash).toBeTruthy(); expect(event.evidenceHash).toBeTruthy(); expect(event.lastCommitHash).toBeTruthy(); expect(event.lastResultsHash).toBeTruthy(); expect(event.validatorsHash).toBeTruthy(); events.push(event); if (events.length === 2) { subscription.unsubscribe(); expect(events.length).toEqual(2); expect(events[1].chainId).toEqual(events[0].chainId); expect(events[1].height).toEqual(events[0].height + 1); expect(events[1].time.getTime()).toBeGreaterThan(events[0].time.getTime()); expect(events[1].appHash).toEqual(events[0].appHash); expect(events[1].consensusHash).toEqual(events[0].consensusHash); expect(events[1].dataHash).toEqual(events[0].dataHash); expect(events[1].evidenceHash).toEqual(events[0].evidenceHash); expect(events[1].lastCommitHash).not.toEqual(events[0].lastCommitHash); expect(events[1].lastResultsHash).not.toEqual(events[0].lastResultsHash); expect(events[1].validatorsHash).toEqual(events[0].validatorsHash); client.disconnect(); done(); } }, error: done.fail, complete: () => done.fail("Stream completed before we are done"), }); })().catch(done.fail); }); it("can subscribe to block events", async () => { pendingWithoutTendermint(); const testStart = ReadonlyDate.now(); const transactionData1 = buildKvTx(randomString(), randomString()); const transactionData2 = buildKvTx(randomString(), randomString()); const events: responses.NewBlockEvent[] = []; const client = await Tendermint33Client.create(rpcFactory()); const stream = client.subscribeNewBlock(); const subscription = stream.subscribe({ next: (event) => { expect(event.header.chainId).toMatch(chainIdMatcher); expect(event.header.height).toBeGreaterThan(0); // seems that tendermint just guarantees within the last second for timestamp expect(event.header.time.getTime()).toBeGreaterThan(testStart - 1000); // Tendermint clock is sometimes ahead of test clock. Add 10ms tolerance expect(event.header.time.getTime()).toBeLessThanOrEqual(ReadonlyDate.now() + 10); expect(event.header.lastBlockId).toBeTruthy(); // merkle roots for proofs expect(event.header.appHash).toBeTruthy(); expect(event.header.consensusHash).toBeTruthy(); expect(event.header.dataHash).toBeTruthy(); expect(event.header.evidenceHash).toBeTruthy(); expect(event.header.lastCommitHash).toBeTruthy(); expect(event.header.lastResultsHash).toBeTruthy(); expect(event.header.validatorsHash).toBeTruthy(); events.push(event); if (events.length === 2) { subscription.unsubscribe(); } }, error: fail, }); await client.broadcastTxCommit({ tx: transactionData1 }); await client.broadcastTxCommit({ tx: transactionData2 }); // wait for events to be processed await sleep(100); expect(events.length).toEqual(2); // Block header expect(events[1].header.height).toEqual(events[0].header.height + 1); expect(events[1].header.chainId).toEqual(events[0].header.chainId); expect(events[1].header.time.getTime()).toBeGreaterThan(events[0].header.time.getTime()); expect(events[1].header.appHash).not.toEqual(events[0].header.appHash); expect(events[1].header.validatorsHash).toEqual(events[0].header.validatorsHash); // Block body expect(events[0].txs.length).toEqual(1); expect(events[1].txs.length).toEqual(1); expect(events[0].txs[0]).toEqual(transactionData1); expect(events[1].txs[0]).toEqual(transactionData2); client.disconnect(); }); it("can subscribe to transaction events", async () => { pendingWithoutTendermint(); const events: responses.TxEvent[] = []; const client = await Tendermint33Client.create(rpcFactory()); const stream = client.subscribeTx(); const subscription = stream.subscribe({ next: (event) => { expect(event.height).toBeGreaterThan(0); expect(event.result).toBeTruthy(); expect(event.result.events.length).toBeGreaterThanOrEqual(1); events.push(event); if (events.length === 2) { subscription.unsubscribe(); } }, error: fail, }); const transactionData1 = buildKvTx(randomString(), randomString()); const transactionData2 = buildKvTx(randomString(), randomString()); await client.broadcastTxCommit({ tx: transactionData1 }); await client.broadcastTxCommit({ tx: transactionData2 }); // wait for events to be processed await sleep(100); expect(events.length).toEqual(2); // Meta expect(events[1].height).toEqual(events[0].height + 1); expect(events[1].result.events).not.toEqual(events[0].result.events); // Content expect(events[0].tx).toEqual(transactionData1); expect(events[1].tx).toEqual(transactionData2); client.disconnect(); }); it("can subscribe to transaction events filtered by creator", async () => { pendingWithoutTendermint(); const transactionData1 = buildKvTx(randomString(), randomString()); const transactionData2 = buildKvTx(randomString(), randomString()); const events: responses.TxEvent[] = []; const client = await Tendermint33Client.create(rpcFactory()); const query = buildQuery({ tags: [{ key: "app.creator", value: expected.appCreator }] }); const stream = client.subscribeTx(query); expect(stream).toBeTruthy(); const subscription = stream.subscribe({ next: (event) => { expect(event.height).toBeGreaterThan(0); expect(event.result).toBeTruthy(); expect(event.result.events.length).toBeGreaterThanOrEqual(1); events.push(event); if (events.length === 2) { subscription.unsubscribe(); } }, error: fail, }); await client.broadcastTxCommit({ tx: transactionData1 }); await client.broadcastTxCommit({ tx: transactionData2 }); // wait for events to be processed await sleep(100); expect(events.length).toEqual(2); // Meta expect(events[1].height).toEqual(events[0].height + 1); expect(events[1].result.events).not.toEqual(events[0].result.events); // Content expect(events[0].tx).toEqual(transactionData1); expect(events[1].tx).toEqual(transactionData2); client.disconnect(); }); it("can unsubscribe and re-subscribe to the same stream", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const stream = client.subscribeNewBlockHeader(); const event1 = await firstEvent(stream); expect(event1.height).toBeGreaterThanOrEqual(1); expect(event1.time.getTime()).toBeGreaterThanOrEqual(1); // No sleep: producer will not be stopped in the meantime const event2 = await firstEvent(stream); expect(event2.height).toBeGreaterThan(event1.height); expect(event2.time.getTime()).toBeGreaterThan(event1.time.getTime()); // Very short sleep: just enough to schedule asynchronous producer stopping await sleep(5); const event3 = await firstEvent(stream); expect(event3.height).toBeGreaterThan(event2.height); expect(event3.time.getTime()).toBeGreaterThan(event2.time.getTime()); // Proper sleep: enough to finish unsubscribing at over the network await sleep(100); const event4 = await firstEvent(stream); expect(event4.height).toBeGreaterThan(event3.height); expect(event4.time.getTime()).toBeGreaterThan(event3.time.getTime()); client.disconnect(); }); it("can subscribe twice", async () => { pendingWithoutTendermint(); const client = await Tendermint33Client.create(rpcFactory()); const stream1 = client.subscribeNewBlockHeader(); const stream2 = client.subscribeNewBlockHeader(); const events = await toListPromise(Stream.merge(stream1, stream2), 4); expect(new Set(events.map((e) => e.height)).size).toEqual(2); client.disconnect(); }); } describe(`Tendermint33Client`, () => { const { url, expected } = tendermintInstances[0]; it("can connect to a given url", async () => { pendingWithoutTendermint(); // default connection { const client = await Tendermint33Client.connect(url); const info = await client.abciInfo(); expect(info).toBeTruthy(); client.disconnect(); } // http connection { const client = await Tendermint33Client.connect("http://" + url); const info = await client.abciInfo(); expect(info).toBeTruthy(); client.disconnect(); } // ws connection { const client = await Tendermint33Client.connect("ws://" + url); const info = await client.abciInfo(); expect(info).toBeTruthy(); client.disconnect(); } }); describe("With HttpClient", () => { defaultTestSuite(() => new HttpClient(url), expected); }); describe("With WebsocketClient", () => { // don't print out WebSocket errors if marked pending const onError = process.env.TENDERMINT_ENABLED ? console.error : () => 0; const factory = (): WebsocketClient => new WebsocketClient(url, onError); defaultTestSuite(factory, expected); websocketTestSuite(factory, expected); }); });
the_stack
import React, { useEffect, useState } from 'react' import { DatePicker, Form, Input, Modal, Radio, Select } from 'antd' import dayjs, { Dayjs } from 'dayjs' import { PageEntity } from '@logseq/libs/dist/LSPlugin.user' import Calendar from 'tui-calendar' import type { ICustomCalendar, ISettingsForm } from '../util/type' import { deleteProjectTaskTime, genProjectTaskTime, genSchedule, getAgendaCalendars, modifyTimeInfo, removeTimeInfo, updateProjectTaskTime } from '@/util/schedule' import { createBlockToSpecificBlock, getPageData, joinPrefixTaskBlockContent, moveBlockToNewPage, moveBlockToSpecificBlock, pureTaskBlockContent, updateBlock } from '@/util/logseq' import { format } from 'date-fns' import { SCHEDULE_PARENT_BLOCK } from '@/util/constants' import { getInitalSettings, initializeSettings } from '@/util/baseInfo' import { IEvent } from '@/util/events' import { transformBlockToEvent, transformMilestoneEventToSchedule, transformTaskEventToSchedule } from '@/helper/transform' import { DEFAULT_CALENDAR_STYLE } from '@/constants/style' export type IScheduleForm = { calendarId: string title: string start: Dayjs end: Dayjs isAllDay?: boolean keepRef?: boolean } export type IScheduleValue = Partial<IScheduleForm> & { id?: string; raw?: IEvent } const ModifySchedule: React.FC<{ visible: boolean initialValues?: IScheduleValue type?: 'create' | 'update' calendar?: Calendar showKeepRef?: boolean onSave?: () => void onCancel?: () => void }> = ({ visible, initialValues, onCancel, onSave, type='create', calendar, showKeepRef }) => { console.log('[faiz:] === initialValues', initialValues) // const [agendaCalendars, setAgendaCalendars] = useState<ICustomCalendar[]>([]) const [showTime, setShowTime] = useState(!initialValues?.isAllDay) const { defaultDuration, projectList = [], journal } = getInitalSettings() const isInitialJournal = initialValues?.calendarId === 'Journal' const isInitialProject = projectList.some(({ id }) => id === initialValues?.calendarId) let projects = (!isInitialProject && !isInitialJournal && type === 'update') ? [journal, { id: initialValues?.calendarId, ...DEFAULT_CALENDAR_STYLE }, ...projectList] : [journal, ...projectList] // const oldScheduleType = logseq.settings?.projectList?.some(project => project?.id === initialValues?.calendarId) ? 'project' : 'calendar' const [form] = Form.useForm() const onFormChange = (changedValues, allValues) => { if (changedValues.isAllDay !== undefined) { setShowTime(!changedValues.isAllDay) } if (changedValues.start !== undefined) { form.setFieldsValue({ end: changedValues.start.add(defaultDuration.value, defaultDuration.unit), }) } // if (changedValues.calendarId?.value === 'journal') { // const start = allValues.start // const end = allValues.end // if (!start.isSame(end, 'day')) { // form.setFieldsValue({ // end: start.add(1, 'hour'), // }) // } // } } const onClickSave = () => { form.validateFields().then(async values => { const { title, start, end, isAllDay, calendarId } = values const startDate = dayjs(start).format('YYYY-MM-DD') const endDate = dayjs(end).format('YYYY-MM-DD') const startTime = dayjs(start).format('HH:mm') const endTime = dayjs(end).format('HH:mm') const settings = getInitalSettings() const calendarConfig = projects.find(({ id }) => id === calendarId.value) let newScheduleType: 'journal' | 'project' = calendarConfig?.id === 'Journal' ? 'journal' : 'project' console.log('[faiz:] === newScheduleType', newScheduleType) console.log('[faiz:] === onClickSave', values) // 变更后的schedule是否是journal中的schedule const isJournalSchedule = newScheduleType === 'journal' if (dayjs(start).isAfter(dayjs(end), isAllDay ? 'day' : undefined)) return logseq.App.showMsg('Start time cannot be later than end time', 'error') if (isJournalSchedule && !dayjs(start).isSame(dayjs(end), 'day')) return logseq.App.showMsg('Journal schedule cannot span multiple days', 'error') // new block content let newTitle = title if (newScheduleType === 'journal') { if (type === 'create') newTitle = isAllDay ? `TODO ${title}` : `TODO ${startTime}-${endTime} ${title}` if (type === 'update') { // const pureTitle = deleteProjectTaskTime(pureTaskBlockContent(initialValues?.raw, title)) newTitle = isAllDay ? joinPrefixTaskBlockContent(initialValues?.raw!, title) : joinPrefixTaskBlockContent(initialValues?.raw!, modifyTimeInfo(title, startTime, endTime)) } } else if (newScheduleType === 'project') { if (type === 'create') { newTitle = 'TODO ' + updateProjectTaskTime(title, { start, end, allDay: isAllDay }) } else if (type === 'update') { newTitle = joinPrefixTaskBlockContent(initialValues?.raw!, updateProjectTaskTime(title, { start, end, allDay: isAllDay })) } } // else { // if (type === 'update') { // newTitle = joinPrefixTaskBlockContent(initialValues?.raw, deleteProjectTaskTime(removeTimeInfo(pureTaskBlockContent(initialValues?.raw, title)))) // } // } // new properties const newBlockPropeties = {} const { preferredDateFormat } = await logseq.App.getUserConfigs() // oldCalendarId: journal shcedule is journal page, other is calendar id let oldCalendarId = initialValues?.calendarId if (isJournalSchedule) { const oldStart = initialValues?.start if(oldStart) oldCalendarId = format(oldStart?.valueOf(), preferredDateFormat) } // newCalendarId: journal shcedule is journal page, other is calendar id let newCalendarId = calendarId.value if (isJournalSchedule) { const journalName = format(start.valueOf(), preferredDateFormat) const newPage = await logseq.Editor.createPage(journalName, {}, { journal: true }) if (newPage) newCalendarId = newPage.originalName } if (type === 'create') { // create schedule const logKey: ISettingsForm['logKey'] = logseq.settings?.logKey let block if (isJournalSchedule) { block = logKey?.enabled ? await createBlockToSpecificBlock(newCalendarId!, `[[${logKey?.id}]]`, newTitle, newBlockPropeties) : await logseq.Editor.insertBlock(newCalendarId!, newTitle, { isPageBlock: true, sibling: true, properties: newBlockPropeties, }) } else if (newScheduleType === 'project') { block = await createBlockToSpecificBlock(newCalendarId!, SCHEDULE_PARENT_BLOCK, newTitle) } // else { // block = await createBlockToSpecificBlock(newCalendarId, SCHEDULE_PARENT_BLOCK, newTitle, newBlockPropeties) // } if (!block) return logseq.App.showMsg('Create block failed', 'error') const _block = await logseq.Editor.getBlock(block.uuid) const event = await transformBlockToEvent(_block!, settings) const schedule = event?.addOns?.type === 'milestone' ? transformMilestoneEventToSchedule(event) : transformTaskEventToSchedule(event) calendar?.createSchedules([schedule]) } else if (newCalendarId !== oldCalendarId) { // move schedule: move block to new page let newBlock const logKey: ISettingsForm['logKey'] = logseq.settings?.logKey // if (showKeepRef && values?.keepRef) { // // const block = await logseq.Editor.getBlock(initialValues?.id) // await logseq.Editor.insertBlock(initialValues?.id, `((${initialValues?.id}))${isJournalSchedule ? '' : ` #[[${newCalendarId}]]`}`, { before: false, sibling: true }) // } if (isJournalSchedule) { newBlock = logKey?.enabled ? await moveBlockToSpecificBlock(initialValues?.id!, newCalendarId!, `[[${logKey?.id}]]`) : await moveBlockToNewPage(initialValues?.id!, newCalendarId!) } else if (newScheduleType === 'project') { newBlock = await moveBlockToSpecificBlock(initialValues?.id!, newCalendarId!, SCHEDULE_PARENT_BLOCK) } // else { // newBlock = await moveBlockToSpecificBlock(initialValues.id, newCalendarId, SCHEDULE_PARENT_BLOCK) // } // 移动完成后需要设置 content await updateBlock(newBlock.uuid, newTitle, newBlockPropeties) // calendar schedule 移动到 journal project 需要去除 start end 属性 if (Object.keys(newBlockPropeties).length === 0) { await logseq.Editor.removeBlockProperty(newBlock.uuid, 'start') await logseq.Editor.removeBlockProperty(newBlock.uuid, 'end') } if (newBlock && initialValues?.calendarId) { const _newBlock = await logseq.Editor.getBlock(newBlock.uuid) // updateSchedule can't update id, so we need to create new schedule after delete old one calendar?.deleteSchedule(initialValues?.id!, initialValues.calendarId) const event = await transformBlockToEvent(_newBlock!, settings) const schedule = initialValues?.raw?.addOns.type === 'milestone' ? transformMilestoneEventToSchedule(event) : transformTaskEventToSchedule(event) calendar?.createSchedules([schedule]) } } else { // update schedule await updateBlock(initialValues?.id!, newTitle) // else { // await updateBlock(initialValues?.id!, title, newBlockPropeties) // } const blockAfterUpdated = await logseq.Editor.getBlock(initialValues?.id!) const event = await transformBlockToEvent(blockAfterUpdated!, settings) const schedule = initialValues?.raw?.addOns.type === 'task' ? transformTaskEventToSchedule(event) : transformMilestoneEventToSchedule(event) calendar?.updateSchedule(initialValues?.id!, initialValues?.calendarId!, schedule) } onSave?.() }) } const onClickCancel = () => { onCancel?.() } return ( <Modal title="Modify Schedule" visible={visible} onOk={onClickSave} onCancel={onClickCancel} > <Form form={form} onValuesChange={onFormChange} initialValues={{ isAllDay: true, ...initialValues, calendarId: initialValues?.calendarId ? { value: initialValues?.calendarId } : undefined }} > <Form.Item name="calendarId" label="Project" rules={[{ required: true }]}> <Select labelInValue> {projects.map(calendar => ( <Select.Option key={calendar?.id} value={calendar?.id}> <span style={{ width: '12px', height: '12px', display: 'inline-block', backgroundColor: calendar?.bgColor, verticalAlign: 'middle', marginRight: '5px', borderRadius: '4px'}}></span> {calendar?.id} </Select.Option> ))} </Select> </Form.Item> <Form.Item name="title" label="Schedule Title" rules={[{ required: true }]}> <Input /> </Form.Item> <Form.Item name="start" label="Start" rules={[{ required: true }]}> <DatePicker showTime={showTime ? { format: 'HH:mm' } : false} /> </Form.Item> <Form.Item name="end" label="End" rules={[{ required: true }]}> <DatePicker showTime={showTime ? { format: 'HH:mm' } : false} /> </Form.Item> <Form.Item name="isAllDay" label="All Day" rules={[{ required: true }]}> <Radio.Group> <Radio value={true}>Yes</Radio> <Radio value={false}>No</Radio> </Radio.Group> </Form.Item> {/* { showKeepRef && ( <Form.Item name="keepRef" label="Keep Ref"> <Radio.Group> <Radio value={true}>Yes</Radio> <Radio value={false}>No</Radio> </Radio.Group> </Form.Item> ) } */} </Form> </Modal> ) } export default ModifySchedule
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "../types"; import * as utilities from "../utilities"; /** * Provides an AWS App Mesh gateway route resource. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const example = new aws.appmesh.GatewayRoute("example", { * meshName: "example-service-mesh", * virtualGatewayName: aws_appmesh_virtual_gateway.example.name, * spec: { * httpRoute: { * action: { * target: { * virtualService: { * virtualServiceName: aws_appmesh_virtual_service.example.name, * }, * }, * }, * match: { * prefix: "/", * }, * }, * }, * tags: { * Environment: "test", * }, * }); * ``` * * ## Import * * App Mesh gateway routes can be imported using `mesh_name` and `virtual_gateway_name` together with the gateway route's `name`, e.g. * * ```sh * $ pulumi import aws:appmesh/gatewayRoute:GatewayRoute example mesh/gw1/example-gateway-route * ``` * * [1]/docs/providers/aws/index.html */ export class GatewayRoute extends pulumi.CustomResource { /** * Get an existing GatewayRoute resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: GatewayRouteState, opts?: pulumi.CustomResourceOptions): GatewayRoute { return new GatewayRoute(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'aws:appmesh/gatewayRoute:GatewayRoute'; /** * Returns true if the given object is an instance of GatewayRoute. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is GatewayRoute { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === GatewayRoute.__pulumiType; } /** * The ARN of the gateway route. */ public /*out*/ readonly arn!: pulumi.Output<string>; /** * The creation date of the gateway route. */ public /*out*/ readonly createdDate!: pulumi.Output<string>; /** * The last update date of the gateway route. */ public /*out*/ readonly lastUpdatedDate!: pulumi.Output<string>; /** * The name of the service mesh in which to create the gateway route. Must be between 1 and 255 characters in length. */ public readonly meshName!: pulumi.Output<string>; /** * The AWS account ID of the service mesh's owner. Defaults to the account ID the [AWS provider](https://www.terraform.io/docs/providers/aws/index.html) is currently connected to. */ public readonly meshOwner!: pulumi.Output<string>; /** * The name to use for the gateway route. Must be between 1 and 255 characters in length. */ public readonly name!: pulumi.Output<string>; /** * The resource owner's AWS account ID. */ public /*out*/ readonly resourceOwner!: pulumi.Output<string>; /** * The gateway route specification to apply. */ public readonly spec!: pulumi.Output<outputs.appmesh.GatewayRouteSpec>; /** * A map of tags to assign to the resource. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * A map of tags assigned to the resource, including those inherited from the provider . */ public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>; /** * The name of the virtual gateway to associate the gateway route with. Must be between 1 and 255 characters in length. */ public readonly virtualGatewayName!: pulumi.Output<string>; /** * Create a GatewayRoute resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: GatewayRouteArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: GatewayRouteArgs | GatewayRouteState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as GatewayRouteState | undefined; inputs["arn"] = state ? state.arn : undefined; inputs["createdDate"] = state ? state.createdDate : undefined; inputs["lastUpdatedDate"] = state ? state.lastUpdatedDate : undefined; inputs["meshName"] = state ? state.meshName : undefined; inputs["meshOwner"] = state ? state.meshOwner : undefined; inputs["name"] = state ? state.name : undefined; inputs["resourceOwner"] = state ? state.resourceOwner : undefined; inputs["spec"] = state ? state.spec : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["tagsAll"] = state ? state.tagsAll : undefined; inputs["virtualGatewayName"] = state ? state.virtualGatewayName : undefined; } else { const args = argsOrState as GatewayRouteArgs | undefined; if ((!args || args.meshName === undefined) && !opts.urn) { throw new Error("Missing required property 'meshName'"); } if ((!args || args.spec === undefined) && !opts.urn) { throw new Error("Missing required property 'spec'"); } if ((!args || args.virtualGatewayName === undefined) && !opts.urn) { throw new Error("Missing required property 'virtualGatewayName'"); } inputs["meshName"] = args ? args.meshName : undefined; inputs["meshOwner"] = args ? args.meshOwner : undefined; inputs["name"] = args ? args.name : undefined; inputs["spec"] = args ? args.spec : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["virtualGatewayName"] = args ? args.virtualGatewayName : undefined; inputs["arn"] = undefined /*out*/; inputs["createdDate"] = undefined /*out*/; inputs["lastUpdatedDate"] = undefined /*out*/; inputs["resourceOwner"] = undefined /*out*/; inputs["tagsAll"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(GatewayRoute.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering GatewayRoute resources. */ export interface GatewayRouteState { /** * The ARN of the gateway route. */ arn?: pulumi.Input<string>; /** * The creation date of the gateway route. */ createdDate?: pulumi.Input<string>; /** * The last update date of the gateway route. */ lastUpdatedDate?: pulumi.Input<string>; /** * The name of the service mesh in which to create the gateway route. Must be between 1 and 255 characters in length. */ meshName?: pulumi.Input<string>; /** * The AWS account ID of the service mesh's owner. Defaults to the account ID the [AWS provider](https://www.terraform.io/docs/providers/aws/index.html) is currently connected to. */ meshOwner?: pulumi.Input<string>; /** * The name to use for the gateway route. Must be between 1 and 255 characters in length. */ name?: pulumi.Input<string>; /** * The resource owner's AWS account ID. */ resourceOwner?: pulumi.Input<string>; /** * The gateway route specification to apply. */ spec?: pulumi.Input<inputs.appmesh.GatewayRouteSpec>; /** * A map of tags to assign to the resource. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * A map of tags assigned to the resource, including those inherited from the provider . */ tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The name of the virtual gateway to associate the gateway route with. Must be between 1 and 255 characters in length. */ virtualGatewayName?: pulumi.Input<string>; } /** * The set of arguments for constructing a GatewayRoute resource. */ export interface GatewayRouteArgs { /** * The name of the service mesh in which to create the gateway route. Must be between 1 and 255 characters in length. */ meshName: pulumi.Input<string>; /** * The AWS account ID of the service mesh's owner. Defaults to the account ID the [AWS provider](https://www.terraform.io/docs/providers/aws/index.html) is currently connected to. */ meshOwner?: pulumi.Input<string>; /** * The name to use for the gateway route. Must be between 1 and 255 characters in length. */ name?: pulumi.Input<string>; /** * The gateway route specification to apply. */ spec: pulumi.Input<inputs.appmesh.GatewayRouteSpec>; /** * A map of tags to assign to the resource. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The name of the virtual gateway to associate the gateway route with. Must be between 1 and 255 characters in length. */ virtualGatewayName: pulumi.Input<string>; }
the_stack
import React, { Component, Fragment } from 'react'; import DragResizeEngine from './drag-resize-engine'; import { observer, computed, globalContext, Editor } from '@alilc/lowcode-editor-core'; import classNames from 'classnames'; import { SimulatorContext } from '../context'; import { BuiltinSimulatorHost } from '../host'; import { OffsetObserver, Designer } from '../../designer'; import { Node } from '../../document'; import { normalizeTriggers } from '../../utils/misc'; @observer export default class BoxResizing extends Component<{ host: BuiltinSimulatorHost }> { static contextType = SimulatorContext; get host(): BuiltinSimulatorHost { return this.props.host; } get dragging(): boolean { return this.host.designer.dragon.dragging; } @computed get selecting() { const doc = this.host.currentDocument; if (!doc || doc.suspensed) { return null; } const { selection } = doc; return this.dragging ? selection.getTopNodes() : selection.getNodes(); } componentDidUpdate() { // this.hoveringCapture.setBoundary(this.outline); // this.willBind(); } render() { const { selecting } = this; if (!selecting || selecting.length < 1) { // DIRTY FIX, recore has a bug! return <Fragment />; } // const componentMeta = selecting[0].componentMeta; // const metadata = componentMeta.getMetadata(); return ( <Fragment> {selecting.map((node) => ( <BoxResizingForNode key={node.id} node={node} host={this.props.host} /> ))} </Fragment> ); } } @observer export class BoxResizingForNode extends Component<{ host: BuiltinSimulatorHost; node: Node }> { static contextType = SimulatorContext; get host(): BuiltinSimulatorHost { return this.props.host; } get dragging(): boolean { return this.host.designer.dragon.dragging; } @computed get instances() { return this.host.getComponentInstances(this.props.node); } render() { const { instances } = this; const { node } = this.props; const { designer } = this.host; if (!instances || instances.length < 1 || this.dragging) { return null; } return ( <Fragment key={node.id}> {instances.map((instance: any) => { const observed = designer.createOffsetObserver({ node, instance, }); if (!observed) { return null; } return ( <BoxResizingInstance key={observed.id} dragging={this.dragging} designer={designer} observed={observed} /> ); })} </Fragment> ); } } @observer export class BoxResizingInstance extends Component<{ observed: OffsetObserver; highlight?: boolean; dragging?: boolean; designer?: Designer; }> { // private outline: any; private willUnbind: () => any; // outline of eight direction private outlineN: any; private outlineE: any; private outlineS: any; private outlineW: any; private outlineNE: any; private outlineNW: any; private outlineSE: any; private outlineSW: any; private dragEngine: DragResizeEngine; constructor(props: any) { super(props); this.dragEngine = new DragResizeEngine(props.designer); } componentWillUnmount() { if (this.willUnbind) { this.willUnbind(); } this.props.observed.purge(); } componentDidMount() { // this.hoveringCapture.setBoundary(this.outline); this.willBind(); const resize = (e: MouseEvent, direction: string, node: any, moveX: number, moveY: number) => { const metadata = node.componentMeta.getMetadata(); if ( metadata.configure?.advanced?.callbacks && typeof metadata.configure.advanced.callbacks.onResize === 'function' ) { (e as any).trigger = direction; (e as any).deltaX = moveX; (e as any).deltaY = moveY; const cbNode = node?.isNode ? node.internalToShellNode() : node; metadata.configure.advanced.callbacks.onResize(e, cbNode); } }; const resizeStart = (e: MouseEvent, direction: string, node: any) => { const metadata = node.componentMeta.getMetadata(); if ( metadata.configure?.advanced?.callbacks && typeof metadata.configure.advanced.callbacks.onResizeStart === 'function' ) { (e as any).trigger = direction; const cbNode = node?.isNode ? node.internalToShellNode() : node; metadata.configure.advanced.callbacks.onResizeStart(e, cbNode); } }; const resizeEnd = (e: MouseEvent, direction: string, node: any) => { const metadata = node.componentMeta.getMetadata(); if ( metadata.configure?.advanced?.callbacks && typeof metadata.configure.advanced.callbacks.onResizeEnd === 'function' ) { (e as any).trigger = direction; const cbNode = node?.isNode ? node.internalToShellNode() : node; metadata.configure.advanced.callbacks.onResizeEnd(e, cbNode); } const editor = globalContext.get(Editor); const npm = node?.componentMeta?.npm; const selected = [npm?.package, npm?.componentName].filter((item) => !!item).join('-') || node?.componentMeta?.componentName || ''; editor?.emit('designer.border.resize', { selected, layout: node?.parent?.getPropValue('layout') || '', }); }; this.dragEngine.onResize(resize); this.dragEngine.onResizeStart(resizeStart); this.dragEngine.onResizeEnd(resizeEnd); } willBind() { if (this.willUnbind) { this.willUnbind(); } if ( !this.outlineN && !this.outlineE && !this.outlineS && !this.outlineW && !this.outlineNE && !this.outlineNW && !this.outlineSE && !this.outlineSW ) { return; } const unBind: any[] = []; const { node } = this.props.observed; unBind.push( ...[ this.dragEngine.from(this.outlineN, 'n', () => node), this.dragEngine.from(this.outlineE, 'e', () => node), this.dragEngine.from(this.outlineS, 's', () => node), this.dragEngine.from(this.outlineW, 'w', () => node), this.dragEngine.from(this.outlineNE, 'ne', () => node), this.dragEngine.from(this.outlineNW, 'nw', () => node), this.dragEngine.from(this.outlineSE, 'se', () => node), this.dragEngine.from(this.outlineSW, 'sw', () => node), ], ); this.willUnbind = () => { if (unBind && unBind.length > 0) { unBind.forEach((item) => { item(); }); } this.willUnbind = () => {}; }; } render() { const { observed } = this.props; if (!observed.hasOffset) { return null; } const { node, offsetWidth, offsetHeight, offsetTop, offsetLeft } = observed; let triggerVisible: any = []; const metadata = node.componentMeta.getMetadata(); if (metadata.configure?.advanced?.getResizingHandlers) { triggerVisible = metadata.configure.advanced.getResizingHandlers(node.internalToShellNode()); } triggerVisible = normalizeTriggers(triggerVisible); const baseSideClass = 'lc-borders lc-resize-side'; const baseCornerClass = 'lc-borders lc-resize-corner'; return ( <div> {triggerVisible.includes('N') && ( <div ref={(ref) => { this.outlineN = ref; }} className={classNames(baseSideClass, 'n')} style={{ height: 20, transform: `translate(${offsetLeft}px, ${offsetTop - 10}px)`, width: offsetWidth, }} /> )} {triggerVisible.includes('NE') && ( <div ref={(ref) => { this.outlineNE = ref; }} className={classNames(baseCornerClass, 'ne')} style={{ transform: `translate(${offsetLeft + offsetWidth - 5}px, ${offsetTop - 3}px)`, cursor: 'nesw-resize', }} /> )} {triggerVisible.includes('E') && ( <div className={classNames(baseSideClass, 'e')} ref={(ref) => { this.outlineE = ref; }} style={{ height: offsetHeight, transform: `translate(${offsetLeft + offsetWidth - 10}px, ${offsetTop}px)`, width: 20, }} /> )} {triggerVisible.includes('SE') && ( <div ref={(ref) => { this.outlineSE = ref; }} className={classNames(baseCornerClass, 'se')} style={{ transform: `translate(${offsetLeft + offsetWidth - 5}px, ${offsetTop + offsetHeight - 5}px)`, cursor: 'nwse-resize', }} /> )} {triggerVisible.includes('S') && ( <div ref={(ref) => { this.outlineS = ref; }} className={classNames(baseSideClass, 's')} style={{ height: 20, transform: `translate(${offsetLeft}px, ${offsetTop + offsetHeight - 10}px)`, width: offsetWidth, }} /> )} {triggerVisible.includes('SW') && ( <div ref={(ref) => { this.outlineSW = ref; }} className={classNames(baseCornerClass, 'sw')} style={{ transform: `translate(${offsetLeft - 3}px, ${offsetTop + offsetHeight - 5}px)`, cursor: 'nesw-resize', }} /> )} {triggerVisible.includes('W') && ( <div ref={(ref) => { this.outlineW = ref; }} className={classNames(baseSideClass, 'w')} style={{ height: offsetHeight, transform: `translate(${offsetLeft - 10}px, ${offsetTop}px)`, width: 20, }} /> )} {triggerVisible.includes('NW') && ( <div ref={(ref) => { this.outlineNW = ref; }} className={classNames(baseCornerClass, 'nw')} style={{ transform: `translate(${offsetLeft - 3}px, ${offsetTop - 3}px)`, cursor: 'nwse-resize', }} /> )} </div> ); } }
the_stack
import * as React from 'react' import * as Kb from '../../../common-adapters' import * as Styles from '../../../styles' import {ParticipantsRow} from '../../common' import {isLargeScreen} from '../../../constants/platform' import {SelectedEntry, DropdownEntry, DropdownText} from './dropdown' import Search from './search' import {Account} from '.' import debounce from 'lodash/debounce' import defer from 'lodash/defer' export type ToKeybaseUserProps = { isRequest: boolean recipientUsername: string errorMessage?: string onShowProfile: (username: string) => void onRemoveProfile: () => void onChangeRecipient: (recipient: string) => void onScanQRCode: (() => void) | null onSearch: () => void } const placeholderExample = isLargeScreen ? 'Ex: G12345... or you*example.com' : 'G12.. or you*example.com' const ToKeybaseUser = (props: ToKeybaseUserProps) => { if (props.recipientUsername) { // A username has been set, so display their name and avatar. return ( <ParticipantsRow heading={props.isRequest ? 'From' : 'To'} headingAlignment="Left" dividerColor={props.errorMessage ? Styles.globalColors.red : ''} style={styles.toKeybaseUser} > <Kb.Box2 direction="vertical" fullWidth={true} style={styles.inputBox}> <Kb.Box2 direction="horizontal" centerChildren={true} fullWidth={true}> <Kb.ConnectedNameWithIcon colorFollowing={true} horizontal={true} containerStyle={styles.toKeybaseUserNameWithIcon} username={props.recipientUsername} avatarStyle={styles.avatar} avatarSize={32} onClick="tracker" /> <Kb.Icon type="iconfont-remove" boxStyle={styles.keybaseUserRemoveButton} fontSize={16} color={Styles.globalColors.black_20} onClick={props.onRemoveProfile} /> </Kb.Box2> {!!props.errorMessage && ( <Kb.Text type="BodySmall" style={styles.errorText}> {props.errorMessage} </Kb.Text> )} </Kb.Box2> </ParticipantsRow> ) } // No username, so show search box. return ( <Search heading={props.isRequest ? 'From' : 'To'} onClickResult={props.onChangeRecipient} onSearch={props.onSearch} onShowTracker={props.onShowProfile} onScanQRCode={props.onScanQRCode} /> ) } export type ToStellarPublicKeyProps = { recipientPublicKey: string errorMessage?: string onChangeRecipient: (recipient: string) => void onScanQRCode: (() => void) | null setReadyToReview: (ready: boolean) => void } const ToStellarPublicKey = (props: ToStellarPublicKeyProps) => { const [recipientPublicKey, setRecipentPublicKey] = React.useState(props.recipientPublicKey) const debouncedOnChangeRecip = React.useCallback(debounce(props.onChangeRecipient, 1e3), [ props.onChangeRecipient, ]) const {setReadyToReview} = props const onChangeRecipient = React.useCallback( (recipientPublicKey: string) => { setRecipentPublicKey(recipientPublicKey) setReadyToReview(false) debouncedOnChangeRecip(recipientPublicKey) }, [setReadyToReview, debouncedOnChangeRecip] ) React.useEffect(() => { if (props.recipientPublicKey !== recipientPublicKey) { // Hot fix to let any empty string textChange callbacks happen before we change the value. defer(() => setRecipentPublicKey(props.recipientPublicKey)) } // We do not want this be called when the state changes // Only when the prop.recipientPublicKey changes. // eslint-disable-next-line react-hooks/exhaustive-deps }, [props.recipientPublicKey]) return ( <ParticipantsRow heading="To" headingAlignment="Left" headingStyle={styles.heading} dividerColor={props.errorMessage ? Styles.globalColors.red : ''} style={styles.toStellarPublicKey} > <Kb.Box2 direction="vertical" fullWidth={!Styles.isMobile} style={styles.inputBox}> <Kb.Box2 direction="horizontal" gap="xxtiny" fullWidth={!Styles.isMobile} style={styles.inputInner}> <Kb.Icon sizeType={Styles.isMobile ? 'Small' : 'Default'} type="iconfont-identity-stellar" color={ recipientPublicKey.length === 0 || props.errorMessage ? Styles.globalColors.black_20 : Styles.globalColors.black } /> <Kb.Box2 direction="horizontal" style={styles.publicKeyInputContainer}> <Kb.NewInput type="text" onChangeText={onChangeRecipient} textType="BodySemibold" hideBorder={true} containerStyle={styles.input} multiline={true} rowsMin={2} rowsMax={3} value={recipientPublicKey} /> {!recipientPublicKey && ( <Kb.Box activeOpacity={1} pointerEvents="none" style={Styles.collapseStyles([Styles.globalStyles.fillAbsolute, styles.placeholderContainer])} > <Kb.Text type="BodySemibold" style={styles.colorBlack20}> Stellar address </Kb.Text> <Kb.Text type="BodySemibold" style={styles.colorBlack20} lineClamp={1} ellipsizeMode="middle"> {placeholderExample} </Kb.Text> </Kb.Box> )} </Kb.Box2> {!recipientPublicKey && props.onScanQRCode && ( <Kb.Icon color={Styles.globalColors.black_50} type="iconfont-qr-code" onClick={props.onScanQRCode} style={styles.qrCode} /> )} </Kb.Box2> {!!props.errorMessage && ( <Kb.Text type="BodySmall" style={styles.errorText}> {props.errorMessage} </Kb.Text> )} </Kb.Box2> </ParticipantsRow> ) } export type ToOtherAccountProps = { user: string toAccount?: Account allAccounts: Account[] onChangeRecipient: (recipient: string) => void onLinkAccount: () => void onCreateNewAccount: () => void showSpinner: boolean } class ToOtherAccount extends React.Component<ToOtherAccountProps> { onAccountDropdownChange = (node: React.ReactNode) => { if (React.isValidElement(node)) { const element: React.ReactElement = node if (element.key === 'create-new') { this.props.onCreateNewAccount() } else if (element.key === 'link-existing') { this.props.onLinkAccount() } else { this.props.onChangeRecipient(element.props.account.id) } } } render() { if (this.props.allAccounts.length <= 1) { // A user is sending to another account, but has no other // accounts. Show a "create new account" button. return ( <ParticipantsRow heading="To" headingAlignment="Right" style={styles.toAccountRow}> <Kb.Button small={true} type="Wallet" style={styles.createNewAccountButton} label="Create a new account" onClick={this.props.onCreateNewAccount} /> </ParticipantsRow> ) } // A user is sending from an account to another account with other // accounts. Show a dropdown list of other accounts, in addition // to the link existing and create new actions. let items = [ <DropdownText spinner={this.props.showSpinner} key="link-existing" text="Link an existing Stellar account" />, <DropdownText spinner={this.props.showSpinner} key="create-new" text="Create a new account" />, ] if (this.props.allAccounts.length > 0) { const walletItems = this.props.allAccounts.map(account => ( <DropdownEntry key={account.id} account={account} user={this.props.user} /> )) items = walletItems.concat(items) } return ( <ParticipantsRow heading="To" headingAlignment="Right" style={styles.toAccountRow}> <Kb.Dropdown onChanged={this.onAccountDropdownChange} items={items} style={styles.dropdown} selectedBoxStyle={styles.dropdownSelectedBox} selected={ this.props.toAccount ? ( <SelectedEntry spinner={this.props.showSpinner} account={this.props.toAccount} user={this.props.user} /> ) : ( <DropdownText spinner={this.props.showSpinner} key="placeholder-select" text="Pick another account" /> ) } /> </ParticipantsRow> ) } } const styles = Styles.styleSheetCreate( () => ({ avatar: { marginRight: 8, }, colorBlack20: { color: Styles.globalColors.black_20, }, createNewAccountButton: Styles.platformStyles({ isElectron: { width: 194, }, }), dropdown: Styles.platformStyles({ isMobile: {height: 32}, }), dropdownSelectedBox: Styles.platformStyles({ isMobile: {minHeight: 32}, }), errorText: Styles.platformStyles({ common: { color: Styles.globalColors.redDark, width: '100%', }, isElectron: { wordWrap: 'break-word', }, }), heading: { alignSelf: 'flex-start', }, input: Styles.platformStyles({ common: { padding: 0, }, isMobile: { paddingLeft: Styles.globalMargins.xtiny, }, }), inputBox: Styles.platformStyles({isElectron: {flexGrow: 1}, isMobile: {flex: 1}}), inputInner: Styles.platformStyles({ common: { alignItems: 'flex-start', flex: 1, position: 'relative', }, isElectron: { flexShrink: 0, }, }), keybaseUserRemoveButton: { flex: 1, marginRight: Styles.globalMargins.tiny, textAlign: 'right', // consistent with UserInput }, placeholderContainer: Styles.platformStyles({ common: { display: 'flex', flexDirection: 'column', paddingLeft: (Styles.isMobile ? 0 : 16) + 4, }, isElectron: { pointerEvents: 'none', }, }), publicKeyInputContainer: {flexGrow: 1, flexShrink: 1}, qrCode: { marginRight: Styles.globalMargins.tiny, marginTop: Styles.globalMargins.tiny, }, toAccountRow: Styles.platformStyles({ isMobile: { height: 40, paddingBottom: 4, paddingTop: 4, }, }), toKeybaseUser: { height: 48, }, toKeybaseUserNameWithIcon: { flexGrow: 1, }, toStellarPublicKey: { alignItems: 'flex-start', minHeight: 52, }, } as const) ) export {ToKeybaseUser, ToStellarPublicKey, ToOtherAccount}
the_stack
declare module 'passable' { const passable: Passable; const enforce: (value) => PassableNS.IEnforceInstance; const Enforce: PassableNS.IEnforceConstructor; const validate: PassableNS.IValidate; const WARN: PassableNS.IWARN; const FAIL: PassableNS.IFAIL; const VERSION: PassableNS.IVERSION; export default passable; export { enforce, Enforce, validate, WARN, FAIL, VERSION }; interface Passable { (name: string, testFn: (test: (name: string, errorMessage: string, callback: PassableNS.IFunctionOrPromise) => void, draft: PassableNS.IValidationResult) => void, specific?: string | string[] | {only?: string | string[], not?: string | string[]}): PassableNS.IValidationResult, enforce(value): PassableNS.IEnforceInstance; test(name: string, errorMessage: string, callback: PassableNS.IFunctionOrPromise): void; draft(): PassableNS.IEnforceInstance; Enforce: PassableNS.IEnforceConstructor; any: PassableNS.IAny; validate: PassableNS.IValidate; VERSION: PassableNS.IVERSION; WARN: PassableNS.IWARN; FAIL: PassableNS.IFAIL; } namespace PassableNS { export interface IValidationResult { /** * The name of the form being validated */ name: string; /** * Overall errors count in current validation suite */ failCount: number; /** * All skipped fields in suite (empty, unless the specific option is used) */ skipped: string[]; /** * Overall warnings count in current validation suite */ testCount: number; /** * Detailed stats per field (structure detailed below) */ testsPerformed: { [fieldName: string]: { /** * Overall test count in this field */ testCount: number; /** * Overall errors count for this field */ failCount: number; /** * Overall warnings count for this field */ warnCount: number; } }; /** * Actual errors per each field */ errors: { [fieldName: string]: string[]; }; /** * Actual errors per each field */ warnings: { [fieldName: string]: string[]; }; /** * Overall warnings count for this form */ warnCount: number; /** * Getter function which allows accessing the errors array of a certain field (or the whole suite if not supplied) */ getErrors: (field?: string) => any[]; /** * Getter function which allows accessing the warnings array of a certain field (or the whole suite if not supplied) */ getWarnings: (field?: string) => any[]; /** * Returns whether a certain field (or the whole suite if not supplied) has errors */ hasErrors: (field?: string) => boolean; /** * Returns whether a certain field (or the whole suite if not supplied) has warnings */ hasWarnings: (field?: string) => boolean; /** * Registers a completion callback for the validation suite */ done: (callback: (res: PassableNS.IValidationResult) => void) => PassableNS.IValidationResult; /** * Registers a completion callback for a specific field */ after: (fieldName: string, callback: (res: PassableNS.IValidationResult) => void) => PassableNS.IValidationResult; /** * Cancels Async tests callbacks (after/done) */ cancel: () => PassableNS.IValidationResult; } export type IFunctionOrPromise = () => void | Promise<any>; export type IVERSION = string; export type IWARN = 'warn'; export type IFAIL = 'fail'; export interface IValidate { (): boolean; } export interface IAny { (): boolean; } type IEnforceChain<T> = { [K in keyof T]: IEnforceInstance }; export type IEnforceConstructor = { new(): (value) => IEnforceInstance; new<T extends { [key: string]: (...args) => boolean }> (arg: T): (value) => IEnforceInstance<IEnforceChain<T>>; }; export interface IEnforceInstance<T = {}> { /** * Checks if a value contains a regex match by Regex expression * * @example * enforce(1984).matches(/[0-9]/) // truthy * * enforce('nineteen eighty four').matches(/[0-9]/) // falsy */ matches(regex: RegExp): IEnforceInstance & T; /** * Checks if a value contains a regex match by a string expression * * @example * enforce(1984).matches('[0-9]') //truthy * * enforce('nineteen eighty four').matches('[0-9]') // falsy */ matches(regexAsString: string): IEnforceInstance & T; /** * Checks if a value doesn't contains a regex match by Regex expression * * @example * enforce(1984).notMatches(/[0-9]/) // falsy */ notMatches(regex: RegExp): IEnforceInstance & T; /** * Checks if a value doesn't contains a regex match by string expression * * @example * enforce('nineteen eighty four').notMatches('[0-9]') // truthy */ notMatches(regexAsString: string): IEnforceInstance & T; /** * Checks if your enforce value is contained in another array * * @example * enforce('hello').inside(['hello', 'world']) // truthy * * enforce(3).inside([1, 2]) // falsy * * enforce(false).inside([true, false]) // truthy */ inside(array: number[] | string[] | boolean[]): IEnforceInstance & T; /** * Checks if your enforce value is contained in another string * * @example * enforce('da').inside('tru dat.') // truthy * * enforce('ad').inside('tru dat.') // falsy */ inside(text: string): IEnforceInstance & T; /** * Checks if your enforce value is not contained in another array * * @example * enforce('hello').notInside(['hello', 'world']) // falsy */ notInside(array: number[] | string[] | boolean[]): IEnforceInstance & T; /** * Checks if your enforce value is not contained in another string * * @example * enforce('ad').notInside('tru dat.') // truthy */ notInside(text: string): IEnforceInstance & T; /** * Checks if a value is of type Array * * @example * enforce(['hello']).isArray() // truthy * * enforce('hello').isArray() // falsy */ isArray(): IEnforceInstance & T; /** * Checks if a value is of any type other than array * * @example * enforce(['hello']).isNotArray() // falsy * * enforce('hello').isNotArray() // truthy */ isNotArray(): IEnforceInstance & T; /** * Checks if a value is of type String * * @example * enforce('hello').isString() // truthy * * enforce(['hello']).isString() // falsy */ isString(): IEnforceInstance & T; /** * Checks if a value is of any type other than string * * @example * enforce('hello').isNotString() // falsy * * enforce(['hello']).isNotString() // truthy */ isNotString(): IEnforceInstance & T; /** * Checks if a value is of type number * * @example * enforce(143).isNumber() // truthy * * enforce(NaN).isNumber() // truthy! (NaN is of type 'number!') */ isNumber(): IEnforceInstance & T; /** * Checks if a value is of any type other than number * * @example * enforce(143).isNotNumber() // falsy * * enforce('143').isNotNumber() // truthy */ isNotNumber(): IEnforceInstance & T; /** * Checks if your enforce value is empty, false, zero, null or undefined * * @example * enforce([]).isEmpty() // truthy * * enforce('').isEmpty() // truthy * * enforce({}).isEmpty() // truthy */ isEmpty(): IEnforceInstance & T; /** * Checks that your enforce value is not empty, false, or zero * * @example * * enforce([1]).isNotEmpty() // truthy * * enforce({1:1}).isNotEmpty() // truthy * * enforce([]).isNotEmpty() // falsy */ isNotEmpty(): IEnforceInstance & T; /** * Checks that your enforce value is a numeric value * * @example * * enforce('-0x42').isNumeric() // falsy * * enforce('0xFF').isNumeric() // truthy */ isNumeric(): IEnforceInstance & T; /** * Checks that your enforce value is not a numeric value * * @example * * enforce('7.2acdgs').isNotNumeric() // truthy * * enforce('-10').isNotNumeric() // falsy */ isNotNumeric(): IEnforceInstance & T; /** * Checks that your numeric enforce value is smaller than another value * * @example * * enforce(0).lessThan(1) // truthy * * enforce('1').lessThan(0) // falsy */ lessThan(size: number): IEnforceInstance & T; /** * Checks that your numeric enforce value is smaller than another value * * @example * * enforce(0).lt(1) // truthy * * enforce('1').lt(0) // falsy */ lt(size: number): IEnforceInstance & T; /** * Checks that your numeric enforce value is smaller than or equals another value * * @example * * enforce(0).lessThanOrEquals(1) // truthy * * enforce('1').lessThanOrEquals(1) // truthy * * enforce(2).lessThanOrEquals(1) // falsy */ lessThanOrEquals(size: number): IEnforceInstance & T; /** * Checks that your numeric enforce value is smaller than or equals another value * * @example * * enforce(0).lte(1) // truthy * * enforce('1').lte(1) // truthy * * enforce(2).lte('1') // falsy */ lte(size: number): IEnforceInstance & T; /** * Checks that your numeric enforce value is greater than another value * * @example * * enforce(1).greaterThan(0) // truthy * * enforce('0').greaterThan('1') // falsy */ greaterThan(size: number): IEnforceInstance & T; /** * Checks that your numeric enforce value is greater than another value * * @example * * enforce(1).gt(0) // truthy * * enforce(0).gt('1') // falsy */ gt(size: number): IEnforceInstance & T; /** * Checks that your numeric enforce value is greater than or equals another value * * @example * * enforce(1).greaterThanOrEquals(1) // truthy * * enforce('1').greaterThanOrEquals(0) // truthy * * enforce('2').greaterThanOrEquals(3) // falsy */ greaterThanOrEquals(size: number): IEnforceInstance & T; /** * Checks that your numeric enforce value is greater than or equals another value * * @example * * enforce(1).gte(1) // truthy * * enforce('1').gte(0) // truthy * * enforce(2).gte('3') // falsy */ gte(size: number): IEnforceInstance & T; /** * Checks that your enforce value equals a given number * * @example * * enforce('1').numberEquals(1) // truthy * * enforce(2).numberEquals(2) // truthy * * enforce('2').numberEquals(0) // falsy */ numberEquals(size: number): IEnforceInstance & T; /** * Checks that your enforce value does not equal a given number * * @example * * enforce(3).numberNotEquals(1) // truthy * * enforce('3').numberNotEquals(3) // falsy */ numberNotEquals(size: number): IEnforceInstance & T; /** * Checks that your enforce value is longer than a given number * * @example * * enforce(['one']).longerThan(0) // truthy * * enforce('').longerThan(0) // falsy */ longerThan(size: number): IEnforceInstance & T; /** * Checks that your enforce value is longer than or equals another value * * @example * * enforce([1]).longerThanOrEquals(0) // truthy * * enforce('').longerThanOrEquals(1) // falsy */ longerThanOrEquals(size: number): IEnforceInstance & T; /** * Checks that your enforce value is shorter than a given number * * @example * * enforce([]).shorterThan(1) // truthy * * enforce('0').shorterThan(0) // falsy */ shorterThan(size: number): IEnforceInstance & T; /** * Checks that your enforce value is shorter than or equals another value * * @example * * enforce([]).shorterThanOrEquals(1) // truthy * * enforce('0').shorterThanOrEquals(0) // falsy */ shorterThanOrEquals(size: number): IEnforceInstance & T; /** * Checks that your enforce value equals a given number * * @example * * enforce([1]).lengthEquals(1) // truthy * * enforce('0').lengthEquals(0) // falsy */ lengthEquals(size: number): IEnforceInstance & T; /** * Checks that your enforce value does not equal a given number * * @example * * enforce([]).lengthNotEquals(1) // truthy * * enforce('').lengthNotEquals(0) // falsy */ lengthNotEquals(size: number): IEnforceInstance & T; /** * Checks that your enforce value strictly equals (===) a given value * * @example * * enforce(1).equals(1) // truthy * * enforce('hello').equals('hello') // truthy * * enforce('1').equals(1) // falsy * * enforce([1]).equals([1]) // falsy */ equals(value: any): IEnforceInstance & T; /** * Checks that your enforce value doesn't strictly equal (===) a given value * * @example * * enforce('1').notEquals(1) // truthy * * enforce([1]).notEquals([1]) // truthy * * enforce(1).notEquals(1) // falsy * * enforce('hello').notEquals('hello') // falsy */ notEquals(value: any): IEnforceInstance & T; } } }
the_stack
import { Component, OnInit, OnDestroy } from '@angular/core'; import { HttpErrorResponse, HttpResponse } from '@angular/common/http'; import { Subscription } from 'rxjs'; import { JhiEventManager, JhiAlertService } from 'ng-jhipster'; import { Router } from '@angular/router'; import { IBroker } from 'app/shared/model/broker.model'; import { AccountService } from 'app/core'; import { BrokerService } from './broker.service'; enum Status { active = 'active', paused = 'paused', inactive = 'inactive', inactiveError = 'inactiveError', activeError = 'activeError' } @Component({ selector: 'jhi-broker', templateUrl: './broker.component.html' }) export class BrokerComponent implements OnInit, OnDestroy { brokers: IBroker[]; broker: IBroker; currentAccount: any; eventSubscriber: Subscription; public isBrokerStarted: boolean; public isBrokerRestarted: boolean; public isBrokerStopped: boolean; public isBrokerPaused: boolean; public isBrokerResumed: boolean; public disableActionBtns: boolean; public brokerDetails: string; public brokerInfo: string; public brokerStatus: string; public brokerStatusError: string; public isBrokerStatusOK: boolean; public brokerStatusButton: string; lastError: string; constructor( protected brokerService: BrokerService, protected jhiAlertService: JhiAlertService, protected eventManager: JhiEventManager, protected accountService: AccountService, protected router: Router ) { this.router.routeReuseStrategy.shouldReuseRoute = function() { return false; }; } ngOnInit() { this.setBrokerStatusDefaults(); this.loadAll(); this.accountService.identity().then(account => { this.currentAccount = account; }); this.registerChangeInBrokers(); } ngOnDestroy() { this.eventManager.destroy(this.eventSubscriber); } loadAll() { this.brokerService.query().subscribe( (res: HttpResponse<IBroker[]>) => { this.brokers = res.body; if (this.brokers[0]) { this.broker = this.brokers[0]; this.getbrokerStatus(this.broker.id); } else { this.setbrokerStatus('unconfigured'); } }, (res: HttpErrorResponse) => this.onError(res.message) ); } getbrokerStatus(id: number) { this.brokerService.getBrokerStatus(id, this.broker.type).subscribe(response => { this.setbrokerStatus(response.body); }); } setbrokerStatus(status: string): void { switch (status) { case 'unconfigured': this.brokerStatus = Status.inactive; this.isBrokerStarted = this.isBrokerPaused = false; this.isBrokerStopped = this.isBrokerRestarted = this.isBrokerResumed = true; this.brokerStatusButton = ` Last action: - <br/> Status: Stopped<br/> `; break; case 'started with errors': this.brokerStatus = Status.activeError; this.isBrokerPaused = this.isBrokerStopped = this.isBrokerRestarted = false; this.isBrokerStarted = this.isBrokerResumed = true; this.brokerStatusButton = ` Last action: Start <br/> Status: Started with error (check logs) `; break; case 'started': this.brokerStatus = Status.active; this.isBrokerPaused = this.isBrokerStopped = this.isBrokerRestarted = false; this.isBrokerStarted = this.isBrokerResumed = true; this.brokerStatusButton = ` Last action: Start <br/> Status: Started succesfullly `; break; case 'restarted': this.brokerStatus = Status.active; this.isBrokerPaused = this.isBrokerStopped = this.isBrokerRestarted = false; this.isBrokerResumed = this.isBrokerStarted = true; this.brokerStatusButton = ` Last action: Restart <br/> Status: Restarted succesfully `; break; case 'stopped': this.brokerStatus = Status.inactive; this.isBrokerStarted = this.isBrokerPaused = false; this.isBrokerStopped = this.isBrokerRestarted = this.isBrokerResumed = true; this.brokerStatusButton = ` Last action: Stop <br/> Status: Stopped succesfully `; break; default: this.isBrokerStarted = this.isBrokerPaused = false; this.isBrokerStopped = this.isBrokerRestarted = this.isBrokerResumed = true; this.brokerStatusButton = ` Message: ${status} <br/> Status: Stopped after error `; this.brokerStatus = 'inactiveError'; break; } } setBrokerStatusDefaults() { this.isBrokerStatusOK = true; this.brokerStatus = 'unconfigured'; this.lastError = ''; this.setbrokerStatus('unconfigured'); } getBrokerInfo(id: number) { this.brokerService.getBrokerInfo(id, this.broker.type).subscribe(res => { this.setBrokerInfo(res.body); }); } setBrokerInfo(info: String) { if (info.startsWith('no info')) { this.brokerInfo = `Currently there are no statistics for this flow.`; } else { var infoSplitted = info.split(','); const uptime = infoSplitted[0].split('=').pop(); const totalConnections = infoSplitted[1].split('=').pop(); const totalConsumers = infoSplitted[2].split('=').pop(); const totalMessages = infoSplitted[3].split('=').pop(); const nodeId = infoSplitted[4].split('=').pop(); const state = infoSplitted[5].split('=').pop(); const version = infoSplitted[6].split('=')[1]; const type = infoSplitted[7].split('=')[1]; this.brokerInfo = ` <br/> <b>Broker type:</b> ${type}<br/> <b>Broker version:</b> ${version}<br/> <b>Broker Node ID:</b> ${nodeId}<br/> <br/> <b>Broker state:</b> ${state}<br/> <b>Broker uptime:</b> ${uptime}<br/> <br/> <b>Total Connections:</b> ${totalConnections}<br/> <b>Total Consumers:</b> ${totalConsumers}<br/> <b>Total Messages:</b> ${totalMessages}<br/>`; } } start() { this.isBrokerStatusOK = true; this.disableActionBtns = true; this.brokerService.start(this.broker.id, this.broker.type, this.broker.configurationType).subscribe( response => { if (response.status === 200) { this.setbrokerStatus(response.body); } this.disableActionBtns = false; }, err => { //this.getFlowLastError(this.broker.id, 'Start', err.error); this.isBrokerStatusOK = false; this.brokerStatusError = `Broker with id=${this.broker.id} is not started.`; this.disableActionBtns = false; this.setbrokerStatus(err.body); } ); } restart() { this.isBrokerStatusOK = true; this.disableActionBtns = true; this.brokerService.restart(this.broker.id, this.broker.type, this.broker.configurationType).subscribe( response => { if (response.status === 200) { if (response.body === 'started') { this.setbrokerStatus('restarted'); } else { this.setbrokerStatus(response.body); } } this.disableActionBtns = false; }, err => { //this.getFlowLastError(this.broker.id, 'Restart', err.error); this.isBrokerStatusOK = false; this.brokerStatusError = `Flow with id=${this.broker.id} is not restarted.`; this.disableActionBtns = false; this.setbrokerStatus(err.body); } ); } stop() { this.isBrokerStatusOK = true; this.disableActionBtns = true; this.brokerService.stop(this.broker.id, this.broker.type, this.broker.configurationType).subscribe( response => { if (response.status === 200) { this.setbrokerStatus(response.body); } this.disableActionBtns = false; }, err => { //this.getFlowLastError(this.broker.id, 'Stop', err.error); this.isBrokerStatusOK = false; this.brokerStatusError = `Flow with id=${this.broker.id} is not stopped.`; this.disableActionBtns = false; } ); } getBrokerDetails() { this.brokerDetails = ` <b>ID:</b> ${this.broker.id}<br/> <b>Name:</b> ${this.broker.name}<br/> <b>Type:</b> ${this.broker.type}<br/> <b>Autostart:</b> ${this.broker.autoStart}<br/> <b>Configuration Type:</b> ${this.broker.configurationType}<br/> `; } trackId(index: number, item: IBroker) { return item.id; } registerChangeInBrokers() { this.eventSubscriber = this.eventManager.subscribe('brokerListModification', response => this.loadAll()); } protected onError(errorMessage: string) { this.jhiAlertService.error(errorMessage, null, null); } }
the_stack
import { test as _test } from '../testlib'; import * as expect from 'expect'; import * as promisify from 'util.promisify'; import * as getStream from 'get-stream'; import { CMD_TS_NODE_WITH_PROJECT_FLAG, contextTsNodeUnderTest, ROOT_DIR, TEST_DIR, } from '../helpers'; import { dirname, join } from 'path'; import { createExec, createExecTester } from '../exec-helpers'; import { homedir } from 'os'; import { contextReplHelpers } from './helpers'; const test = _test.context(contextTsNodeUnderTest).context(contextReplHelpers); const exec = createExec({ cwd: TEST_DIR, }); const execTester = createExecTester({ cmd: CMD_TS_NODE_WITH_PROJECT_FLAG, exec, }); test.suite( '[eval], <repl>, and [stdin] execute with correct globals', (test) => { interface GlobalInRepl extends NodeJS.Global { testReport: any; replReport: any; stdinReport: any; evalReport: any; module: any; exports: any; fs: any; __filename: any; __dirname: any; } const globalInRepl = global as GlobalInRepl; const programmaticTest = test.macro( ( { evalCodeBefore, stdinCode, waitFor, }: { evalCodeBefore: string | null; stdinCode: string; waitFor?: () => boolean; }, assertions: (stdout: string) => Promise<void> | void ) => async (t) => { delete globalInRepl.testReport; delete globalInRepl.replReport; delete globalInRepl.stdinReport; delete globalInRepl.evalReport; delete globalInRepl.module; delete globalInRepl.exports; delete globalInRepl.fs; delete globalInRepl.__filename; delete globalInRepl.__dirname; const { stdin, stderr, stdout, replService } = t.context.createReplViaApi({ registerHooks: true }); if (typeof evalCodeBefore === 'string') { replService.evalCode(evalCodeBefore); } replService.start(); stdin.write(stdinCode); stdin.end(); let done = false; await Promise.race([ promisify(setTimeout)(20e3), (async () => { while (!done && !waitFor?.()) { await promisify(setTimeout)(1e3); } })(), ]); done = true; stdout.end(); stderr.end(); expect(await getStream(stderr)).toBe(''); await assertions(await getStream(stdout)); } ); const declareGlobals = `declare var replReport: any, stdinReport: any, evalReport: any, restReport: any, global: any, __filename: any, __dirname: any, module: any, exports: any;`; function setReportGlobal(type: 'repl' | 'stdin' | 'eval') { return ` ${declareGlobals} global.${type}Report = { __filename: typeof __filename !== 'undefined' && __filename, __dirname: typeof __dirname !== 'undefined' && __dirname, moduleId: typeof module !== 'undefined' && module.id, modulePath: typeof module !== 'undefined' && module.path, moduleFilename: typeof module !== 'undefined' && module.filename, modulePaths: typeof module !== 'undefined' && [...module.paths], exportsTest: typeof exports !== 'undefined' ? module.exports === exports : null, stackTest: new Error().stack!.split('\\n')[1], moduleAccessorsTest: eval('typeof fs') === 'undefined' ? null : eval('fs') === require('fs'), argv: [...process.argv] }; `.replace(/\n/g, ''); } const reportsObject = ` { stdinReport: typeof stdinReport !== 'undefined' && stdinReport, evalReport: typeof evalReport !== 'undefined' && evalReport, replReport: typeof replReport !== 'undefined' && replReport } `; const printReports = ` ${declareGlobals} console.log(JSON.stringify(${reportsObject})); `.replace(/\n/g, ''); const saveReportsAsGlobal = ` ${declareGlobals} global.testReport = ${reportsObject}; `.replace(/\n/g, ''); function parseStdoutStripReplPrompt(stdout: string) { // Strip node's welcome header, only uncomment if running these tests manually against vanilla node // stdout = stdout.replace(/^Welcome to.*\nType "\.help" .*\n/, ''); expect(stdout.slice(0, 2)).toBe('> '); expect(stdout.slice(-12)).toBe('undefined\n> '); return parseStdout(stdout.slice(2, -12)); } function parseStdout(stdout: string) { return JSON.parse(stdout); } /** Every possible ./node_modules directory ascending upwards starting with ./tests/node_modules */ const modulePaths = createModulePaths(TEST_DIR); const rootModulePaths = createModulePaths(ROOT_DIR); function createModulePaths(dir: string) { const modulePaths: string[] = []; for (let path = dir; ; path = dirname(path)) { modulePaths.push(join(path, 'node_modules')); if (dirname(path) === path) break; } return modulePaths; } // Executable is `ts-node` on Posix, `bin.js` on Windows due to Windows shimming limitations (this is determined by package manager) const tsNodeExe = expect.stringMatching(/\b(ts-node|bin.js)$/); test('stdin', async (t) => { const { stdout } = await execTester({ stdin: `${setReportGlobal('stdin')};${printReports}`, flags: '', }); const report = parseStdout(stdout); expect(report).toMatchObject({ stdinReport: { __filename: '[stdin]', __dirname: '.', moduleId: '[stdin]', modulePath: '.', // Note: vanilla node does does not have file extension moduleFilename: join(TEST_DIR, `[stdin].ts`), modulePaths, exportsTest: true, // Note: vanilla node uses different name. See #1360 stackTest: expect.stringContaining( ` at ${join(TEST_DIR, `[stdin].ts`)}:1:` ), moduleAccessorsTest: null, argv: [tsNodeExe], }, evalReport: false, replReport: false, }); }); test('repl', async (t) => { const { stdout } = await execTester({ stdin: `${setReportGlobal('repl')};${printReports}`, flags: '-i', }); const report = parseStdoutStripReplPrompt(stdout); expect(report).toMatchObject({ stdinReport: false, evalReport: false, replReport: { __filename: false, __dirname: false, moduleId: '<repl>', modulePath: '.', moduleFilename: null, modulePaths: expect.objectContaining({ ...[join(TEST_DIR, `repl/node_modules`), ...modulePaths], }), // Note: vanilla node REPL does not set exports exportsTest: true, // Note: vanilla node uses different name. See #1360 stackTest: expect.stringContaining( ` at ${join(TEST_DIR, '<repl>.ts')}:4:` ), moduleAccessorsTest: true, argv: [tsNodeExe], }, }); // Prior to these, nyc adds another entry on Windows; we need to ignore it expect(report.replReport.modulePaths.slice(-3)).toMatchObject([ join(homedir(), `.node_modules`), join(homedir(), `.node_libraries`), // additional entry goes to node's install path expect.any(String), ]); }); // Should ignore -i and run the entrypoint test('-i w/entrypoint ignores -i', async (t) => { const { stdout } = await execTester({ stdin: `${setReportGlobal('repl')};${printReports}`, flags: '-i ./repl/script.js', }); const report = parseStdout(stdout); expect(report).toMatchObject({ stdinReport: false, evalReport: false, replReport: false, }); }); // Should not execute stdin // Should not interpret positional arg as an entrypoint script test('-e', async (t) => { const { stdout } = await execTester({ stdin: `throw new Error()`, flags: `-e "${setReportGlobal('eval')};${printReports}"`, }); const report = parseStdout(stdout); expect(report).toMatchObject({ stdinReport: false, evalReport: { __filename: '[eval]', __dirname: '.', moduleId: '[eval]', modulePath: '.', // Note: vanilla node does does not have file extension moduleFilename: join(TEST_DIR, `[eval].ts`), modulePaths: [...modulePaths], exportsTest: true, // Note: vanilla node uses different name. See #1360 stackTest: expect.stringContaining( ` at ${join(TEST_DIR, `[eval].ts`)}:1:` ), moduleAccessorsTest: true, argv: [tsNodeExe], }, replReport: false, }); }); test('-e w/entrypoint arg does not execute entrypoint', async (t) => { const { stdout } = await execTester({ stdin: `throw new Error()`, flags: `-e "${setReportGlobal( 'eval' )};${printReports}" ./repl/script.js`, }); const report = parseStdout(stdout); expect(report).toMatchObject({ stdinReport: false, evalReport: { __filename: '[eval]', __dirname: '.', moduleId: '[eval]', modulePath: '.', // Note: vanilla node does does not have file extension moduleFilename: join(TEST_DIR, `[eval].ts`), modulePaths, exportsTest: true, // Note: vanilla node uses different name. See #1360 stackTest: expect.stringContaining( ` at ${join(TEST_DIR, `[eval].ts`)}:1:` ), moduleAccessorsTest: true, argv: [tsNodeExe, './repl/script.js'], }, replReport: false, }); }); test('-e w/non-path arg', async (t) => { const { stdout } = await execTester({ stdin: `throw new Error()`, flags: `-e "${setReportGlobal( 'eval' )};${printReports}" ./does-not-exist.js`, }); const report = parseStdout(stdout); expect(report).toMatchObject({ stdinReport: false, evalReport: { __filename: '[eval]', __dirname: '.', moduleId: '[eval]', modulePath: '.', // Note: vanilla node does does not have file extension moduleFilename: join(TEST_DIR, `[eval].ts`), modulePaths, exportsTest: true, // Note: vanilla node uses different name. See #1360 stackTest: expect.stringContaining( ` at ${join(TEST_DIR, `[eval].ts`)}:1:` ), moduleAccessorsTest: true, argv: [tsNodeExe, './does-not-exist.js'], }, replReport: false, }); }); test('-e -i', async (t) => { const { stdout } = await execTester({ stdin: `${setReportGlobal('repl')};${printReports}`, flags: `-e "${setReportGlobal('eval')}" -i`, }); const report = parseStdoutStripReplPrompt(stdout); expect(report).toMatchObject({ stdinReport: false, evalReport: { __filename: '[eval]', __dirname: '.', moduleId: '[eval]', modulePath: '.', // Note: vanilla node does does not have file extension moduleFilename: join(TEST_DIR, `[eval].ts`), modulePaths, exportsTest: true, // Note: vanilla node uses different name. See #1360 stackTest: expect.stringContaining( ` at ${join(TEST_DIR, `[eval].ts`)}:1:` ), moduleAccessorsTest: true, argv: [tsNodeExe], }, replReport: { __filename: '[eval]', __dirname: '.', moduleId: '<repl>', modulePath: '.', moduleFilename: null, modulePaths: expect.objectContaining({ ...[join(TEST_DIR, `repl/node_modules`), ...modulePaths], }), // Note: vanilla node REPL does not set exports, so this would be false exportsTest: true, // Note: vanilla node uses different name. See #1360 stackTest: expect.stringContaining( ` at ${join(TEST_DIR, '<repl>.ts')}:4:` ), moduleAccessorsTest: true, argv: [tsNodeExe], }, }); // Prior to these, nyc adds another entry on Windows; we need to ignore it expect(report.replReport.modulePaths.slice(-3)).toMatchObject([ join(homedir(), `.node_modules`), join(homedir(), `.node_libraries`), // additional entry goes to node's install path expect.any(String), ]); }); test('-e -i w/entrypoint ignores -e and -i, runs entrypoint', async (t) => { const { stdout } = await execTester({ stdin: `throw new Error()`, flags: '-e "throw new Error()" -i ./repl/script.js', }); const report = parseStdout(stdout); expect(report).toMatchObject({ stdinReport: false, evalReport: false, replReport: false, }); }); test('-e -i when -e throws error, -i does not run', async (t) => { const { stdout, stderr, err } = await execTester({ stdin: `console.log('hello')`, flags: `-e "throw new Error('error from -e')" -i`, expectError: true, }); expect(err).toBeDefined(); expect(stdout).toBe(''); expect(stderr).toContain('error from -e'); }); // Serial because it's timing-sensitive test.serial( 'programmatically, eval-ing before starting REPL', programmaticTest, { evalCodeBefore: `${setReportGlobal('repl')};${saveReportsAsGlobal}`, stdinCode: '', waitFor: () => !!globalInRepl.testReport, }, (stdout) => { expect(globalInRepl.testReport).toMatchObject({ stdinReport: false, evalReport: false, replReport: { __filename: false, __dirname: false, // Due to limitations in node's REPL API, we can't really expose // the `module` prior to calling repl.start() which also sends // output to stdout. // For now, leaving this as unsupported / undefined behavior. // moduleId: '<repl>', // modulePath: '.', // moduleFilename: null, // modulePaths: [ // join(ROOT_DIR, `repl/node_modules`), // ...rootModulePaths, // join(homedir(), `.node_modules`), // join(homedir(), `.node_libraries`), // // additional entry goes to node's install path // exp.any(String), // ], // // Note: vanilla node REPL does not set exports // exportsTest: true, // moduleAccessorsTest: true, // Note: vanilla node uses different name. See #1360 stackTest: expect.stringContaining( ` at ${join(ROOT_DIR, '<repl>.ts')}:1:` ), }, }); } ); test.serial( 'programmatically, passing code to stdin after starting REPL', programmaticTest, { evalCodeBefore: null, stdinCode: `${setReportGlobal('repl')};${saveReportsAsGlobal}`, waitFor: () => !!globalInRepl.testReport, }, (stdout) => { expect(globalInRepl.testReport).toMatchObject({ stdinReport: false, evalReport: false, replReport: { __filename: false, __dirname: false, moduleId: '<repl>', modulePath: '.', moduleFilename: null, modulePaths: expect.objectContaining({ ...[join(ROOT_DIR, `repl/node_modules`), ...rootModulePaths], }), // Note: vanilla node REPL does not set exports exportsTest: true, // Note: vanilla node uses different name. See #1360 stackTest: expect.stringContaining( ` at ${join(ROOT_DIR, '<repl>.ts')}:1:` ), moduleAccessorsTest: true, }, }); // Prior to these, nyc adds another entry on Windows; we need to ignore it expect( globalInRepl.testReport.replReport.modulePaths.slice(-3) ).toMatchObject([ join(homedir(), `.node_modules`), join(homedir(), `.node_libraries`), // additional entry goes to node's install path expect.any(String), ]); } ); } );
the_stack
import { smRatingModule } from './rating'; describe('Semantic-UI: Components - smRating', function() { 'use strict'; let $scope, $compile, element; beforeEach(angular.mock.module(smRatingModule.name)); beforeEach(inject(function($rootScope, $injector) { $scope = $rootScope.$new(); $compile = $injector.get('$compile'); $scope.rate = 3; element = $compile('<sm-rating ng-model="rate"></sm-rating>')($scope); $scope.$digest(); })); function getStars() { return element.find('i'); } function getStar(number) { return getStars().eq( number - 1 ); } function getState(className, classDefault) { let stars = getStars(); let state = []; for (let i = 0, n = stars.length; i < n; i++) { state.push(stars.eq(i).hasClass(className || classDefault)); } return state; } function getStateActive(classActive?) { return getState(classActive, 'active'); } function getStateHover(classHover?, classHoverParent?) { let classDefault = 'selected'; return getState(classHover, classDefault).concat([element.hasClass(classHoverParent || classDefault)]); } function triggerKeyDown(keyCode) { let e = $.Event('keydown'); e.which = keyCode; element.trigger(e); } it('contains the default number of icons', function() { expect(getStars().length).toBe(5); expect(element.attr('aria-valuemax')).toBe('5'); }); it('use star icons as default icons', function() { expect(element.hasClass('star')).toBe(true); }); it('initializes the default star icons as selected', function() { expect(getStateActive()).toEqual([true, true, true, false, false]); expect(element.attr('aria-valuenow')).toBe('3'); }); it('handles correctly the click event', function() { getStar(2).click(); $scope.$digest(); expect(getStateActive()).toEqual([true, true, false, false, false]); expect($scope.rate).toBe(2); expect(element.attr('aria-valuenow')).toBe('2'); getStar(5).click(); $scope.$digest(); expect(getStateActive()).toEqual([true, true, true, true, true]); expect($scope.rate).toBe(5); expect(element.attr('aria-valuenow')).toBe('5'); }); it('handles correctly the hover event', function() { getStar(2).trigger('mouseover'); $scope.$digest(); expect(getStateHover()).toEqual([true, true, false, false, false, true]); expect($scope.rate).toBe(3); getStar(5).trigger('mouseover'); $scope.$digest(); expect(getStateHover()).toEqual([true, true, true, true, true, true]); expect($scope.rate).toBe(3); element.trigger('mouseout'); expect(getStateHover()).toEqual([false, false, false, false, false, false]); expect($scope.rate).toBe(3); }); it('rounds off the number of stars shown with decimal values', function() { $scope.rate = 2.1; $scope.$digest(); expect(getStateActive()).toEqual([true, true, false, false, false]); expect(element.attr('aria-valuenow')).toBe('2'); $scope.rate = 2.5; $scope.$digest(); expect(getStateActive()).toEqual([true, true, true, false, false]); expect(element.attr('aria-valuenow')).toBe('3'); }); it('changes the number of selected icons when value changes', function() { $scope.rate = 2; $scope.$digest(); expect(getStateActive()).toEqual([true, true, false, false, false]); expect(element.attr('aria-valuenow')).toBe('2'); }); it('shows different number of icons when `max` attribute is set', function() { element = $compile('<sm-rating ng-model="rate" max="7"></sm-rating>')($scope); $scope.$digest(); expect(getStars().length).toBe(7); expect(element.attr('aria-valuemax')).toBe('7'); }); it('shows different number of icons when `max` attribute is from scope variable', function() { $scope.max = 15; element = $compile('<sm-rating ng-model="rate" max="max"></sm-rating>')($scope); $scope.$digest(); expect(getStars().length).toBe(15); expect(element.attr('aria-valuemax')).toBe('15'); }); it('handles readonly attribute', function() { $scope.isReadonly = true; element = $compile('<sm-rating ng-model="rate" readonly="isReadonly"></sm-rating>')($scope); $scope.$digest(); expect(getStateActive()).toEqual([true, true, true, false, false]); let star5 = getStar(5); star5.trigger('mouseover'); $scope.$digest(); expect(getStateActive()).toEqual([true, true, true, false, false]); expect(getStateHover()).toEqual([false, false, false, false, false, false]); $scope.isReadonly = false; $scope.$digest(); star5.trigger('mouseover'); $scope.$digest(); expect(getStateHover()).toEqual([true, true, true, true, true, true]); }); it('should fire onHover', function() { $scope.hoveringOver = jasmine.createSpy('hoveringOver'); element = $compile('<sm-rating ng-model="rate" on-hover="hoveringOver(value)"></sm-rating>')($scope); $scope.$digest(); getStar(3).trigger('mouseover'); $scope.$digest(); expect($scope.hoveringOver).toHaveBeenCalledWith(3); }); it('should fire onLeave', function() { $scope.leaving = jasmine.createSpy('leaving'); element = $compile('<sm-rating ng-model="rate" on-leave="leaving()"></sm-rating>')($scope); $scope.$digest(); element.trigger('mouseleave'); $scope.$digest(); expect($scope.leaving).toHaveBeenCalled(); }); describe('keyboard navigation', function() { it('supports arrow keys', function() { triggerKeyDown(38); expect($scope.rate).toBe(4); triggerKeyDown(37); expect($scope.rate).toBe(3); triggerKeyDown(40); expect($scope.rate).toBe(2); triggerKeyDown(39); expect($scope.rate).toBe(3); }); it('supports only arrow keys', function() { $scope.rate = undefined; $scope.$digest(); triggerKeyDown(36); expect($scope.rate).toBe(undefined); triggerKeyDown(41); expect($scope.rate).toBe(undefined); }); it('can get zero value but not negative', function() { $scope.rate = 1; $scope.$digest(); triggerKeyDown(37); expect($scope.rate).toBe(0); triggerKeyDown(37); expect($scope.rate).toBe(0); }); it('cannot get value above max', function() { $scope.rate = 4; $scope.$digest(); triggerKeyDown(38); expect($scope.rate).toBe(5); triggerKeyDown(38); expect($scope.rate).toBe(5); }); }); describe('custom states', function() { beforeEach(inject(function() { $scope.classActive = 'foo-active'; $scope.classHover = 'foo-hover'; $scope.classHoverParent = 'foo-hover-parent'; element = $compile(` <sm-rating ng-model="rate" state-active="classActive" state-hover="classHover" state-hover-parent="classHoverParent"> </sm-rating> `)($scope); $scope.$digest(); })); it('changes the default icons', function() { expect(getStateActive($scope.classActive)).toEqual([true, true, true, false, false]); getStar(3).trigger('mouseover'); expect(getStateHover($scope.classHover, $scope.classHoverParent)).toEqual([true, true, true, false, false, true]); }); }); describe('`rating-states`', function() { beforeEach(inject(function() { $scope.states = [ {stateActive: 'sign', stateHover: 'circle'}, {stateActive: 'heart', stateHover: 'ban'}, {stateActive: 'heart', stateHover: 'fly'}, {stateHover: 'float'} ]; element = $compile('<sm-rating ng-model="rate" rating-states="states"></sm-rating>')($scope); $scope.$digest(); })); it('should define number of icon elements', function () { expect(getStars().length).toBe(4); expect(element.attr('aria-valuemax')).toBe('4'); }); it('handles each icon', function() { let stars = getStars(); for (let i = 0; i < stars.length; i++) { let star = stars.eq(i); let state = $scope.states[i]; let isOn = i < $scope.rate; let isHover = i < 2; if (isHover) { star.trigger('mouseover'); } expect(star.hasClass(state.stateActive)).toBe(isOn); expect(star.hasClass(state.stateHover)).toBe(isHover); } }); }); describe('setting ratingConfig', function() { let originalConfig = {}; beforeEach(inject(function(ratingConfig) { $scope.rate = 5; angular.extend(originalConfig, ratingConfig); ratingConfig.max = 10; ratingConfig.stateActive = 'on'; ratingConfig.stateHover = 'float'; ratingConfig.stateHoverParent = 'float-parent'; ratingConfig.type = 'heart'; ratingConfig.size = 'massive'; element = $compile('<sm-rating ng-model="rate"></sm-rating>')($scope); $scope.$digest(); getStar(7).trigger('mouseover'); })); afterEach(inject(function(ratingConfig) { // return it to the original state angular.extend(ratingConfig, originalConfig); })); it('should change number of icon elements', function () { expect(getStars().length).toBe(10); }); it('should change icon states', function() { expect(getStateActive('on')).toEqual([true, true, true, true, true, false, false, false, false, false]); expect(getStateHover('float', 'float-parent')).toEqual([true, true, true, true, true, true, true, false, false, false, true]); }); it('should update rating type', function() { expect(element.hasClass('heart')).toBe(true); }); it('should update rating size', function() { expect(element.hasClass('massive')).toBe(true); }); }); it('shows star icon when attribute type is invalid', function() { element = $compile('<sm-rating ng-model="rate"></sm-rating>')($scope); $scope.$digest(); expect(element.hasClass('star')).toBe(true); }); it('shows icon type when attribute type is specified', function() { element = $compile('<sm-rating ng-model="rate" type="potato"></sm-rating>')($scope); $scope.$digest(); expect(element.hasClass('potato')).toBe(true); }); it('change size when attribute size is set', function() { element = $compile('<sm-rating ng-model="rate" size="massive"></sm-rating>')($scope); $scope.$digest(); expect(element.hasClass('massive')).toBe(true); }); it('should change size when attribute size is specified', function() { element = $compile('<sm-rating ng-model="rate" size="huge"></sm-rating>')($scope); $scope.$digest(); expect(element.hasClass('huge')).toBe(true); }); });
the_stack
import * as React from 'react'; import * as ReactDom from 'react-dom'; import { IPropertyPaneField, PropertyPaneFieldType, IPropertyPaneCustomFieldProps } from '@microsoft/sp-webpart-base'; import PropertyFieldRichTextBoxHost, { IPropertyFieldRichTextBoxHostProps } from './PropertyFieldRichTextBoxHost'; import { SPComponentLoader } from '@microsoft/sp-loader'; import { Async } from 'office-ui-fabric-react/lib/Utilities'; import { IWebPartContext} from '@microsoft/sp-webpart-base'; /** * @interface * Public properties of the PropertyFieldRichTextBox custom field * */ export interface IPropertyFieldRichTextBoxProps { /** * @var * Property field label displayed on top */ label: string; /** * @var * Initial value */ initialValue?: string; /** * @var * 'basic' or 'standard' or 'full'. Default is basic */ mode?: string; /** * @var * Popin toolbar or Classic toolbar */ inline?: boolean; /** * @var * Textarea min height */ minHeight?: number; /** * @function * Defines a onPropertyChange function to raise when the selected Color changed. * Normally this function must be always defined with the 'this.onPropertyChange' * method of the web part object. */ onPropertyChange(propertyPath: string, oldValue: any, newValue: any): void; /** * @function * This API is called to render the web part. * Normally this function must be always defined with the 'this.render.bind(this)' * method of the web part object. */ render(): void; /** * This property is used to indicate the web part's PropertyPane interaction mode: Reactive or NonReactive. * The default behaviour is Reactive. */ disableReactivePropertyChanges?: boolean; /** * @var * Parent Web Part properties */ properties: any; /** * @var * An UNIQUE key indicates the identity of this control */ key: string; /** * @var * The current web part context */ context: IWebPartContext; /** * Whether the property pane field is enabled or not. */ disabled?: boolean; /** * The method is used to get the validation error message and determine whether the input value is valid or not. * * When it returns string: * - If valid, it returns empty string. * - If invalid, it returns the error message string and the text field will * show a red border and show an error message below the text field. * * When it returns Promise<string>: * - The resolved value is display as error message. * - The rejected, the value is thrown away. * */ onGetErrorMessage?: (value: string) => string | Promise<string>; /** * Custom Field will start to validate after users stop typing for `deferredValidationTime` milliseconds. * Default value is 200. */ deferredValidationTime?: number; } /** * @interface * Private properties of the PropertyFieldRichTextBox custom field. * We separate public & private properties to include onRender & onDispose method waited * by the PropertyFieldCustom, witout asking to the developer to add it when he's using * the PropertyFieldRichTextBox. * */ export interface IPropertyFieldRichTextBoxPropsInternal extends IPropertyPaneCustomFieldProps { label: string; initialValue?: string; targetProperty: string; mode?: string; inline?: boolean; minHeight?: number; onRender(elem: HTMLElement): void; onDispose(elem: HTMLElement): void; onPropertyChange(propertyPath: string, oldValue: any, newValue: any): void; render(): void; disableReactivePropertyChanges?: boolean; properties: any; disabled?: boolean; context: IWebPartContext; onGetErrorMessage?: (value: string) => string | Promise<string>; deferredValidationTime?: number; } /** * @interface * Represents a PropertyFieldRichTextBox object * */ class PropertyFieldRichTextBoxBuilder implements IPropertyPaneField<IPropertyFieldRichTextBoxPropsInternal> { //Properties defined by IPropertyPaneField public type: PropertyPaneFieldType = PropertyPaneFieldType.Custom; public targetProperty: string; public properties: IPropertyFieldRichTextBoxPropsInternal; //Custom properties private label: string; private initialValue: string; private mode: string; private inline: boolean; private minHeight: number; private onPropertyChange: (propertyPath: string, oldValue: any, newValue: any) => void; private customProperties: any; private key: string; private keyCopy: string; private disabled: boolean = false; private context: IWebPartContext; private onGetErrorMessage: (value: string) => string | Promise<string>; private deferredValidationTime: number = 200; private renderWebPart: () => void; private disableReactivePropertyChanges: boolean = false; private latestValidateValue: string; private async: Async; private delayedValidate: (value: string) => void; //Static helper to manage load state private static CURRENT_WEBPART_INSTANCE: string = null; private static FIELD_KEY_INSTANCES = []; /** * @function * Ctor */ public constructor(_targetProperty: string, _properties: IPropertyFieldRichTextBoxPropsInternal) { this.render = this.render.bind(this); this.targetProperty = _properties.targetProperty; this.properties = _properties; this.label = _properties.label; this.mode = _properties.mode; this.inline = _properties.inline; this.initialValue = _properties.initialValue; this.properties.onDispose = this.dispose; this.properties.onRender = this.render; this.minHeight = this.minHeight; this.onPropertyChange = _properties.onPropertyChange; this.render = this.render.bind(this); this.customProperties = _properties.properties; this.key = _properties.key; this.keyCopy = _properties.key; this.context = _properties.context; if (_properties.disabled === true) this.disabled = _properties.disabled; this.onGetErrorMessage = _properties.onGetErrorMessage; if (_properties.deferredValidationTime !== undefined) this.deferredValidationTime = _properties.deferredValidationTime; this.renderWebPart = _properties.render; if (_properties.disableReactivePropertyChanges !== undefined && _properties.disableReactivePropertyChanges != null) this.disableReactivePropertyChanges = _properties.disableReactivePropertyChanges; this.async = new Async(this); this.validate = this.validate.bind(this); this.notifyAfterValidate = this.notifyAfterValidate.bind(this); this.delayedValidate = this.async.debounce(this.validate, this.deferredValidationTime); } /** * @function * Renders the ColorPicker field content */ private render(elem: HTMLElement): void { //Construct the JSX properties const element: React.ReactElement<IPropertyFieldRichTextBoxHostProps> = React.createElement(PropertyFieldRichTextBoxHost, { label: this.label, initialValue: this.initialValue, targetProperty: this.targetProperty, mode: this.mode, inline: this.inline, minHeight: this.minHeight, onDispose: this.dispose, onRender: this.render, onPropertyChange: this.onPropertyChange, properties: this.customProperties, key: this.keyCopy, keyCopy: this.keyCopy, context: this.context, disabled: this.disabled, onGetErrorMessage: this.onGetErrorMessage, deferredValidationTime: this.deferredValidationTime, render: this.renderWebPart, disableReactivePropertyChanges: this.disableReactivePropertyChanges }); //Calls the REACT content generator ReactDom.render(element, elem); var fMode = 'basic'; if (this.mode != null) fMode = this.mode; var ckEditorCdn = '//cdn.ckeditor.com/4.6.2/{0}/ckeditor.js'.replace("{0}", fMode); //Checks if the web part is loaded or reloaded to reload the CKEditor let shouldReloadCKEditor: boolean = false; if (PropertyFieldRichTextBoxBuilder.CURRENT_WEBPART_INSTANCE !== this.context.instanceId) { shouldReloadCKEditor = true; PropertyFieldRichTextBoxBuilder.FIELD_KEY_INSTANCES = []; PropertyFieldRichTextBoxBuilder.CURRENT_WEBPART_INSTANCE = this.context.instanceId; } if (!shouldReloadCKEditor) { //The web part has been already loaded, but check if the current field must recall CKEditor if (PropertyFieldRichTextBoxBuilder.FIELD_KEY_INSTANCES[this.key] == null) { shouldReloadCKEditor = true; } } PropertyFieldRichTextBoxBuilder.FIELD_KEY_INSTANCES[this.key] = true; SPComponentLoader.loadScript(ckEditorCdn, { globalExportsName: 'CKEDITOR' }).then((CKEDITOR: any): void => { if (shouldReloadCKEditor || CKEDITOR.instances[this.key + '-' + this.context.instanceId + '-editor'] == null) { if (this.inline == null || this.inline === false) { CKEDITOR.replace( this.key + '-' + this.context.instanceId + '-editor', { skin: 'moono-lisa,//cdn.ckeditor.com/4.6.2/full-all/skins/moono-lisa/' } ); } else { CKEDITOR.inline( this.key + '-' + this.context.instanceId + '-editor', { skin: 'moono-lisa,//cdn.ckeditor.com/4.6.2/full-all/skins/moono-lisa/' } ); } for (var i in CKEDITOR.instances) { CKEDITOR.instances[i].on('change', (elm?, val?) => { CKEDITOR.instances[i].updateElement(); var value = ((document.getElementById(this.key + '-' + this.context.instanceId + '-editor')) as any).value; this.delayedValidate(value); }); } } }); } /** * @function * Validates the new custom field value */ private validate(value: string): void { if (this.onGetErrorMessage === null || this.onGetErrorMessage === undefined) { this.notifyAfterValidate(this.initialValue, value); return; } if (this.latestValidateValue === value) return; this.latestValidateValue = value; var result: string | PromiseLike<string> = this.onGetErrorMessage(value || ''); if (result !== undefined) { if (typeof result === 'string') { if (result === undefined || result === '') this.notifyAfterValidate(this.initialValue, value); ((document.getElementById(this.key + '-' + this.context.instanceId + '-errorMssg1')) as any).innerHTML = result; ((document.getElementById(this.key + '-' + this.context.instanceId + '-errorMssg2')) as any).innerHTML = result; } else { result.then((errorMessage: string) => { if (errorMessage === undefined || errorMessage === '') this.notifyAfterValidate(this.initialValue, value); ((document.getElementById(this.key + '-' + this.context.instanceId + '-errorMssg1')) as any).innerHTML = errorMessage; ((document.getElementById(this.key + '-' + this.context.instanceId + '-errorMssg2')) as any).innerHTML = errorMessage; }); } } else { this.notifyAfterValidate(this.initialValue, value); } } /** * @function * Notifies the parent Web Part of a property value change */ private notifyAfterValidate(oldValue: string, newValue: string) { if (this.onPropertyChange && newValue != null) { this.customProperties[this.targetProperty] = newValue; this.onPropertyChange(this.targetProperty, this.properties.initialValue, newValue); if (!this.disableReactivePropertyChanges && this.renderWebPart != null) this.renderWebPart(); } } /** * @function * Disposes the current object */ private dispose(elem: HTMLElement): void { if (this.async != null && this.async != undefined) this.async.dispose(); } } /** * @function * Helper method to create the customer field on the PropertyPane. * @param targetProperty - Target property the custom field is associated to. * @param properties - Strongly typed custom field properties. */ export function PropertyFieldRichTextBox(targetProperty: string, properties: IPropertyFieldRichTextBoxProps): IPropertyPaneField<IPropertyFieldRichTextBoxPropsInternal> { //Create an internal properties object from the given properties var newProperties: IPropertyFieldRichTextBoxPropsInternal = { label: properties.label, targetProperty: targetProperty, initialValue: properties.initialValue, mode: properties.mode, inline: properties.inline, minHeight: properties.minHeight, onPropertyChange: properties.onPropertyChange, properties: properties.properties, onDispose: null, onRender: null, key: properties.key, context: properties.context, disabled: properties.disabled, onGetErrorMessage: properties.onGetErrorMessage, deferredValidationTime: properties.deferredValidationTime, render: properties.render, disableReactivePropertyChanges: properties.disableReactivePropertyChanges }; //Calls the PropertyFieldRichTextBox builder object //This object will simulate a PropertyFieldCustom to manage his rendering process return new PropertyFieldRichTextBoxBuilder(targetProperty, newProperties); }
the_stack
import {KEY} from '../../../mdc-dom/keyboard'; import {setUpFoundationTest, setUpMdcTestEnvironment} from '../../../../testing/helpers/setup'; import {MDCChipActionFocusBehavior, MDCChipActionInteractionTrigger, MDCChipActionType} from '../../action/constants'; import {MDCChipAnimation, MDCChipAttributes, MDCChipCssClasses, MDCChipEvents} from '../constants'; import {MDCChipFoundation} from '../foundation'; import {ActionInteractionEvent, ActionNavigationEvent} from '../types'; describe('MDCChipFoundation', () => { setUpMdcTestEnvironment(); const setupTest = () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCChipFoundation); return {foundation, mockAdapter}; }; it(`#getElementID() returns the adapter's return value`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.getElementID.and.returnValue('foo'); expect(foundation.getElementID()).toBe('foo'); }); it(`#getActions() returns the adapter's return value`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.getActions.and.returnValue([MDCChipActionType.UNSPECIFIED]); expect(foundation.getActions()).toEqual([MDCChipActionType.UNSPECIFIED]); }); it(`#isActionFocusable() returns the adapter's return value`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.isActionFocusable.and.returnValue(true); expect(foundation.isActionFocusable(MDCChipActionType.UNSPECIFIED)) .toBe(true); }); it(`#isActionSelectable() returns the adapter's return value`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.isActionSelectable.and.returnValue(true); expect(foundation.isActionSelectable(MDCChipActionType.UNSPECIFIED)) .toBe(true); }); it(`#isActionSelected() returns the adapter's return value`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.isActionSelected.and.returnValue(true); expect(foundation.isActionSelected(MDCChipActionType.UNSPECIFIED)) .toBe(true); }); it(`#setActionFocus(` + `${MDCChipActionType.UNSPECIFIED}, ${ MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED})` + ` updates the action focus`, () => { const {foundation, mockAdapter} = setupTest(); foundation.setActionFocus( MDCChipActionType.UNSPECIFIED, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); expect(mockAdapter.setActionFocus) .toHaveBeenCalledWith( MDCChipActionType.UNSPECIFIED, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); }); it(`#setActionSelected(${MDCChipActionType.UNSPECIFIED}, true) updates` + ` the action selection`, () => { const {foundation, mockAdapter} = setupTest(); foundation.setActionSelected(MDCChipActionType.UNSPECIFIED, true); expect(mockAdapter.setActionSelected) .toHaveBeenCalledWith(MDCChipActionType.UNSPECIFIED, true); }); it(`sequential calls to #setActionSelected() only modify the DOM once`, () => { const {foundation, mockAdapter} = setupTest(); foundation.setActionSelected(MDCChipActionType.UNSPECIFIED, true); foundation.setActionSelected(MDCChipActionType.UNSPECIFIED, false); foundation.setActionSelected(MDCChipActionType.UNSPECIFIED, true); jasmine.clock().tick(3); expect(mockAdapter.addClass) .toHaveBeenCalledWith(MDCChipCssClasses.SELECTING); expect(mockAdapter.addClass) .toHaveBeenCalledWith(MDCChipCssClasses.SELECTED); expect(mockAdapter.addClass).toHaveBeenCalledTimes(2); }); it('#destroy() cancels selection animation frames', () => { const {foundation, mockAdapter} = setupTest(); foundation.setActionSelected(MDCChipActionType.UNSPECIFIED, true); foundation.destroy(); jasmine.clock().tick(3); expect(mockAdapter.addClass) .not.toHaveBeenCalledWith(MDCChipCssClasses.SELECTING); expect(mockAdapter.addClass) .not.toHaveBeenCalledWith(MDCChipCssClasses.SELECTED); }); it(`#setActionSelected(${ MDCChipActionType.UNSPECIFIED}, true) adds the selected class`, () => { const {foundation, mockAdapter} = setupTest(); foundation.setActionSelected(MDCChipActionType.UNSPECIFIED, true); jasmine.clock().tick(3); expect(mockAdapter.addClass) .toHaveBeenCalledWith(MDCChipCssClasses.SELECTED); }); it(`#setActionSelected(${ MDCChipActionType.UNSPECIFIED}, false) removes the selected class`, () => { const {foundation, mockAdapter} = setupTest(); foundation.setActionSelected(MDCChipActionType.UNSPECIFIED, false); jasmine.clock().tick(3); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(MDCChipCssClasses.SELECTED); }); it(`#setActionSelected(${ MDCChipActionType.UNSPECIFIED}, true) removes all animating classes`, () => { const {foundation, mockAdapter} = setupTest(); foundation.setActionSelected(MDCChipActionType.UNSPECIFIED, true); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(MDCChipCssClasses.SELECTING); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(MDCChipCssClasses.DESELECTING); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(MDCChipCssClasses.SELECTING_WITH_PRIMARY_ICON); expect(mockAdapter.removeClass) .toHaveBeenCalledWith( MDCChipCssClasses.DESELECTING_WITH_PRIMARY_ICON); }); it(`#setActionSelected(${ MDCChipActionType .UNSPECIFIED}, true) adds the selecting class when no primary icon is present`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.hasClass.withArgs(MDCChipCssClasses.WITH_PRIMARY_ICON) .and.returnValue(false); foundation.setActionSelected(MDCChipActionType.UNSPECIFIED, true); jasmine.clock().tick(2); expect(mockAdapter.addClass) .toHaveBeenCalledWith(MDCChipCssClasses.SELECTING); }); it(`#setActionSelected(${ MDCChipActionType .UNSPECIFIED}, true) adds the selecting with icon class when the primary icon is present`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.hasClass.withArgs(MDCChipCssClasses.WITH_PRIMARY_ICON) .and.returnValue(true); foundation.setActionSelected(MDCChipActionType.UNSPECIFIED, true); jasmine.clock().tick(2); expect(mockAdapter.addClass) .toHaveBeenCalledWith(MDCChipCssClasses.SELECTING_WITH_PRIMARY_ICON); }); it(`#setActionSelected(${ MDCChipActionType .UNSPECIFIED}, false) adds the deselecting class when no primary icon is present`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.hasClass.withArgs(MDCChipCssClasses.WITH_PRIMARY_ICON) .and.returnValue(false); foundation.setActionSelected(MDCChipActionType.UNSPECIFIED, false); jasmine.clock().tick(2); expect(mockAdapter.addClass) .toHaveBeenCalledWith(MDCChipCssClasses.DESELECTING); }); it(`#setActionSelected(${ MDCChipActionType .UNSPECIFIED}, false) adds the deelecting with icon class when the primary icon is present`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.hasClass.withArgs(MDCChipCssClasses.WITH_PRIMARY_ICON) .and.returnValue(true); foundation.setActionSelected(MDCChipActionType.UNSPECIFIED, false); jasmine.clock().tick(2); expect(mockAdapter.addClass) .toHaveBeenCalledWith( MDCChipCssClasses.DESELECTING_WITH_PRIMARY_ICON); }); it('#setDisabled(true) makes each action disabled', () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.getActions.and.returnValue([MDCChipActionType.UNSPECIFIED]); foundation.setDisabled(true); expect(mockAdapter.setActionDisabled) .toHaveBeenCalledWith(MDCChipActionType.UNSPECIFIED, true); }); it('#setDisabled(true) adds the disabled class', () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.getActions.and.returnValue([MDCChipActionType.UNSPECIFIED]); foundation.setDisabled(true); expect(mockAdapter.addClass) .toHaveBeenCalledWith(MDCChipCssClasses.DISABLED); }); it('#setDisabled(false) makes each action enabled', () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.getActions.and.returnValue([MDCChipActionType.UNSPECIFIED]); foundation.setDisabled(false); expect(mockAdapter.setActionDisabled) .toHaveBeenCalledWith(MDCChipActionType.UNSPECIFIED, false); }); it('#setDisabled(false) removes the disabled class', () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.getActions.and.returnValue([MDCChipActionType.UNSPECIFIED]); foundation.setDisabled(false); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(MDCChipCssClasses.DISABLED); }); it(`#handleActionInteraction() emits ${MDCChipEvents.INTERACTION}`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.getElementID.and.returnValue('foo'); mockAdapter.isActionSelected.withArgs(MDCChipActionType.UNSPECIFIED) .and.returnValue(true); mockAdapter.isActionSelectable.withArgs(MDCChipActionType.UNSPECIFIED) .and.returnValue(true); foundation.handleActionInteraction({ detail: { actionID: 'bar', source: MDCChipActionType.UNSPECIFIED, trigger: MDCChipActionInteractionTrigger.CLICK, }, } as ActionInteractionEvent); expect(mockAdapter.emitEvent) .toHaveBeenCalledWith(MDCChipEvents.INTERACTION, { actionID: 'bar', chipID: 'foo', shouldRemove: false, isSelectable: true, isSelected: true, source: MDCChipActionType.UNSPECIFIED, }); }); it(`#handleActionInteraction() emits ${MDCChipEvents.INTERACTION} with` + ` {shouldRemove: true} when from action "${ MDCChipActionType.TRAILING}"`, () => { const {foundation, mockAdapter} = setupTest(); foundation.handleActionInteraction({ detail: { actionID: 'bar', source: MDCChipActionType.TRAILING, trigger: MDCChipActionInteractionTrigger.CLICK, }, } as ActionInteractionEvent); expect(mockAdapter.emitEvent) .toHaveBeenCalledWith(MDCChipEvents.INTERACTION, { actionID: 'bar', chipID: '', shouldRemove: true, isSelectable: false, isSelected: false, source: MDCChipActionType.TRAILING, }); }); it(`#handleActionInteraction() emits ${MDCChipEvents.INTERACTION} with` + ` {shouldRemove: true} when from` + ` trigger "${MDCChipActionInteractionTrigger.BACKSPACE_KEY}"`, () => { const {foundation, mockAdapter} = setupTest(); foundation.handleActionInteraction({ detail: { actionID: 'bar', source: MDCChipActionType.UNSPECIFIED, trigger: MDCChipActionInteractionTrigger.BACKSPACE_KEY, }, } as ActionInteractionEvent); expect(mockAdapter.emitEvent) .toHaveBeenCalledWith(MDCChipEvents.INTERACTION, { actionID: 'bar', chipID: '', shouldRemove: true, isSelectable: false, isSelected: false, source: MDCChipActionType.UNSPECIFIED, }); }); describe('#handleActionNavigation', () => { describe('ArrowRight', () => { // Use the same key for all tests const key = KEY.ARROW_RIGHT; it(`from primary action focuses trailing action if focusable`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.isActionFocusable.withArgs(MDCChipActionType.TRAILING) .and.returnValue(true); foundation.handleActionNavigation({ detail: { source: MDCChipActionType.PRIMARY, key, }, } as ActionNavigationEvent); expect(mockAdapter.setActionFocus) .toHaveBeenCalledWith( MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); expect(mockAdapter.setActionFocus) .toHaveBeenCalledWith( MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); }); it(`from primary action emits ${MDCChipEvents.NAVIGATION}` + ` if trailing action is not focusable`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.getElementID.and.returnValue('foo'); mockAdapter.isActionFocusable.withArgs(MDCChipActionType.TRAILING) .and.returnValue(false); foundation.handleActionNavigation({ detail: { source: MDCChipActionType.PRIMARY, key, }, } as ActionNavigationEvent); expect(mockAdapter.emitEvent) .toHaveBeenCalledWith(MDCChipEvents.NAVIGATION, { chipID: 'foo', source: MDCChipActionType.PRIMARY, isRTL: false, key, }); }); it(`from primary action in RTL emits ${MDCChipEvents.NAVIGATION}`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.isRTL.and.returnValue(true); mockAdapter.getElementID.and.returnValue('foo'); foundation.handleActionNavigation({ detail: { source: MDCChipActionType.PRIMARY, key, }, } as ActionNavigationEvent); expect(mockAdapter.emitEvent) .toHaveBeenCalledWith(MDCChipEvents.NAVIGATION, { chipID: 'foo', source: MDCChipActionType.PRIMARY, isRTL: true, key, }); }); }); describe('ArrowLeft', () => { // Use the same key for all tests const key = KEY.ARROW_LEFT; it(`from trailing action focuses primary action if focusable`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.isActionFocusable.withArgs(MDCChipActionType.PRIMARY) .and.returnValue(true); foundation.handleActionNavigation({ detail: { source: MDCChipActionType.TRAILING, key, }, } as ActionNavigationEvent); expect(mockAdapter.setActionFocus) .toHaveBeenCalledWith( MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); expect(mockAdapter.setActionFocus) .toHaveBeenCalledWith( MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); }); it(`from trailing action emits ${MDCChipEvents.NAVIGATION}` + ` if primary action is not focusable`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.getElementID.and.returnValue('foo'); mockAdapter.isActionFocusable.withArgs(MDCChipActionType.PRIMARY) .and.returnValue(false); foundation.handleActionNavigation({ detail: { source: MDCChipActionType.TRAILING, key, }, } as ActionNavigationEvent); expect(mockAdapter.emitEvent) .toHaveBeenCalledWith(MDCChipEvents.NAVIGATION, { chipID: 'foo', source: MDCChipActionType.TRAILING, isRTL: false, key, }); }); it(`from trailing action in RTL emits ${MDCChipEvents.NAVIGATION}`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.isRTL.and.returnValue(true); mockAdapter.getElementID.and.returnValue('foo'); foundation.handleActionNavigation({ detail: { source: MDCChipActionType.TRAILING, key, }, } as ActionNavigationEvent); expect(mockAdapter.emitEvent) .toHaveBeenCalledWith(MDCChipEvents.NAVIGATION, { chipID: 'foo', source: MDCChipActionType.TRAILING, isRTL: true, key, }); }); }); const emittingKeys = [ KEY.ARROW_UP, KEY.ARROW_DOWN, KEY.HOME, KEY.END, ]; for (const key of emittingKeys) { it(`${key} emits ${MDCChipEvents.NAVIGATION}`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.getElementID.and.returnValue('foo'); foundation.handleActionNavigation({ detail: { source: MDCChipActionType.UNSPECIFIED, key, }, } as ActionNavigationEvent); expect(mockAdapter.emitEvent) .toHaveBeenCalledWith(MDCChipEvents.NAVIGATION, { chipID: 'foo', source: MDCChipActionType.UNSPECIFIED, isRTL: false, key, }); }); } }); it(`#startAnimation(${MDCChipAnimation.ENTER}) adds the enter class`, () => { const {foundation, mockAdapter} = setupTest(); foundation.startAnimation(MDCChipAnimation.ENTER); expect(mockAdapter.addClass).toHaveBeenCalledWith(MDCChipCssClasses.ENTER); }); it(`#startAnimation(${MDCChipAnimation.EXIT}) adds the exit class`, () => { const {foundation, mockAdapter} = setupTest(); foundation.startAnimation(MDCChipAnimation.EXIT); expect(mockAdapter.addClass).toHaveBeenCalledWith(MDCChipCssClasses.EXIT); }); it(`#handleAnimationEnd() for enter removes the enter class`, () => { const {foundation, mockAdapter} = setupTest(); foundation.handleAnimationEnd( {animationName: 'mdc-evolution-chip-enter'} as AnimationEvent); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(MDCChipCssClasses.ENTER); }); it(`#handleAnimationEnd() for enter emits an event`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.getElementID.and.returnValue('foo'); mockAdapter.getAttribute.withArgs(MDCChipAttributes.DATA_ADDED_ANNOUNCEMENT) .and.returnValue('Added foo'); foundation.handleAnimationEnd( {animationName: 'mdc-evolution-chip-enter'} as AnimationEvent); expect(mockAdapter.emitEvent) .toHaveBeenCalledWith(MDCChipEvents.ANIMATION, { chipID: 'foo', addedAnnouncement: 'Added foo', animation: MDCChipAnimation.ENTER, isComplete: true, }); }); it(`#handleAnimationEnd() for exit removes the exit class`, () => { const {foundation, mockAdapter} = setupTest(); foundation.handleAnimationEnd( {animationName: 'mdc-evolution-chip-exit'} as AnimationEvent); expect(mockAdapter.removeClass) .toHaveBeenCalledWith(MDCChipCssClasses.EXIT); }); it(`#handleAnimationEnd() for exit adds the hidden class`, () => { const {foundation, mockAdapter} = setupTest(); foundation.handleAnimationEnd( {animationName: 'mdc-evolution-chip-exit'} as AnimationEvent); expect(mockAdapter.addClass).toHaveBeenCalledWith(MDCChipCssClasses.HIDDEN); }); it(`#handleAnimationEnd() sets the computed width on the root`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.getOffsetWidth.and.returnValue(123); foundation.handleAnimationEnd( {animationName: 'mdc-evolution-chip-exit'} as AnimationEvent); expect(mockAdapter.setStyleProperty).toHaveBeenCalledWith('width', '123px'); }); it(`#handleAnimationEnd() sets the width on the root to 0`, () => { const {foundation, mockAdapter} = setupTest(); foundation.handleAnimationEnd( {animationName: 'mdc-evolution-chip-exit'} as AnimationEvent); jasmine.clock().tick(2); expect(mockAdapter.setStyleProperty).toHaveBeenCalledWith('width', '0'); }); it(`#handleTransitionEnd() emits an event when the root has the hidden class`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.getElementID.and.returnValue('foo'); mockAdapter.getAttribute .withArgs(MDCChipAttributes.DATA_REMOVED_ANNOUNCEMENT) .and.returnValue('Removed foo'); mockAdapter.hasClass.withArgs(MDCChipCssClasses.HIDDEN) .and.returnValue(true); foundation.handleTransitionEnd(); expect(mockAdapter.emitEvent) .toHaveBeenCalledWith(MDCChipEvents.ANIMATION, { chipID: 'foo', removedAnnouncement: 'Removed foo', animation: MDCChipAnimation.EXIT, isComplete: true, }); }); it(`#handleTransitionEnd() does not emit an event when the root does not have the hidden class`, () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.hasClass.withArgs(MDCChipCssClasses.HIDDEN) .and.returnValue(false); foundation.handleTransitionEnd(); expect(mockAdapter.emitEvent).not.toHaveBeenCalled(); }); });
the_stack
import { Component, Directive, NgZone, OnInit, ViewChild, ElementRef } from '@angular/core'; import { TestBed, ComponentFixture, fakeAsync, tick, waitForAsync } from '@angular/core/testing'; import { IgxScrollInertiaModule, IgxScrollInertiaDirective } from './scroll_inertia.directive'; import { configureTestSuite } from '../../test-utils/configure-suite'; import { wait } from '../../test-utils/ui-interactions.spec'; describe('Scroll Inertia Directive - Rendering', () => { let fix: ComponentFixture<ScrollInertiaComponent>; configureTestSuite(); beforeAll(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ IgxTestScrollInertiaDirective, ScrollInertiaComponent ], imports: [IgxScrollInertiaModule] }).compileComponents().then(() => { fix = TestBed.createComponent(ScrollInertiaComponent); fix.detectChanges(); }); })); it('should initialize directive on non-scrollable container.', () => { expect(fix.componentInstance.scrInertiaDir).toBeDefined('scroll inertia initializing through markup failed'); }); // Unit tests for inertia function. it('inertia should accelerate and then deccelerate vertically.', async () => { pending('This should be tested in the e2e test'); const scrInertiaDir = fix.componentInstance.scrInertiaDir; // vertical inertia scrInertiaDir._inertiaInit(0, 1); await wait(1500); const scrTopStepArray = fix.componentInstance.scrTopStepArray; expect(scrTopStepArray.length).toEqual(57); const first = scrTopStepArray[0]; const mid = scrTopStepArray[9]; const end = scrTopStepArray[56]; expect(first).toBeLessThan(mid); expect(end).toBeLessThan(mid); }); it('inertia should accelerate and then deccelerate horizontally.', async () => { pending('This should be tested in the e2e test'); const scrInertiaDir = fix.componentInstance.scrInertiaDir; // horizontal inertia scrInertiaDir._inertiaInit(1, 0); await wait(1500); const scrLeftStepArray = fix.componentInstance.scrLeftStepArray; expect(scrLeftStepArray.length).toEqual(57); const first = scrLeftStepArray[0]; const mid = scrLeftStepArray[9]; const end = scrLeftStepArray[56]; expect(first).toBeLessThan(mid); expect(end).toBeLessThan(mid); }); }); describe('Scroll Inertia Directive - Scrolling', () => { let scrollInertiaDir: IgxTestScrollInertiaDirective; let scrollContainerMock; beforeEach(() => { const mockZone = jasmine.createSpyObj('NgZone', ['runOutsideAngular']); scrollContainerMock = { scrollLeft: 0, scrollTop: 0, offsetHeight: 500, children: [{ style: { width: '50px', height: '500px', scrollHeight: 100 } }] }; scrollInertiaDir = new IgxTestScrollInertiaDirective(null, mockZone); scrollInertiaDir.IgxScrollInertiaScrollContainer = scrollContainerMock; scrollInertiaDir.smoothingDuration = 0; }); // Unit test for wheel - wheelDelataY/wheelDeltaX supported on Chrome, Safari, Opera. it('should change scroll top for related scrollbar if onWheel is executed with wheelDeltaY.', () => { scrollInertiaDir.IgxScrollInertiaDirection = 'vertical'; const evt = {wheelDeltaY: -240, preventDefault: () => {}}; scrollInertiaDir.onWheel(evt); expect(scrollContainerMock.scrollTop).toEqual(2 * scrollInertiaDir.wheelStep); }); it('should change scroll left for related scrollbar if onWheel is executed with wheelDeltaX.', () => { scrollInertiaDir.IgxScrollInertiaDirection = 'horizontal'; const evt = {wheelDeltaX: -240, preventDefault: () => {}}; scrollInertiaDir.onWheel(evt); expect(scrollContainerMock.scrollLeft).toEqual(2 * scrollInertiaDir.wheelStep); }); // Unit tests for wheel on other browsers that don't provide wheelDelta - use deltaX and deltaY. it('should change scroll top for related scrollbar if onWheel is executed with deltaY.', () => { scrollInertiaDir.IgxScrollInertiaDirection = 'vertical'; const evt = {deltaY: 1, preventDefault: () => {}}; scrollInertiaDir.onWheel(evt); expect(scrollContainerMock.scrollTop).toEqual(scrollInertiaDir.wheelStep); }); it('should change scroll left for related scrollbar if onWheel is executed with deltaX.', () => { scrollInertiaDir.IgxScrollInertiaDirection = 'horizontal'; const evt = {deltaX: 1, preventDefault: () => {}}; scrollInertiaDir.onWheel(evt); expect(scrollContainerMock.scrollLeft).toEqual(scrollInertiaDir.wheelStep); }); it('should not throw error if there is no associated scrollbar and wheel event is called.', () => { scrollInertiaDir.IgxScrollInertiaScrollContainer = null; const evt = {preventDefault: () => {}}; expect (() => scrollInertiaDir.onWheel(evt)).not.toThrow(); }); it('should change scroll left when shift + wheel is triggered' , () => { scrollInertiaDir.IgxScrollInertiaDirection = 'horizontal'; const evt = {shiftKey: true, wheelDeltaY: -240, preventDefault: () => {}}; scrollInertiaDir.onWheel(evt); expect(scrollContainerMock.scrollTop).toEqual(0); expect(scrollContainerMock.scrollLeft).toEqual(2 * scrollInertiaDir.wheelStep); }); it('should be able to scroll to left/right when shift + wheel is triggered' , () => { scrollInertiaDir.IgxScrollInertiaDirection = 'horizontal'; let evt = {shiftKey: true, wheelDeltaY: -240, preventDefault: () => {}}; scrollInertiaDir.onWheel(evt); expect(scrollContainerMock.scrollTop).toEqual(0); expect(scrollContainerMock.scrollLeft).toEqual(2 * scrollInertiaDir.wheelStep); evt = {shiftKey: true, wheelDeltaY: 120, preventDefault: () => {}}; scrollInertiaDir.onWheel(evt); expect(scrollContainerMock.scrollTop).toEqual(0); expect(scrollContainerMock.scrollLeft).toEqual(scrollInertiaDir.wheelStep); }); it('should change scroll left when shift + wheel is called with with deltaY' , () => { scrollInertiaDir.IgxScrollInertiaDirection = 'horizontal'; const evt = {shiftKey: true, deltaY: 1, preventDefault: () => {}}; scrollInertiaDir.onWheel(evt); expect(scrollContainerMock.scrollTop).toEqual(0); expect(scrollContainerMock.scrollLeft).toEqual(scrollInertiaDir.wheelStep); }); it('should be able to scroll to left/right when shift + wheel is called with with deltaY' , () => { scrollInertiaDir.IgxScrollInertiaDirection = 'horizontal'; let evt = {shiftKey: true, deltaY: 1, preventDefault: () => {}}; scrollInertiaDir.onWheel(evt); expect(scrollContainerMock.scrollTop).toEqual(0); expect(scrollContainerMock.scrollLeft).toEqual(scrollInertiaDir.wheelStep); evt = {shiftKey: true, deltaY: -1, preventDefault: () => {}}; scrollInertiaDir.onWheel(evt); expect(scrollContainerMock.scrollTop).toEqual(0); expect(scrollContainerMock.scrollLeft).toEqual(0); }); // Unit tests for touch events with inertia - Chrome, FireFox, Safari. it('should change scroll top for related scrollbar on touch start/move/end', fakeAsync(() => { let evt = { touches: [{ pageX: 0, pageY: 0 }], preventDefault: () => {} }; scrollInertiaDir.onTouchStart(evt); evt = { touches: [{ pageX: 0, pageY: -100 }], preventDefault: () => {} }; tick(10); scrollInertiaDir.onTouchMove(evt); scrollInertiaDir.onTouchEnd(evt); // wait for inertia to complete tick(300); expect(scrollContainerMock.scrollTop).toBeGreaterThan(3000); })); it('should stop inertia if another touch event is initiated while inertia is executing.', fakeAsync(() => { let evt = { touches: [{ pageX: 0, pageY: 0 }], preventDefault: () => {} }; scrollInertiaDir.onTouchStart(evt); evt = { touches: [{ pageX: 0, pageY: -100 }], preventDefault: () => {} }; tick(10); scrollInertiaDir.onTouchMove(evt); scrollInertiaDir.onTouchEnd(evt); tick(10); // don't wait for inertia to end. Instead start another touch interaction. evt = { touches: [{ pageX: 0, pageY: 0 }], preventDefault: () => {} }; scrollInertiaDir.onTouchStart(evt); expect(scrollContainerMock.scrollTop).toBeLessThan(1000); })); it('should honor the defined swipeToleranceX.', fakeAsync(() => { // if scroll is initiated on Y and on X within the defined tolerance no scrolling should occur on X. let evt = { touches: [{ pageX: 0, pageY: 0 }], preventDefault: () => {} }; scrollInertiaDir.onTouchStart(evt); evt = { touches: [{ pageX: -10, pageY: -50 }], preventDefault: () => {} }; tick(10); scrollInertiaDir.onTouchMove(evt); scrollInertiaDir.onTouchEnd(evt); tick(300); expect(scrollContainerMock.scrollLeft).toEqual(0); expect(scrollContainerMock.scrollTop).toBeGreaterThan(100); })); it('should change scroll left for related scrollbar on touch start/move/end', fakeAsync(() => { let evt = { touches: [{ pageX: 0, pageY: 0 }], preventDefault: () => {} }; scrollInertiaDir.onTouchStart(evt); evt = { touches: [{ pageX: -100, pageY: 0 }], preventDefault: () => {} }; tick(10); scrollInertiaDir.onTouchMove(evt); scrollInertiaDir.onTouchEnd(evt); // wait for inertia to complete tick(300); expect(scrollContainerMock.scrollLeft).toBeGreaterThan(3000); })); it('should not throw errors on touch start/move/end if no scrollbar is associated.', () => { scrollInertiaDir.IgxScrollInertiaScrollContainer = null; const evt = {preventDefault: () => {}}; expect (() => scrollInertiaDir.onTouchStart(evt)).not.toThrow(); expect (() => scrollInertiaDir.onTouchMove(evt)).not.toThrow(); expect (() => scrollInertiaDir.onTouchEnd(evt)).not.toThrow(); }); // Unit tests for touch events on IE/Edge it('should change scroll top related scrollbar via gesture events. ', () => { let evt = { screenX: 0, screenY: 0 }; scrollInertiaDir.onMSGestureStart(evt); evt = { screenX: 0, screenY: -100 }; scrollInertiaDir.onMSGestureChange(evt); expect(scrollContainerMock.scrollTop).toEqual(100); }); it('should change scroll left related scrollbar via gesture events. ', () => { let evt = { screenX: 0, screenY: 0 }; scrollInertiaDir.onMSGestureStart(evt); evt = { screenX: -100, screenY: 0 }; scrollInertiaDir.onMSGestureChange(evt); expect(scrollContainerMock.scrollLeft).toEqual(80); }); // Unit tests for Pointer Down/Pointer Up - IE/Edge specific it('should prepare MSGesture on PointerDown to handle touch interactions on IE/Edge and should release them on PointerUp.', () => { const targetElem = { setPointerCapture: (_args) => {}, releasePointerCapture: (_args) => {} }; const pointerId = 100; spyOn(targetElem, 'setPointerCapture'); spyOn(targetElem, 'releasePointerCapture'); const msGesture = window['MSGesture']; if (!msGesture) { // if MSGesture does not exist create a dummy obj to use instead. window['MSGesture'] = (() => ({ addPointer: () => {} })) as any; } const evt = { pointerType: 2, target: targetElem, pointerId }; scrollInertiaDir.onPointerDown(evt); expect(targetElem.setPointerCapture).toHaveBeenCalledWith(pointerId); scrollInertiaDir.onPointerUp(evt); expect(targetElem.releasePointerCapture).toHaveBeenCalledWith(pointerId); // restore original MSGesture state window['MSGesture'] = msGesture; }); it('should not throw error when calling pointerDown/pointerUp if there is no associated scrollbar.', () => { scrollInertiaDir.IgxScrollInertiaScrollContainer = null; const evt = { pointerType: 2, target: {}, pointerId: 0 }; expect (() => scrollInertiaDir.onPointerDown(evt)).not.toThrow(); expect (() => scrollInertiaDir.onPointerUp(evt)).not.toThrow(); }); }); /** igxScroll inertia for testing */ @Directive({ selector: '[igxTestScrollInertia]' }) export class IgxTestScrollInertiaDirective extends IgxScrollInertiaDirective { constructor(element: ElementRef, _zone: NgZone) { super(element, _zone, { isIE: false } as any); } public onWheel(evt) { super.onWheel(evt); } public onTouchStart(evt) { return super.onTouchStart(evt); } public onTouchEnd(evt) { super.onTouchEnd(evt); } public onTouchMove(evt) { return super.onTouchMove(evt); } // IE/Edge specific events public onPointerDown(evt) { return super.onPointerDown(evt); } public onPointerUp(evt) { return super.onPointerUp(evt); } public onMSGestureStart(evt) { return super.onMSGestureStart(evt); } public onMSGestureChange(evt) { return super.onMSGestureChange(evt); } public _inertiaInit(speedX, speedY) { super._inertiaInit(speedX, speedY); } } /** igxScroll inertia component */ @Component({ template: ` <div #container style='width:calc(100% - 50px); height: 500px; float: left;'> <ng-template igxTestScrollInertia #scrInertiaContainer></ng-template> </div> <div #scrBar [style.height]='height' style='overflow: auto; width: 50px; float:right;'> <div [style.height]='innerHeight' [style.width]='innerWidth'></div> </div> ` }) export class ScrollInertiaComponent implements OnInit { @ViewChild('container', { static: true }) public container: ElementRef; @ViewChild('scrBar', { static: true }) public scrollContainer: ElementRef; @ViewChild('scrInertiaContainer', { read: IgxTestScrollInertiaDirective, static: true }) public scrInertiaDir: IgxTestScrollInertiaDirective; public height = '500px'; public innerHeight = '5000px'; public innerWidth = '5000px'; public scrTopArray = []; public scrTopStepArray = []; public scrLeftArray = []; public scrLeftStepArray = []; public ngOnInit() { this.scrInertiaDir.IgxScrollInertiaScrollContainer = this.scrollContainer.nativeElement; this.scrollContainer.nativeElement.addEventListener('scroll', (evt) => { this.onScroll(evt); }); } public onScroll(evt) { const ind = this.scrTopArray.length - 1; const prevScrTop = ind < 0 ? 0 : this.scrTopArray[ind]; const prevScrLeft = ind < 0 ? 0 : this.scrLeftArray[ind]; this.scrTopArray.push(evt.target.scrollTop); this.scrLeftArray.push(evt.target.scrollLeft); const calcScrollStep = evt.target.scrollTop - prevScrTop; const calcScrollLeftStep = evt.target.scrollLeft - prevScrLeft; this.scrTopStepArray.push(calcScrollStep); this.scrLeftStepArray.push(calcScrollLeftStep); } }
the_stack
import { WebGLUniformItem } from "../../interface/backend/webgl/webglContext"; import { WebGLTensor } from "../../interface/backend/webgl/webglTensor"; import { Tensor } from "../../interface/core/tensor"; // Float encode: https://community.khronos.org/t/packing-multiple-floats-into-a-single-float-value/59320/3 export const shaderFloatPack = ` vec4 encode_float (float val) { if (val == 0.0) return vec4(0, 0, 0, 0); float sign = val > 0.0 ? 192.0 : 64.0; float absval = abs(val); float exponent = ceil(log2(absval) + 0.0001); float scaled = absval * exp2(-exponent); vec3 enc = vec3(1.0, 255.0, 65025.0) * scaled; enc = fract(enc); enc -= enc.yzz * vec3(1.0/255.0, 1.0/255.0, 0.0); return vec4((sign + clamp(exponent, -63.0, 63.0)) * (1.0 / 255.0), enc.x, enc.y, enc.z); } float decode_float(vec4 code) { if (code.x == 0.0) { return 0.0; } float ebyte = code.x * 255.0; float sign, exponent; if (ebyte >= 128.0) { sign = 1.0; exponent = ebyte - 192.0; } else { sign = -1.0; exponent = ebyte - 64.0; } float scaled = code.w * (1.0 / 65025.0) + code.z * (1.0 / 255.0) + code.y; float value = scaled * exp2(exponent) * sign; return value; } `; export const shaderHeaderWebGL1 = `#version 100 precision highp float; precision highp int; precision highp sampler2D; `; export const shaderHeaderWebGL2 = `#version 300 es precision highp float; precision highp int; precision highp sampler2D; out vec4 fragColor; `; export function shaderGenHeader(webgl2: boolean): string { if (webgl2) { return shaderHeaderWebGL2; } return shaderHeaderWebGL1 + shaderFloatPack; } export function shaderGenOutput(expr: string, webgl2: boolean): string { if (webgl2) { return `fragColor = vec4((${expr}), 0.0, 0.0, 0.0);`; } return `gl_FragColor = encode_float(${expr});`; } export function shaderGenOutputVec4(expr: string, webgl2: boolean): string { if (webgl2) { return `fragColor = (${expr});`; } throw new Error("shaderGenOutputVec4 is only for WebGL2"); } export function shaderGenTensorNDGet( name: string, ndim: number, webgl2: boolean ): string { let args: string, flat_index: string, uniforms: string; switch (ndim) { case 0: uniforms = ""; args = ""; flat_index = "0"; break; case 1: uniforms = ` uniform int ${name}_stride_0; `; args = "int d0"; flat_index = `d0 * ${name}_stride_0`; break; case 2: uniforms = ` uniform int ${name}_stride_0; uniform int ${name}_stride_1; `; args = "int d0, int d1"; flat_index = `d0 * ${name}_stride_0 + d1 * ${name}_stride_1`; break; case 3: uniforms = ` uniform int ${name}_stride_0; uniform int ${name}_stride_1; uniform int ${name}_stride_2; `; args = "int d0, int d1, int d2"; flat_index = `d0 * ${name}_stride_0 + d1 * ${name}_stride_1 + d2 * ${name}_stride_2`; break; case 4: uniforms = ` uniform int ${name}_stride_0; uniform int ${name}_stride_1; uniform int ${name}_stride_2; uniform int ${name}_stride_3; `; args = "int d0, int d1, int d2, int d3"; flat_index = `d0 * ${name}_stride_0 + d1 * ${name}_stride_1 + d2 * ${name}_stride_2 + d3 * ${name}_stride_3`; break; case 5: uniforms = ` uniform int ${name}_stride_0; uniform int ${name}_stride_1; uniform int ${name}_stride_2; uniform int ${name}_stride_3; uniform int ${name}_stride_4; `; args = "int d0, int d1, int d2, int d3, int d4"; flat_index = `d0 * ${name}_stride_0 + d1 * ${name}_stride_1 + d2 * ${name}_stride_2 + d3 * ${name}_stride_3 + d4 * ${name}_stride_4`; break; case 6: uniforms = ` uniform int ${name}_stride_0; uniform int ${name}_stride_1; uniform int ${name}_stride_2; uniform int ${name}_stride_3; uniform int ${name}_stride_4; uniform int ${name}_stride_5; `; args = "int d0, int d1, int d2, int d3, int d4, int d5"; flat_index = `d0 * ${name}_stride_0 + d1 * ${name}_stride_1 + d2 * ${name}_stride_2 + d3 * ${name}_stride_3 + d4 * ${name}_stride_4 + d5 * ${name}_stride_5`; break; default: throw new Error(); } if (webgl2) { return ` uniform sampler2D ${name}; ${uniforms} float get_${name}(${args}) { int flat_index = ${flat_index}; int texture_w = textureSize(${name}, 0).x; int y = flat_index / texture_w; int x = flat_index - y * texture_w; return texelFetch(${name}, ivec2(x, y), 0).r; } `; } return ` uniform sampler2D ${name}; ${uniforms} uniform int ${name}_texture_w; uniform int ${name}_texture_h; float get_${name}(${args}) { int flat_index = ${flat_index}; int texture_w = ${name}_texture_w; int y = flat_index / texture_w; int x = flat_index - y * texture_w; vec4 p = texture2D(${name}, vec2((float(x) + 0.5) / float(${name}_texture_w), (float(y) + 0.5) / float(${name}_texture_h))); return decode_float(p); } `; } export function shaderGenTensorNDGetVec4( name: string, ndim: number, webgl2: boolean ): string { let args: string, flat_index: string, uniforms: string; switch (ndim) { case 0: uniforms = ""; args = ""; flat_index = "0"; break; case 1: uniforms = ` uniform int ${name}_stride_0; `; args = "int d0"; flat_index = `d0 * ${name}_stride_0`; break; case 2: uniforms = ` uniform int ${name}_stride_0; uniform int ${name}_stride_1; `; args = "int d0, int d1"; flat_index = `d0 * ${name}_stride_0 + d1 * ${name}_stride_1`; break; case 3: uniforms = ` uniform int ${name}_stride_0; uniform int ${name}_stride_1; uniform int ${name}_stride_2; `; args = "int d0, int d1, int d2"; flat_index = `d0 * ${name}_stride_0 + d1 * ${name}_stride_1 + d2 * ${name}_stride_2`; break; case 4: uniforms = ` uniform int ${name}_stride_0; uniform int ${name}_stride_1; uniform int ${name}_stride_2; uniform int ${name}_stride_3; `; args = "int d0, int d1, int d2, int d3"; flat_index = `d0 * ${name}_stride_0 + d1 * ${name}_stride_1 + d2 * ${name}_stride_2 + d3 * ${name}_stride_3`; break; case 5: uniforms = ` uniform int ${name}_stride_0; uniform int ${name}_stride_1; uniform int ${name}_stride_2; uniform int ${name}_stride_3; uniform int ${name}_stride_4; `; args = "int d0, int d1, int d2, int d3, int d4"; flat_index = `d0 * ${name}_stride_0 + d1 * ${name}_stride_1 + d2 * ${name}_stride_2 + d3 * ${name}_stride_3 + d4 * ${name}_stride_4`; break; case 6: uniforms = ` uniform int ${name}_stride_0; uniform int ${name}_stride_1; uniform int ${name}_stride_2; uniform int ${name}_stride_3; uniform int ${name}_stride_4; uniform int ${name}_stride_5; `; args = "int d0, int d1, int d2, int d3, int d4, int d5"; flat_index = `d0 * ${name}_stride_0 + d1 * ${name}_stride_1 + d2 * ${name}_stride_2 + d3 * ${name}_stride_3 + d4 * ${name}_stride_4 + d5 * ${name}_stride_5`; break; default: throw new Error(); } if (webgl2) { return ` uniform sampler2D ${name}; ${uniforms} vec4 get_vec4_${name}(${args}) { int flat_index = ${flat_index}; int texture_w = textureSize(${name}, 0).x; int y = flat_index / texture_w; int x = flat_index - y * texture_w; return texelFetch(${name}, ivec2(x, y), 0); } `; } throw new Error("shaderGenTensorNDGetVec4 is only for WebGL2"); } function isWebGLTensor(tensor: unknown): tensor is WebGLTensor { return typeof tensor === "object" && (tensor as Tensor).backend === "webgl"; } export function shaderGenTensorNDGetUniformItem( name: string, strides: ReadonlyArray<number>, textureShape: ReadonlyArray<number> | WebGLTensor, webgl2: boolean ): WebGLUniformItem[] { let textureShapeArray: ReadonlyArray<number>; if (isWebGLTensor(textureShape)) { textureShapeArray = [textureShape.textureHeight, textureShape.textureWidth]; } else { textureShapeArray = textureShape; } const uniforms: WebGLUniformItem[] = []; for (let i = 0; i < strides.length; i++) { uniforms.push({ name: `${name}_stride_${i}`, type: "int", value: strides[i], }); } if (!webgl2) { uniforms.push({ name: `${name}_texture_h`, type: "int", value: textureShapeArray[0], }); uniforms.push({ name: `${name}_texture_w`, type: "int", value: textureShapeArray[1], }); } return uniforms; } export function shaderGenTensorOutputUniformItem( shape: ReadonlyArray<number>, textureShape: ReadonlyArray<number> | WebGLTensor, // eslint-disable-next-line @typescript-eslint/no-unused-vars webgl2: boolean ): WebGLUniformItem[] { let textureShapeArray: ReadonlyArray<number>; if (isWebGLTensor(textureShape)) { textureShapeArray = [textureShape.textureHeight, textureShape.textureWidth]; } else { textureShapeArray = textureShape; } const name = "tex_output", uniforms: WebGLUniformItem[] = []; for (let i = 0; i < shape.length; i++) { uniforms.push({ name: `${name}_shape_${i}`, type: "int", value: shape[i], }); } uniforms.push({ name: `${name}_texture_w`, type: "int", value: textureShapeArray[1], }); return uniforms; } export function shaderGenTensorOutputUniform(ndim: number): string { let source = ` uniform int tex_output_texture_w; `; for (let i = 0; i < ndim; i++) { source += `uniform int tex_output_shape_${i};`; } return source; } export function shaderGenTensorOutputCoordsWithReturn(ndim: number): string { let source: string; switch (ndim) { case 0: source = ` int tex_output_0 = 0; if (tex_output_0 >= 1) { return; } `; break; case 1: source = ` int tex_output_0 = tex_output_flat; if (tex_output_0 >= tex_output_shape_0) { return; } `; break; case 2: source = ` int tmp1 = tex_output_flat / tex_output_shape_1; int tex_output_1 = tex_output_flat - tmp1 * tex_output_shape_1; int tex_output_0 = tmp1; if (tex_output_0 >= tex_output_shape_0) { return; } `; break; case 3: source = ` int tmp2 = tex_output_flat / tex_output_shape_2; int tex_output_2 = tex_output_flat - tmp2 * tex_output_shape_2; int tmp1 = tmp2 / tex_output_shape_1; int tex_output_1 = tmp2 - tmp1 * tex_output_shape_1; int tex_output_0 = tmp1; if (tex_output_0 >= tex_output_shape_0) { return; } `; break; case 4: source = ` int tmp3 = tex_output_flat / tex_output_shape_3; int tex_output_3 = tex_output_flat - tmp3 * tex_output_shape_3; int tmp2 = tmp3 / tex_output_shape_2; int tex_output_2 = tmp3 - tmp2 * tex_output_shape_2; int tmp1 = tmp2 / tex_output_shape_1; int tex_output_1 = tmp2 - tmp1 * tex_output_shape_1; int tex_output_0 = tmp1; if (tex_output_0 >= tex_output_shape_0) { return; } `; break; case 5: source = ` int tmp4 = tex_output_flat / tex_output_shape_4; int tex_output_4 = tex_output_flat - tmp4 * tex_output_shape_4; int tmp3 = tmp4 / tex_output_shape_3; int tex_output_3 = tmp4 - tmp3 * tex_output_shape_3; int tmp2 = tmp3 / tex_output_shape_2; int tex_output_2 = tmp3 - tmp2 * tex_output_shape_2; int tmp1 = tmp2 / tex_output_shape_1; int tex_output_1 = tmp2 - tmp1 * tex_output_shape_1; int tex_output_0 = tmp1; if (tex_output_0 >= tex_output_shape_0) { return; } `; break; case 6: source = ` int tmp5 = tex_output_flat / tex_output_shape_5; int tex_output_5 = tex_output_flat - tmp5 * tex_output_shape_5; int tmp4 = tmp5 / tex_output_shape_4; int tex_output_4 = tmp5 - tmp4 * tex_output_shape_4; int tmp3 = tmp4 / tex_output_shape_3; int tex_output_3 = tmp4 - tmp3 * tex_output_shape_3; int tmp2 = tmp3 / tex_output_shape_2; int tex_output_2 = tmp3 - tmp2 * tex_output_shape_2; int tmp1 = tmp2 / tex_output_shape_1; int tex_output_1 = tmp2 - tmp1 * tex_output_shape_1; int tex_output_0 = tmp1; if (tex_output_0 >= tex_output_shape_0) { return; } `; break; default: throw new Error(); } /* * Gl_FragCoord.x 's precision is mediump, which only has 10bit precision * force casting to highp is needed in iOS. Also, "-0.5" cannot be removed. */ return ` highp float helper_gfcx = gl_FragCoord.x; highp float helper_gfcy = gl_FragCoord.y; int tex_output_flat = int(helper_gfcx - 0.5) + tex_output_texture_w * int(helper_gfcy - 0.5); ${source} `; } export function shaderGenTensorElementwiseGet( name: string, webgl2: boolean ): string { if (webgl2) { return ` uniform sampler2D ${name}; float get_${name}() { return texelFetch(${name}, ivec2(int(gl_FragCoord.x), int(gl_FragCoord.y)), 0).r; } `; } return ` uniform sampler2D ${name}; uniform int ${name}_texture_w; uniform int ${name}_texture_h; float get_${name}() { vec4 p = texture2D(${name}, vec2(gl_FragCoord.x / float(${name}_texture_w), gl_FragCoord.y / float(${name}_texture_h))); return decode_float(p); } `; } export function shaderGenTensorElementwiseGetUniformItem( name: string, textureShape: ReadonlyArray<number> | WebGLTensor, webgl2: boolean ): WebGLUniformItem[] { let textureShapeArray: ReadonlyArray<number>; if (isWebGLTensor(textureShape)) { textureShapeArray = [textureShape.textureHeight, textureShape.textureWidth]; } else { textureShapeArray = textureShape; } const uniforms: WebGLUniformItem[] = []; if (!webgl2) { uniforms.push({ name: `${name}_texture_h`, type: "int", value: textureShapeArray[0], }); uniforms.push({ name: `${name}_texture_w`, type: "int", value: textureShapeArray[1], }); } return uniforms; }
the_stack
import { ProtectAccessory, ProtectReservedNames } from "./protect-accessory"; import { ProtectCameraConfig, ProtectNvrConfig } from "unifi-protect"; import { CharacteristicValue } from "homebridge"; export class ProtectSecuritySystem extends ProtectAccessory { private isAlarmTriggered!: boolean; // Configure a security system accessory for HomeKit. protected configureDevice(): Promise<boolean> { const accessory = this.accessory; let securityState: CharacteristicValue = this.hap.Characteristic.SecuritySystemCurrentState.STAY_ARM; // Save the security system state before we wipeout the context. if(accessory.context.securityState !== undefined) { securityState = accessory.context.securityState as CharacteristicValue; } // Clean out the context object in case it's been polluted somehow. accessory.context = {}; accessory.context.nvr = this.nvr.nvrApi.bootstrap?.nvr.mac; accessory.context.securityState = securityState; // Configure accessory information. this.configureInfo(); // Configure MQTT services. this.configureMqtt(); // Configure the security system service. this.configureSecuritySystem(); // Configure the security alarm. this.configureSecurityAlarm(); return Promise.resolve(true); } // Configure the security system device information for HomeKit. protected configureInfo(): boolean { const accessory = this.accessory; const hap = this.hap; let nvrInfo!: ProtectNvrConfig; if(this.nvr && this.nvr.nvrApi && this.nvr.nvrApi.bootstrap && this.nvr.nvrApi.bootstrap.nvr) { nvrInfo = this.nvr.nvrApi.bootstrap.nvr; } // Update the manufacturer information for this security system. accessory .getService(hap.Service.AccessoryInformation) ?.updateCharacteristic(hap.Characteristic.Manufacturer, "github.com/hjdhjd"); // Update the model information for this security system. accessory .getService(hap.Service.AccessoryInformation) ?.updateCharacteristic(hap.Characteristic.Model, "UniFi Protect Liveview Security System"); if(nvrInfo) { // Update the serial number for this security system - we base this off of the NVR. accessory .getService(hap.Service.AccessoryInformation) ?.updateCharacteristic(hap.Characteristic.SerialNumber, nvrInfo.mac + ".Security"); // Update the hardware revision for this security system - we base this off of the NVR. accessory .getService(hap.Service.AccessoryInformation) ?.updateCharacteristic(hap.Characteristic.HardwareRevision, nvrInfo.hardwareRevision); } return true; } // Configure MQTT capabilities for the security system. private configureMqtt(): boolean { // Get the current status of the security system. this.nvr.mqtt?.subscribe(this.accessory, "securitysystem/get", (message: Buffer) => { const value = message.toString().toLowerCase(); // When we get the right message, we return the state of the security system. if(value !== "true") { return; } // Publish the current status of the security system. this.publishSecurityState(); this.log.info("%s: Security system status published via MQTT.", this.name()); }); // Set the security system state. this.nvr.mqtt?.subscribe(this.accessory, "securitysystem/set", (message: Buffer) => { const SecuritySystemCurrentState = this.hap.Characteristic.SecuritySystemCurrentState; const SecuritySystemTargetState = this.hap.Characteristic.SecuritySystemTargetState; const value = message.toString().toLowerCase(); let alarmState!: boolean; let targetState: CharacteristicValue; // Map the request to our security states. switch(value) { case "home": targetState = SecuritySystemTargetState.STAY_ARM; break; case "away": targetState = SecuritySystemTargetState.AWAY_ARM; break; case "night": targetState = SecuritySystemTargetState.NIGHT_ARM; break; case "alarmoff": targetState = SecuritySystemCurrentState.ALARM_TRIGGERED; alarmState = false; break; case "alarmon": targetState = SecuritySystemCurrentState.ALARM_TRIGGERED; alarmState = true; break; case "off": targetState = SecuritySystemTargetState.DISARM; break; default: // The user sent a bad value. Ignore it and we're done. this.log.error("%s: Unable to process MQTT security system setting: %s.", this.name(), message.toString()); return; } // The security alarm gets handled differently than the other state settings. if(targetState === SecuritySystemCurrentState.ALARM_TRIGGERED) { this.setSecurityAlarm(alarmState); this.log.info("%s: Security alarm %s via MQTT.", this.name(), alarmState ? "triggered" : "reset"); return; } // Set the security state, and we're done. this.accessory.getService(this.hap.Service.SecuritySystem)?.updateCharacteristic(SecuritySystemTargetState, targetState); this.setSecurityState(targetState); this.log.info("%s: Security system state set via MQTT: %s.", this.name(), value.charAt(0).toUpperCase() + value.slice(1)); }); return true; } // Configure the security system for HomeKit. private configureSecuritySystem(): boolean { const accessory = this.accessory; const hap = this.hap; // Find any existing security system service. let securityService = accessory.getService(hap.Service.SecuritySystem); // Add the security system service, if needed. if(!securityService) { securityService = new hap.Service.SecuritySystem(accessory.displayName); if(!securityService) { this.log.error("%s: Unable to add security system.", this.name()); return false; } accessory.addService(securityService); } const SecuritySystemCurrentState = this.hap.Characteristic.SecuritySystemCurrentState; const SecuritySystemTargetState = this.hap.Characteristic.SecuritySystemTargetState; let targetSecurityState: CharacteristicValue; switch(accessory.context.securityState) { case SecuritySystemCurrentState.STAY_ARM: targetSecurityState = SecuritySystemTargetState.STAY_ARM; break; case SecuritySystemCurrentState.AWAY_ARM: targetSecurityState = SecuritySystemTargetState.AWAY_ARM; break; case SecuritySystemCurrentState.NIGHT_ARM: targetSecurityState = SecuritySystemTargetState.NIGHT_ARM; break; case SecuritySystemCurrentState.DISARMED: default: targetSecurityState = SecuritySystemTargetState.DISARM; break; } // Handlers to get our current state, and initialize on startup. securityService .updateCharacteristic(SecuritySystemCurrentState, accessory.context.securityState as CharacteristicValue) .getCharacteristic(SecuritySystemCurrentState) ?.onGet(this.getSecurityState.bind(this)); // Handlers for triggering a change in the security system state. accessory.getService(hap.Service.SecuritySystem) ?.getCharacteristic(SecuritySystemTargetState) .onSet(this.setSecurityState.bind(this)); // Set the initial state after we have setup our handlers above. This way, when we startup, we // automatically restore the scene we've been set to, if any. accessory.getService(hap.Service.SecuritySystem) ?.updateCharacteristic(SecuritySystemTargetState, targetSecurityState); return true; } // Configure the security alarm for HomeKit. private configureSecurityAlarm(): boolean { this.isAlarmTriggered = false; // Find the existing security alarm switch service. let switchService = this.accessory.getService(this.hap.Service.Switch); // Have we enabled the security system alarm? if(!this.nvr?.optionEnabled(null, "SecuritySystem.Alarm", false)) { if(switchService) { this.accessory.removeService(switchService); } return false; } // Add the security alarm switch to the security system. if(!switchService) { switchService = new this.hap.Service.Switch(this.accessory.displayName + " Security Alarm"); if(!switchService) { this.log.error("%s: Unable to add security system alarm.", this.name()); return false; } this.accessory.addService(switchService); } // Notify the user that we're enabled. this.log.info("%s: Enabling the security alarm switch on the security system accessory.", this.name()); // Activate or deactivate the security alarm. switchService .getCharacteristic(this.hap.Characteristic.On) ?.onGet(() => { return this.isAlarmTriggered === true; }) .onSet((value: CharacteristicValue) => { this.setSecurityAlarm(value === true); this.log.info("%s: Security system alarm %s.", this.name(), (value === true) ? "triggered" : "reset"); }); // Initialize the value. switchService.updateCharacteristic(this.hap.Characteristic.On, this.isAlarmTriggered); return true; } // Publish the security system state to MQTT. private publishSecurityState(): void { const SecuritySystemCurrentState = this.hap.Characteristic.SecuritySystemCurrentState; let state; switch(this.accessory.context.securityState) { case SecuritySystemCurrentState.STAY_ARM: state = "Home"; break; case SecuritySystemCurrentState.AWAY_ARM: state = "Away"; break; case SecuritySystemCurrentState.NIGHT_ARM: state = "Night"; break; case SecuritySystemCurrentState.ALARM_TRIGGERED: state = "Alarm"; break; case SecuritySystemCurrentState.DISARMED: default: state = "Off"; break; } this.nvr.mqtt?.publish(this.accessory, "securitysystem", this.isAlarmTriggered ? "Alarm" : state); } // Get the current security system state. private getSecurityState(): CharacteristicValue { return this.isAlarmTriggered ? this.hap.Characteristic.SecuritySystemCurrentState.ALARM_TRIGGERED : this.accessory.context.securityState as CharacteristicValue; } // Change the security system state, and enable or disable motion detection accordingly. private setSecurityState(value: CharacteristicValue): void { const accessory = this.accessory; const hap = this.hap; const liveviews = this.nvr.nvrApi.bootstrap?.liveviews; let newState: CharacteristicValue; const nvrApi = this.nvr.nvrApi; const SecuritySystemCurrentState = hap.Characteristic.SecuritySystemCurrentState; const SecuritySystemTargetState = hap.Characteristic.SecuritySystemTargetState; let viewScene = ""; // If we don't have any liveviews or the bootstrap configuration, there's nothing for us to do. if(!liveviews || !nvrApi.bootstrap) { return; } // We have three different states which can be triggered (aside from disarming). // Those states are home, away, and night. We use this as a convenient way to easily enable or disable motion detection // on a Protect controller and effectively give us scene-type functionality in a nice way. switch(value) { case SecuritySystemTargetState.STAY_ARM: newState = SecuritySystemCurrentState.STAY_ARM; viewScene = "Protect-Home"; break; case SecuritySystemTargetState.AWAY_ARM: newState = SecuritySystemCurrentState.AWAY_ARM; viewScene = "Protect-Away"; break; case SecuritySystemTargetState.NIGHT_ARM: newState = SecuritySystemCurrentState.NIGHT_ARM; viewScene = "Protect-Night"; break; case SecuritySystemTargetState.DISARM: newState = SecuritySystemCurrentState.DISARMED; viewScene = "Protect-Off"; break; default: newState = SecuritySystemCurrentState.DISARMED; break; } // Get the complete list of cameras in the liveview we're interested in. // This cryptic line grabs the list of liveviews that have the name we're interested in // (turns out, you can define multiple liveviews in Protect with the same name...who knew!), // and then create a single list containing all of the cameras found. const targetCameraIds = liveviews.filter(view => view.name === viewScene) .map(view => view.slots.map(slots => slots.cameras)) .flat(2); // We don't have a liveview for this state and we aren't disarming - update state for the user and we're done. if(newState !== SecuritySystemCurrentState.DISARMED && !targetCameraIds.length) { this.log.info("%s: No liveview configured for this security system state. Create a liveview named %s in the Protect webUI to use this feature.", this.name(), viewScene); accessory.context.securityState = newState; accessory.getService(hap.Service.SecuritySystem)?.updateCharacteristic(SecuritySystemCurrentState, newState); return; } this.log.info("%s: Setting the liveview scene: %s.", this.name(), viewScene); // Iterate through the list of accessories and set the Protect scene. for(const targetAccessory of this.platform.accessories) { // We only want accessories associated with this Protect controller. if(!targetAccessory.context?.device || targetAccessory.context.nvr !== nvrApi.bootstrap.nvr.mac) { continue; } let targetState = false; // If we're disarming, then all Protect cameras will disable motion detection in HomeKit. Otherwise, // check to see if this is one of the cameras we want to turn on motion detection for. if(((newState !== SecuritySystemCurrentState.DISARMED) || ((newState === SecuritySystemCurrentState.DISARMED) && targetCameraIds.length)) && targetCameraIds.some(thisCameraId => thisCameraId === (targetAccessory.context.device as ProtectCameraConfig).id)) { targetState = true; } // Only take action to change motion detection state if needed. if(targetAccessory.context.detectMotion !== targetState) { targetAccessory.context.detectMotion = targetState; // Update the switch service, if present. const motionSwitch = targetAccessory.getServiceById(hap.Service.Switch, ProtectReservedNames.SWITCH_MOTION_SENSOR); if(motionSwitch) { motionSwitch.updateCharacteristic(hap.Characteristic.On, targetAccessory.context.detectMotion as boolean); } this.log.info("%s: %s -> %s: Motion detection %s.", this.name(), viewScene, targetAccessory.displayName, targetAccessory.context.detectMotion === true ? "enabled" : "disabled"); } } // Inform the user of our new state. accessory.context.securityState = newState; accessory.getService(hap.Service.SecuritySystem)?.updateCharacteristic(SecuritySystemCurrentState, newState); // Reset our alarm state and update our alarm switch. this.isAlarmTriggered = false; if(accessory.getService(hap.Service.Switch)?.getCharacteristic(hap.Characteristic.On).value !== this.isAlarmTriggered) { accessory.getService(hap.Service.Switch)?.updateCharacteristic(hap.Characteristic.On, this.isAlarmTriggered); } // Publish to MQTT, if configured. this.publishSecurityState(); } // Set the security alarm. private setSecurityAlarm(value: boolean): void { // Nothing to do. if(this.isAlarmTriggered === value) { return; } // Update the alarm state. this.isAlarmTriggered = value === true; // Update the security system state. this.accessory.getService(this.hap.Service.SecuritySystem)?.updateCharacteristic(this.hap.Characteristic.SecuritySystemCurrentState, this.isAlarmTriggered ? this.hap.Characteristic.SecuritySystemCurrentState.ALARM_TRIGGERED : this.accessory.context.securityState as CharacteristicValue); // Update the security alarm state. this.accessory.getService(this.hap.Service.Switch)?.updateCharacteristic(this.hap.Characteristic.On, this.isAlarmTriggered); // Publish to MQTT, if configured. this.publishSecurityState(); } }
the_stack
import Immutable from 'immutable'; import React from 'react'; import {plugins} from '..'; import setPrettyPrint from './setPrettyPrint'; const {Immutable: ImmutablePlugin, ReactElement} = plugins; setPrettyPrint([ReactElement, ImmutablePlugin]); it('does not incorrectly match identity-obj-proxy as Immutable object', () => { // SENTINEL constant is from https://github.com/facebook/immutable-js const IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; const val: any = {}; val[IS_ITERABLE_SENTINEL] = IS_ITERABLE_SENTINEL; // mock the mock object :) const expected = `{"${IS_ITERABLE_SENTINEL}": "${IS_ITERABLE_SENTINEL}"}`; expect(val).toPrettyPrintTo(expected, {min: true}); }); describe('Immutable.OrderedSet', () => { it('supports an empty collection {min: true}', () => { expect(Immutable.OrderedSet([])).toPrettyPrintTo( 'Immutable.OrderedSet []', {min: true}, ); }); it('supports an empty collection {min: false}', () => { expect(Immutable.OrderedSet([])).toPrettyPrintTo( 'Immutable.OrderedSet []', {min: false}, ); }); it('supports a single string element', () => { expect(Immutable.OrderedSet(['foo'])).toPrettyPrintTo( 'Immutable.OrderedSet ["foo"]', {min: true}, ); }); it('supports a single integer element', () => { expect(Immutable.OrderedSet([1])).toPrettyPrintTo( 'Immutable.OrderedSet [1]', {min: true}, ); }); it('supports multiple string elements {min: true}', () => { expect(Immutable.OrderedSet(['jhon', 'mike', 'cristian'])).toPrettyPrintTo( 'Immutable.OrderedSet ["jhon", "mike", "cristian"]', { min: true, }, ); }); it('supports multiple string elements {min: false}', () => { expect(Immutable.OrderedSet(['jhon', 'mike', 'cristian'])).toPrettyPrintTo( 'Immutable.OrderedSet [\n "jhon",\n "mike",\n "cristian",\n]', {min: false}, ); }); it('supports multiple integer elements {min: true}', () => { expect(Immutable.OrderedSet([1, 2, 3])).toPrettyPrintTo( 'Immutable.OrderedSet [1, 2, 3]', {min: true}, ); }); it('supports multiple integer elements {min: false}', () => { expect(Immutable.OrderedSet([1, 2, 3])).toPrettyPrintTo( 'Immutable.OrderedSet [\n 1,\n 2,\n 3,\n]', { min: false, }, ); }); it('supports object elements {min: true}', () => { expect(Immutable.OrderedSet([{a: 1, b: 2, c: 3}])).toPrettyPrintTo( 'Immutable.OrderedSet [{"a": 1, "b": 2, "c": 3}]', { min: true, }, ); }); it('supports object elements {min: false}', () => { expect(Immutable.OrderedSet([{a: 1, b: 2, c: 3}])).toPrettyPrintTo( 'Immutable.OrderedSet [\n Object {\n "a": 1,\n "b": 2,\n "c": 3,\n },\n]', {min: false}, ); }); it('supports React elements {min: true}', () => { const reactElement = React.createElement('Mouse', null, 'Hello World'); expect(Immutable.OrderedSet([reactElement, reactElement])).toPrettyPrintTo( 'Immutable.OrderedSet [<Mouse>Hello World</Mouse>]', { min: true, }, ); }); it('supports React elements {min: false}', () => { const reactElement = React.createElement('Mouse', null, 'Hello World'); expect(Immutable.OrderedSet([reactElement, reactElement])).toPrettyPrintTo( 'Immutable.OrderedSet [\n <Mouse>\n Hello World\n </Mouse>,\n]', {min: false}, ); }); }); describe('Immutable.List', () => { it('supports an empty collection {min: true}', () => { expect(Immutable.List([])).toPrettyPrintTo('Immutable.List []', { min: true, }); }); it('supports an empty collection {min: false}', () => { expect(Immutable.List([])).toPrettyPrintTo('Immutable.List []', { min: false, }); }); it('supports a single string element', () => { expect(Immutable.List(['foo'])).toPrettyPrintTo('Immutable.List ["foo"]', { min: true, }); }); it('supports a single integer element', () => { expect(Immutable.List([1])).toPrettyPrintTo('Immutable.List [1]', { min: true, }); }); it('supports multiple string elements {min: true}', () => { expect(Immutable.List(['jhon', 'mike', 'cristian'])).toPrettyPrintTo( 'Immutable.List ["jhon", "mike", "cristian"]', { min: true, }, ); }); it('supports multiple string elements {min: false}', () => { expect(Immutable.List(['jhon', 'mike', 'cristian'])).toPrettyPrintTo( 'Immutable.List [\n "jhon",\n "mike",\n "cristian",\n]', ); }); it('supports multiple integer elements {min: true}', () => { expect(Immutable.List([1, 2, 3])).toPrettyPrintTo( 'Immutable.List [1, 2, 3]', {min: true}, ); }); it('supports multiple integer elements {min: false}', () => { expect(Immutable.List([1, 2, 3])).toPrettyPrintTo( 'Immutable.List [\n 1,\n 2,\n 3,\n]', ); }); it('supports object elements {min: true}', () => { expect(Immutable.List([{a: 1, b: 2, c: 3}])).toPrettyPrintTo( 'Immutable.List [{"a": 1, "b": 2, "c": 3}]', {min: true}, ); }); it('supports object elements {min: false}', () => { expect(Immutable.List([{a: 1, b: 2, c: 3}])).toPrettyPrintTo( 'Immutable.List [\n Object {\n "a": 1,\n "b": 2,\n "c": 3,\n },\n]', ); }); it('supports React elements {min: true}', () => { const reactElement = React.createElement('Mouse', null, 'Hello World'); expect(Immutable.List([reactElement, reactElement])).toPrettyPrintTo( 'Immutable.List [<Mouse>Hello World</Mouse>, <Mouse>Hello World</Mouse>]', {min: true}, ); }); it('supports React elements {min: false}', () => { const reactElement = React.createElement('Mouse', null, 'Hello World'); expect(Immutable.List([reactElement, reactElement])).toPrettyPrintTo( 'Immutable.List [\n <Mouse>\n Hello World\n </Mouse>,\n <Mouse>\n Hello World\n </Mouse>,\n]', ); }); }); describe('Immutable.Stack', () => { it('supports an empty collection {min: true}', () => { expect(Immutable.Stack([])).toPrettyPrintTo('Immutable.Stack []', { min: true, }); }); it('supports an empty collection {min: false}', () => { expect(Immutable.Stack([])).toPrettyPrintTo('Immutable.Stack []', { min: false, }); }); it('supports a single string element', () => { expect(Immutable.Stack(['foo'])).toPrettyPrintTo( 'Immutable.Stack ["foo"]', {min: true}, ); }); it('supports a single integer element', () => { expect(Immutable.Stack([1])).toPrettyPrintTo('Immutable.Stack [1]', { min: true, }); }); it('supports multiple string elements {min: true}', () => { expect(Immutable.Stack(['jhon', 'mike', 'cristian'])).toPrettyPrintTo( 'Immutable.Stack ["jhon", "mike", "cristian"]', { min: true, }, ); }); it('supports multiple string elements {min: false}', () => { expect(Immutable.Stack(['jhon', 'mike', 'cristian'])).toPrettyPrintTo( 'Immutable.Stack [\n "jhon",\n "mike",\n "cristian",\n]', ); }); it('supports multiple integer elements {min: true}', () => { expect(Immutable.Stack([1, 2, 3])).toPrettyPrintTo( 'Immutable.Stack [1, 2, 3]', {min: true}, ); }); it('supports multiple integer elements {min: false}', () => { expect(Immutable.Stack([1, 2, 3])).toPrettyPrintTo( 'Immutable.Stack [\n 1,\n 2,\n 3,\n]', ); }); it('supports object elements {min: true}', () => { expect(Immutable.Stack([{a: 1, b: 2, c: 3}])).toPrettyPrintTo( 'Immutable.Stack [{"a": 1, "b": 2, "c": 3}]', { min: true, }, ); }); it('supports object elements {min: false}', () => { expect(Immutable.Stack([{a: 1, b: 2, c: 3}])).toPrettyPrintTo( 'Immutable.Stack [\n Object {\n "a": 1,\n "b": 2,\n "c": 3,\n },\n]', ); }); it('supports React elements {min: true}', () => { const reactElement = React.createElement('Mouse', null, 'Hello World'); expect(Immutable.Stack([reactElement, reactElement])).toPrettyPrintTo( 'Immutable.Stack [<Mouse>Hello World</Mouse>, <Mouse>Hello World</Mouse>]', {min: true}, ); }); it('supports React elements {min: false}', () => { const reactElement = React.createElement('Mouse', null, 'Hello World'); expect(Immutable.Stack([reactElement, reactElement])).toPrettyPrintTo( 'Immutable.Stack [\n <Mouse>\n Hello World\n </Mouse>,\n <Mouse>\n Hello World\n </Mouse>,\n]', ); }); }); describe('Immutable.Set', () => { it('supports an empty collection {min: true}', () => { expect(Immutable.Set([])).toPrettyPrintTo('Immutable.Set []', {min: true}); }); it('supports an empty collection {min: false}', () => { expect(Immutable.Set([])).toPrettyPrintTo('Immutable.Set []', { min: false, }); }); it('supports a single string element', () => { expect(Immutable.Set(['foo'])).toPrettyPrintTo('Immutable.Set ["foo"]', { min: true, }); }); it('supports a single integer element', () => { expect(Immutable.Set([1])).toPrettyPrintTo('Immutable.Set [1]', { min: true, }); }); it('supports multiple string elements {min: true}', () => { expect(Immutable.Set(['jhon', 'mike', 'cristian'])).toPrettyPrintTo( 'Immutable.Set ["jhon", "mike", "cristian"]', { min: true, }, ); }); it('supports multiple string elements {min: false}', () => { expect(Immutable.Set(['jhon', 'mike', 'cristian'])).toPrettyPrintTo( 'Immutable.Set [\n "jhon",\n "mike",\n "cristian",\n]', ); }); it('supports multiple integer elements {min: true}', () => { expect(Immutable.Set([1, 2, 3])).toPrettyPrintTo( 'Immutable.Set [1, 2, 3]', {min: true}, ); }); it('supports multiple integer elements {min: false}', () => { expect(Immutable.Set([1, 2, 3])).toPrettyPrintTo( 'Immutable.Set [\n 1,\n 2,\n 3,\n]', ); }); it('supports object elements {min: true}', () => { expect(Immutable.Set([{a: 1, b: 2, c: 3}])).toPrettyPrintTo( 'Immutable.Set [{"a": 1, "b": 2, "c": 3}]', {min: true}, ); }); it('supports object elements {min: false}', () => { expect(Immutable.Set([{a: 1, b: 2, c: 3}])).toPrettyPrintTo( 'Immutable.Set [\n Object {\n "a": 1,\n "b": 2,\n "c": 3,\n },\n]', ); }); it('supports React elements {min: true}', () => { const reactElement = React.createElement('Mouse', null, 'Hello World'); expect(Immutable.Set([reactElement, reactElement])).toPrettyPrintTo( 'Immutable.Set [<Mouse>Hello World</Mouse>]', { min: true, }, ); }); it('supports React elements {min: false}', () => { const reactElement = React.createElement('Mouse', null, 'Hello World'); expect(Immutable.Set([reactElement, reactElement])).toPrettyPrintTo( 'Immutable.Set [\n <Mouse>\n Hello World\n </Mouse>,\n]', ); }); }); describe('Immutable.Map', () => { it('supports an empty collection {min: true}', () => { expect(Immutable.Map({})).toPrettyPrintTo('Immutable.Map {}', {min: true}); }); it('supports an empty collection {min: false}', () => { expect(Immutable.Map({})).toPrettyPrintTo('Immutable.Map {}', { min: false, }); }); it('supports an object with single key', () => { expect(Immutable.Map({a: 1})).toPrettyPrintTo('Immutable.Map {"a": 1}', { min: true, }); }); it('supports an object with multiple keys {min: true}', () => { expect(Immutable.Map({a: 1, b: 2, c: 3})).toPrettyPrintTo( 'Immutable.Map {"a": 1, "b": 2, "c": 3}', {min: true}, ); }); it('supports an object with multiple keys {min: false}', () => { expect(Immutable.Map({a: 1, b: 2, c: 3})).toPrettyPrintTo( 'Immutable.Map {\n "a": 1,\n "b": 2,\n "c": 3,\n}', ); }); it('supports object elements {min: true}', () => { expect(Immutable.Map({key: {a: 1, b: 2, c: 3}})).toPrettyPrintTo( 'Immutable.Map {"key": {"a": 1, "b": 2, "c": 3}}', { min: true, }, ); }); it('supports object elements {min: false}', () => { expect(Immutable.Map({key: {a: 1, b: 2, c: 3}})).toPrettyPrintTo( 'Immutable.Map {\n "key": Object {\n "a": 1,\n "b": 2,\n "c": 3,\n },\n}', ); }); it('supports React elements {min: true}', () => { const reactElement = React.createElement('Mouse', null, 'Hello World'); expect(Immutable.Map({a: reactElement, b: reactElement})).toPrettyPrintTo( 'Immutable.Map {"a": <Mouse>Hello World</Mouse>, "b": <Mouse>Hello World</Mouse>}', {min: true}, ); }); it('supports React elements {min: false}', () => { const reactElement = React.createElement('Mouse', null, 'Hello World'); expect(Immutable.Map({a: reactElement, b: reactElement})).toPrettyPrintTo( 'Immutable.Map {\n "a": <Mouse>\n Hello World\n </Mouse>,\n "b": <Mouse>\n Hello World\n </Mouse>,\n}', ); }); }); describe('Immutable.OrderedMap', () => { it('supports an empty collection {min: true}', () => { expect(Immutable.OrderedMap({})).toPrettyPrintTo( 'Immutable.OrderedMap {}', {min: true}, ); }); it('supports an empty collection {min: false}', () => { expect(Immutable.OrderedMap({})).toPrettyPrintTo( 'Immutable.OrderedMap {}', {min: false}, ); }); it('supports an object with single key', () => { expect(Immutable.OrderedMap({a: 1})).toPrettyPrintTo( 'Immutable.OrderedMap {"a": 1}', {min: true}, ); }); it('supports an object with multiple keys {min: true}', () => { expect(Immutable.OrderedMap({a: 1, b: 2, c: 3})).toPrettyPrintTo( 'Immutable.OrderedMap {"a": 1, "b": 2, "c": 3}', { min: true, }, ); }); it('supports an object with multiple keys {min: false}', () => { expect(Immutable.OrderedMap({a: 1, b: 2, c: 3})).toPrettyPrintTo( 'Immutable.OrderedMap {\n "a": 1,\n "b": 2,\n "c": 3,\n}', ); }); it('supports object elements {min: true}', () => { expect(Immutable.OrderedMap({key: {a: 1, b: 2, c: 3}})).toPrettyPrintTo( 'Immutable.OrderedMap {"key": {"a": 1, "b": 2, "c": 3}}', { min: true, }, ); }); it('supports object elements {min: false}', () => { expect(Immutable.OrderedMap({key: {a: 1, b: 2, c: 3}})).toPrettyPrintTo( 'Immutable.OrderedMap {\n "key": Object {\n "a": 1,\n "b": 2,\n "c": 3,\n },\n}', ); }); it('supports React elements {min: true}', () => { const reactElement = React.createElement('Mouse', null, 'Hello World'); expect( Immutable.OrderedMap({a: reactElement, b: reactElement}), ).toPrettyPrintTo( 'Immutable.OrderedMap {"a": <Mouse>Hello World</Mouse>, "b": <Mouse>Hello World</Mouse>}', {min: true}, ); }); it('supports React elements {min: false}', () => { const reactElement = React.createElement('Mouse', null, 'Hello World'); expect( Immutable.OrderedMap({a: reactElement, b: reactElement}), ).toPrettyPrintTo( 'Immutable.OrderedMap {\n "a": <Mouse>\n Hello World\n </Mouse>,\n "b": <Mouse>\n Hello World\n </Mouse>,\n}', ); }); it('supports non-string keys', () => { const val = Immutable.OrderedMap<unknown, unknown>([ [false, 'boolean'], ['false', 'string'], [0, 'number'], ['0', 'string'], [null, 'null'], ['null', 'string'], [undefined, 'undefined'], ['undefined', 'string'], [Symbol('description'), 'symbol'], ['Symbol(description)', 'string'], [['array', 'key'], 'array'], [{key: 'value'}, 'object'], [Immutable.Map({key: 'value'}), 'immutable map'], ]); const expected = [ 'Immutable.OrderedMap {', ' false: "boolean",', ' "false": "string",', ' 0: "number",', ' "0": "string",', ' null: "null",', ' "null": "string",', ' undefined: "undefined",', ' "undefined": "string",', ' Symbol(description): "symbol",', ' "Symbol(description)": "string",', ' Array [', ' "array",', ' "key",', ' ]: "array",', ' Object {', ' "key": "value",', ' }: "object",', ' Immutable.Map {', ' "key": "value",', ' }: "immutable map",', '}', ].join('\n'); expect(val).toPrettyPrintTo(expected); }); }); describe('Immutable.Record', () => { it('supports an empty record {min: true}', () => { const ABRecord = Immutable.Record({}, 'ABRecord'); expect(ABRecord()).toPrettyPrintTo('Immutable.ABRecord {}', { min: true, }); }); it('supports an empty record {min: false}', () => { const ABRecord = Immutable.Record({}, 'ABRecord'); expect(ABRecord()).toPrettyPrintTo('Immutable.ABRecord {}', { min: false, }); }); it('supports a record with descriptive name', () => { const ABRecord = Immutable.Record({a: 1, b: 2}, 'ABRecord'); expect(ABRecord()).toPrettyPrintTo('Immutable.ABRecord {"a": 1, "b": 2}', { min: true, }); }); it('supports a record without descriptive name', () => { const ABRecord = Immutable.Record({a: 1, b: 2}); expect(ABRecord()).toPrettyPrintTo('Immutable.Record {"a": 1, "b": 2}', { min: true, }); }); it('supports a record with values {min: true}', () => { const ABRecord = Immutable.Record({a: 1, b: 2}, 'ABRecord'); expect(ABRecord({a: 3, b: 4})).toPrettyPrintTo( 'Immutable.ABRecord {"a": 3, "b": 4}', {min: true}, ); }); it('supports a record with values {min: false}', () => { const ABRecord = Immutable.Record({a: 1, b: 2}, 'ABRecord'); expect(ABRecord({a: 3, b: 4})).toPrettyPrintTo( 'Immutable.ABRecord {\n "a": 3,\n "b": 4,\n}', ); }); it('supports a record with Map value {min: true}', () => { const ABRecord = Immutable.Record( {a: Immutable.Map({c: 1}), b: 2}, 'ABRecord', ); expect(ABRecord()).toPrettyPrintTo( 'Immutable.ABRecord {"a": Immutable.Map {"c": 1}, "b": 2}', { min: true, }, ); }); it('supports a record with Map value {min: false}', () => { const ABRecord = Immutable.Record( {a: Immutable.Map({c: 1}), b: 2}, 'ABRecord', ); expect(ABRecord()).toPrettyPrintTo( 'Immutable.ABRecord {\n "a": Immutable.Map {\n "c": 1,\n },\n "b": 2,\n}', ); }); it('supports imbricated Record {min: true}', () => { const CDRecord = Immutable.Record({c: 3, d: 4}, 'CDRecord'); const ABRecord = Immutable.Record({a: CDRecord(), b: 2}, 'ABRecord'); expect(ABRecord()).toPrettyPrintTo( 'Immutable.ABRecord {"a": Immutable.CDRecord {"c": 3, "d": 4}, "b": 2}', {min: true}, ); }); it('supports imbricated Record {min: false}', () => { const CDRecord = Immutable.Record({c: 3, d: 4}, 'CDRecord'); const ABRecord = Immutable.Record({a: CDRecord(), b: 2}, 'ABRecord'); expect(ABRecord()).toPrettyPrintTo( 'Immutable.ABRecord {\n "a": Immutable.CDRecord {\n "c": 3,\n "d": 4,\n },\n "b": 2,\n}', ); }); }); describe('indentation of heterogeneous collections', () => { // Don’t interpret tests that pretty-format and plugins are compatible // as recommendation to compose immutable and non-immutable collections. test('empty Immutable.List as child of Object', () => { const val = { filter: 'all', todos: Immutable.List([]), }; expect(val).toPrettyPrintTo( [ 'Object {', ' "filter": "all",', ' "todos": Immutable.List [],', '}', ].join('\n'), ); }); test('empty Immutable.Map as child of Array', () => { const val = [Immutable.Map({})]; expect(val).toPrettyPrintTo( ['Array [', ' Immutable.Map {},', ']'].join('\n'), ); }); test('non-empty Array as child of Immutable.Map', () => { const val = Immutable.Map({ filter: 'completed', todos: [ Immutable.Map({ completed: true, text: 'Replace print with serialize', }), ], }); expect(val).toPrettyPrintTo( [ 'Immutable.Map {', ' "filter": "completed",', ' "todos": Array [', ' Immutable.Map {', ' "completed": true,', ' "text": "Replace print with serialize",', ' },', ' ],', '}', ].join('\n'), ); }); test('non-empty Object as child of Immutable.List', () => { const val = Immutable.List([ { completed: true, text: 'Replace print with serialize', }, ]); expect(val).toPrettyPrintTo( [ 'Immutable.List [', ' Object {', ' "completed": true,', ' "text": "Replace print with serialize",', ' },', ']', ].join('\n'), ); }); }); describe('indent option', () => { const val = Immutable.Map({ filter: 'completed', todos: Immutable.List([ Immutable.Map({ completed: true, text: 'Replace print with serialize', }), Immutable.Map({ completed: false, text: 'Return if depth exceeds max', }), ]), }); const expected = [ 'Immutable.Map {', ' "filter": "completed",', ' "todos": Immutable.List [', ' Immutable.Map {', ' "completed": true,', ' "text": "Replace print with serialize",', ' },', ' Immutable.Map {', ' "completed": false,', ' "text": "Return if depth exceeds max",', ' },', ' ],', '}', ].join('\n'); test('default implicit: 2 spaces', () => { expect(val).toPrettyPrintTo(expected); }); test('default explicit: 2 spaces', () => { expect(val).toPrettyPrintTo(expected, {indent: 2}); }); // Tests assume that no strings in val contain multiple adjacent spaces! test('non-default: 0 spaces', () => { const indent = 0; expect(val).toPrettyPrintTo(expected.replace(/ {2}/g, ' '.repeat(indent)), { indent, }); }); test('non-default: 4 spaces', () => { const indent = 4; expect(val).toPrettyPrintTo(expected.replace(/ {2}/g, ' '.repeat(indent)), { indent, }); }); }); describe('maxDepth option', () => { // Don’t interpret tests that pretty-format and plugins are compatible // as recommendation to compose immutable and non-immutable collections. test('Immutable.List as child of Object', () => { const val = { // ++depth === 1 filter: 'all', todos: Immutable.List([ Immutable.Map({ completed: true, text: 'Return if depth exceeds max', }), ]), }; const expected = [ 'Object {', ' "filter": "all",', ' "todos": [Immutable.List],', '}', ].join('\n'); expect(val).toPrettyPrintTo(expected, {maxDepth: 1}); }); test('Immutable.Map as child of Array', () => { const val = [ // ++depth === 1 Immutable.Map({ completed: false, text: 'Return if depth exceeds max', }), ]; const expected = ['Array [', ' [Immutable.Map],', ']'].join('\n'); expect(val).toPrettyPrintTo(expected, {maxDepth: 1}); }); test('Immutable.Seq as child of Immutable.Map', () => { const val = { // ++depth === 1 filter: 'all', todos: Immutable.Seq( Immutable.List([ Immutable.Map({ completed: true, text: 'Return if depth exceeds max', }), ]), ), }; const expected = [ 'Object {', ' "filter": "all",', ' "todos": [Immutable.Seq],', '}', ].join('\n'); expect(val).toPrettyPrintTo(expected, {maxDepth: 1}); }); test('Immutable.Map as descendants in immutable collection', () => { const val = Immutable.Map({ // ++depth === 1 filter: 'uncompleted', todos: Immutable.List([ // ++depth === 2 Immutable.Map({ // ++depth === 3 completed: true, text: 'Replace print with serialize', }), Immutable.Map({ // ++depth === 3 completed: true, text: 'Return if depth exceeds max', }), ]), }); const expected = [ 'Immutable.Map {', ' "filter": "uncompleted",', ' "todos": Immutable.List [', ' [Immutable.Map],', ' [Immutable.Map],', ' ],', '}', ].join('\n'); expect(val).toPrettyPrintTo(expected, {maxDepth: 2}); }); }); describe('Immutable.Seq', () => { it('supports an empty sequence from array {min: true}', () => { expect(Immutable.Seq([])).toPrettyPrintTo('Immutable.Seq []', {min: true}); }); it('supports an empty sequence from array {min: false}', () => { expect(Immutable.Seq([])).toPrettyPrintTo('Immutable.Seq []', {min: false}); }); it('supports a non-empty sequence from array {min: true}', () => { expect(Immutable.Seq([0, 1, 2])).toPrettyPrintTo( 'Immutable.Seq [0, 1, 2]', {min: true}, ); }); it('supports a non-empty sequence from array {min: false}', () => { expect(Immutable.Seq([0, 1, 2])).toPrettyPrintTo( 'Immutable.Seq [\n 0,\n 1,\n 2,\n]', {min: false}, ); }); it('supports a non-empty sequence from arguments', () => { function returnArguments(..._args: Array<any>) { return arguments; } expect(Immutable.Seq(returnArguments(0, 1, 2))).toPrettyPrintTo( 'Immutable.Seq [\n 0,\n 1,\n 2,\n]', ); }); it('supports an empty sequence from object {min: true}', () => { expect(Immutable.Seq({})).toPrettyPrintTo('Immutable.Seq {}', {min: true}); }); it('supports an empty sequence from object {min: false}', () => { expect(Immutable.Seq({})).toPrettyPrintTo('Immutable.Seq {}', {min: false}); }); it('supports a non-empty sequence from object {min: true}', () => { expect(Immutable.Seq({key: 'value'})).toPrettyPrintTo( 'Immutable.Seq {"key": "value"}', { min: true, }, ); }); it('supports a non-empty sequence from object {min: false}', () => { expect(Immutable.Seq({key: 'value'})).toPrettyPrintTo( 'Immutable.Seq {\n "key": "value",\n}', { min: false, }, ); }); it('supports a sequence of entries from Immutable.Map', () => { expect(Immutable.Seq(Immutable.Map({key: 'value'}))).toPrettyPrintTo( 'Immutable.Seq {\n "key": "value",\n}', ); }); it('supports a sequence of values from ECMAScript Set', () => { expect(Immutable.Seq(new Set([0, 1, 2]))).toPrettyPrintTo( 'Immutable.Seq [\n 0,\n 1,\n 2,\n]', ); }); it('supports a sequence of values from Immutable.List', () => { expect(Immutable.Seq(Immutable.List([0, 1, 2]))).toPrettyPrintTo( 'Immutable.Seq [\n 0,\n 1,\n 2,\n]', ); }); it('supports a sequence of values from Immutable.Set', () => { expect(Immutable.Seq(Immutable.Set([0, 1, 2]))).toPrettyPrintTo( 'Immutable.Seq [\n 0,\n 1,\n 2,\n]', ); }); it('supports a sequence of values from Immutable.Stack', () => { expect(Immutable.Seq(Immutable.Stack([0, 1, 2]))).toPrettyPrintTo( 'Immutable.Seq [\n 0,\n 1,\n 2,\n]', ); }); }); describe('Immutable.Seq lazy entries', () => { const expected = 'Immutable.Seq {…}'; const object = {key0: '', key1: '1'}; const filterer = (value: string) => value.length !== 0; // undefined size confirms correct criteria for lazy Seq test('from object properties', () => { const val = Immutable.Seq(object).filter(filterer); expect(val.size).toBeUndefined(); expect(val).toPrettyPrintTo(expected); }); test('from Immutable.Map entries', () => { const val = Immutable.Seq(Immutable.Map(object)).filter(filterer); expect(val.size).toBeUndefined(); expect(val).toPrettyPrintTo(expected); }); }); describe('Immutable.Seq lazy values', () => { const expected = 'Immutable.Seq […]'; const array = ['', '1', '22']; const filterer = (item: string) => item.length !== 0; test('from Immutable.Range', () => { const val = Immutable.Range(1, Infinity); expect(val.size).toBe(Infinity); expect(val).toPrettyPrintTo(expected); }); // undefined size confirms correct criteria for lazy Seq test('from iterator', () => { function returnIterator(values: Array<string>) { let i = 0; return { next() { return i < values.length ? {done: false, value: values[i++]} : {done: true}; }, }; } const val = Immutable.Seq(returnIterator(array)); expect(val.size).toBeUndefined(); expect(val).toPrettyPrintTo(expected); }); test('from array items', () => { const val = Immutable.Seq(array).filter(filterer); expect(val.size).toBeUndefined(); expect(val).toPrettyPrintTo(expected); }); test('from Immutable.List values', () => { const val = Immutable.Seq(Immutable.List(array)).filter(filterer); expect(val.size).toBeUndefined(); expect(val).toPrettyPrintTo(expected); }); test('from ECMAScript Set values', () => { const val = Immutable.Seq(new Set(array)).filter(filterer); expect(val.size).toBeUndefined(); expect(val).toPrettyPrintTo(expected); }); });
the_stack
import { BoneData, TransformMode } from "./BoneData"; import { Skeleton } from "./Skeleton"; import { Updatable } from "./Updatable"; import { MathUtils, Vector2 } from "./Utils"; /** Stores a bone's current pose. * * A bone has a local transform which is used to compute its world transform. A bone also has an applied transform, which is a * local transform that can be applied to compute the world transform. The local transform and applied transform may differ if a * constraint or application code modifies the world transform after it was computed from the local transform. */ export class Bone implements Updatable { /** The bone's setup pose data. */ data: BoneData; /** The skeleton this bone belongs to. */ skeleton: Skeleton; /** The parent bone, or null if this is the root bone. */ parent: Bone; /** The immediate children of this bone. */ children = new Array<Bone>(); /** The local x translation. */ x = 0; /** The local y translation. */ y = 0; /** The local rotation in degrees, counter clockwise. */ rotation = 0; /** The local scaleX. */ scaleX = 0; /** The local scaleY. */ scaleY = 0; /** The local shearX. */ shearX = 0; /** The local shearY. */ shearY = 0; /** The applied local x translation. */ ax = 0; /** The applied local y translation. */ ay = 0; /** The applied local rotation in degrees, counter clockwise. */ arotation = 0; /** The applied local scaleX. */ ascaleX = 0; /** The applied local scaleY. */ ascaleY = 0; /** The applied local shearX. */ ashearX = 0; /** The applied local shearY. */ ashearY = 0; /** Part of the world transform matrix for the X axis. If changed, {@link #updateAppliedTransform()} should be called. */ a = 0; /** Part of the world transform matrix for the Y axis. If changed, {@link #updateAppliedTransform()} should be called. */ b = 0; /** Part of the world transform matrix for the X axis. If changed, {@link #updateAppliedTransform()} should be called. */ c = 0; /** Part of the world transform matrix for the Y axis. If changed, {@link #updateAppliedTransform()} should be called. */ d = 0; /** The world X position. If changed, {@link #updateAppliedTransform()} should be called. */ worldY = 0; /** The world Y position. If changed, {@link #updateAppliedTransform()} should be called. */ worldX = 0; sorted = false; active = false; /** @param parent May be null. */ constructor (data: BoneData, skeleton: Skeleton, parent: Bone) { if (!data) throw new Error("data cannot be null."); if (!skeleton) throw new Error("skeleton cannot be null."); this.data = data; this.skeleton = skeleton; this.parent = parent; this.setToSetupPose(); } /** Returns false when the bone has not been computed because {@link BoneData#skinRequired} is true and the * {@link Skeleton#skin active skin} does not {@link Skin#bones contain} this bone. */ isActive () { return this.active; } /** Computes the world transform using the parent bone and this bone's local applied transform. */ update () { this.updateWorldTransformWith(this.ax, this.ay, this.arotation, this.ascaleX, this.ascaleY, this.ashearX, this.ashearY); } /** Computes the world transform using the parent bone and this bone's local transform. * * See {@link #updateWorldTransformWith()}. */ updateWorldTransform () { this.updateWorldTransformWith(this.x, this.y, this.rotation, this.scaleX, this.scaleY, this.shearX, this.shearY); } /** Computes the world transform using the parent bone and the specified local transform. The applied transform is set to the * specified local transform. Child bones are not updated. * * See [World transforms](http://esotericsoftware.com/spine-runtime-skeletons#World-transforms) in the Spine * Runtimes Guide. */ updateWorldTransformWith (x: number, y: number, rotation: number, scaleX: number, scaleY: number, shearX: number, shearY: number) { this.ax = x; this.ay = y; this.arotation = rotation; this.ascaleX = scaleX; this.ascaleY = scaleY; this.ashearX = shearX; this.ashearY = shearY; let parent = this.parent; if (!parent) { // Root bone. let skeleton = this.skeleton; let rotationY = rotation + 90 + shearY; let sx = skeleton.scaleX; let sy = skeleton.scaleY; this.a = MathUtils.cosDeg(rotation + shearX) * scaleX * sx; this.b = MathUtils.cosDeg(rotationY) * scaleY * sx; this.c = MathUtils.sinDeg(rotation + shearX) * scaleX * sy; this.d = MathUtils.sinDeg(rotationY) * scaleY * sy; this.worldX = x * sx + skeleton.x; this.worldY = y * sy + skeleton.y; return; } let pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d; this.worldX = pa * x + pb * y + parent.worldX; this.worldY = pc * x + pd * y + parent.worldY; switch (this.data.transformMode) { case TransformMode.Normal: { let rotationY = rotation + 90 + shearY; let la = MathUtils.cosDeg(rotation + shearX) * scaleX; let lb = MathUtils.cosDeg(rotationY) * scaleY; let lc = MathUtils.sinDeg(rotation + shearX) * scaleX; let ld = MathUtils.sinDeg(rotationY) * scaleY; this.a = pa * la + pb * lc; this.b = pa * lb + pb * ld; this.c = pc * la + pd * lc; this.d = pc * lb + pd * ld; return; } case TransformMode.OnlyTranslation: { let rotationY = rotation + 90 + shearY; this.a = MathUtils.cosDeg(rotation + shearX) * scaleX; this.b = MathUtils.cosDeg(rotationY) * scaleY; this.c = MathUtils.sinDeg(rotation + shearX) * scaleX; this.d = MathUtils.sinDeg(rotationY) * scaleY; break; } case TransformMode.NoRotationOrReflection: { let s = pa * pa + pc * pc; let prx = 0; if (s > 0.0001) { s = Math.abs(pa * pd - pb * pc) / s; pa /= this.skeleton.scaleX; pc /= this.skeleton.scaleY; pb = pc * s; pd = pa * s; prx = Math.atan2(pc, pa) * MathUtils.radDeg; } else { pa = 0; pc = 0; prx = 90 - Math.atan2(pd, pb) * MathUtils.radDeg; } let rx = rotation + shearX - prx; let ry = rotation + shearY - prx + 90; let la = MathUtils.cosDeg(rx) * scaleX; let lb = MathUtils.cosDeg(ry) * scaleY; let lc = MathUtils.sinDeg(rx) * scaleX; let ld = MathUtils.sinDeg(ry) * scaleY; this.a = pa * la - pb * lc; this.b = pa * lb - pb * ld; this.c = pc * la + pd * lc; this.d = pc * lb + pd * ld; break; } case TransformMode.NoScale: case TransformMode.NoScaleOrReflection: { let cos = MathUtils.cosDeg(rotation); let sin = MathUtils.sinDeg(rotation); let za = (pa * cos + pb * sin) / this.skeleton.scaleX; let zc = (pc * cos + pd * sin) / this.skeleton.scaleY; let s = Math.sqrt(za * za + zc * zc); if (s > 0.00001) s = 1 / s; za *= s; zc *= s; s = Math.sqrt(za * za + zc * zc); if (this.data.transformMode == TransformMode.NoScale && (pa * pd - pb * pc < 0) != (this.skeleton.scaleX < 0 != this.skeleton.scaleY < 0)) s = -s; let r = Math.PI / 2 + Math.atan2(zc, za); let zb = Math.cos(r) * s; let zd = Math.sin(r) * s; let la = MathUtils.cosDeg(shearX) * scaleX; let lb = MathUtils.cosDeg(90 + shearY) * scaleY; let lc = MathUtils.sinDeg(shearX) * scaleX; let ld = MathUtils.sinDeg(90 + shearY) * scaleY; this.a = za * la + zb * lc; this.b = za * lb + zb * ld; this.c = zc * la + zd * lc; this.d = zc * lb + zd * ld; break; } } this.a *= this.skeleton.scaleX; this.b *= this.skeleton.scaleX; this.c *= this.skeleton.scaleY; this.d *= this.skeleton.scaleY; } /** Sets this bone's local transform to the setup pose. */ setToSetupPose () { let data = this.data; this.x = data.x; this.y = data.y; this.rotation = data.rotation; this.scaleX = data.scaleX; this.scaleY = data.scaleY; this.shearX = data.shearX; this.shearY = data.shearY; } /** The world rotation for the X axis, calculated using {@link #a} and {@link #c}. */ getWorldRotationX () { return Math.atan2(this.c, this.a) * MathUtils.radDeg; } /** The world rotation for the Y axis, calculated using {@link #b} and {@link #d}. */ getWorldRotationY () { return Math.atan2(this.d, this.b) * MathUtils.radDeg; } /** The magnitude (always positive) of the world scale X, calculated using {@link #a} and {@link #c}. */ getWorldScaleX () { return Math.sqrt(this.a * this.a + this.c * this.c); } /** The magnitude (always positive) of the world scale Y, calculated using {@link #b} and {@link #d}. */ getWorldScaleY () { return Math.sqrt(this.b * this.b + this.d * this.d); } /** Computes the applied transform values from the world transform. * * If the world transform is modified (by a constraint, {@link #rotateWorld(float)}, etc) then this method should be called so * the applied transform matches the world transform. The applied transform may be needed by other code (eg to apply other * constraints). * * Some information is ambiguous in the world transform, such as -1,-1 scale versus 180 rotation. The applied transform after * calling this method is equivalent to the local transform used to compute the world transform, but may not be identical. */ updateAppliedTransform () { let parent = this.parent; if (!parent) { this.ax = this.worldX - this.skeleton.x; this.ay = this.worldY - this.skeleton.y; this.arotation = Math.atan2(this.c, this.a) * MathUtils.radDeg; this.ascaleX = Math.sqrt(this.a * this.a + this.c * this.c); this.ascaleY = Math.sqrt(this.b * this.b + this.d * this.d); this.ashearX = 0; this.ashearY = Math.atan2(this.a * this.b + this.c * this.d, this.a * this.d - this.b * this.c) * MathUtils.radDeg; return; } let pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d; let pid = 1 / (pa * pd - pb * pc); let dx = this.worldX - parent.worldX, dy = this.worldY - parent.worldY; this.ax = (dx * pd * pid - dy * pb * pid); this.ay = (dy * pa * pid - dx * pc * pid); let ia = pid * pd; let id = pid * pa; let ib = pid * pb; let ic = pid * pc; let ra = ia * this.a - ib * this.c; let rb = ia * this.b - ib * this.d; let rc = id * this.c - ic * this.a; let rd = id * this.d - ic * this.b; this.ashearX = 0; this.ascaleX = Math.sqrt(ra * ra + rc * rc); if (this.ascaleX > 0.0001) { let det = ra * rd - rb * rc; this.ascaleY = det / this.ascaleX; this.ashearY = Math.atan2(ra * rb + rc * rd, det) * MathUtils.radDeg; this.arotation = Math.atan2(rc, ra) * MathUtils.radDeg; } else { this.ascaleX = 0; this.ascaleY = Math.sqrt(rb * rb + rd * rd); this.ashearY = 0; this.arotation = 90 - Math.atan2(rd, rb) * MathUtils.radDeg; } } /** Transforms a point from world coordinates to the bone's local coordinates. */ worldToLocal (world: Vector2) { let invDet = 1 / (this.a * this.d - this.b * this.c); let x = world.x - this.worldX, y = world.y - this.worldY; world.x = x * this.d * invDet - y * this.b * invDet; world.y = y * this.a * invDet - x * this.c * invDet; return world; } /** Transforms a point from the bone's local coordinates to world coordinates. */ localToWorld (local: Vector2) { let x = local.x, y = local.y; local.x = x * this.a + y * this.b + this.worldX; local.y = x * this.c + y * this.d + this.worldY; return local; } /** Transforms a world rotation to a local rotation. */ worldToLocalRotation (worldRotation: number) { let sin = MathUtils.sinDeg(worldRotation), cos = MathUtils.cosDeg(worldRotation); return Math.atan2(this.a * sin - this.c * cos, this.d * cos - this.b * sin) * MathUtils.radDeg + this.rotation - this.shearX; } /** Transforms a local rotation to a world rotation. */ localToWorldRotation (localRotation: number) { localRotation -= this.rotation - this.shearX; let sin = MathUtils.sinDeg(localRotation), cos = MathUtils.cosDeg(localRotation); return Math.atan2(cos * this.c + sin * this.d, cos * this.a + sin * this.b) * MathUtils.radDeg; } /** Rotates the world transform the specified amount. * <p> * After changes are made to the world transform, {@link #updateAppliedTransform()} should be called and {@link #update()} will * need to be called on any child bones, recursively. */ rotateWorld (degrees: number) { let a = this.a, b = this.b, c = this.c, d = this.d; let cos = MathUtils.cosDeg(degrees), sin = MathUtils.sinDeg(degrees); this.a = cos * a - sin * c; this.b = cos * b - sin * d; this.c = sin * a + cos * c; this.d = sin * b + cos * d; } }
the_stack
module Fayde.Controls { export class ScrollViewer extends ContentControl { private static _ScrollBarVisibilityChanged(d: DependencyObject, args: IDependencyPropertyChangedEventArgs) { if (!d) return; if (d instanceof ScrollViewer) { var sv = <ScrollViewer>d; sv.XamlNode.LayoutUpdater.invalidateMeasure(); var scrollInfo = sv.ScrollInfo; if (scrollInfo) { scrollInfo.CanHorizontallyScroll = sv.HorizontalScrollBarVisibility !== ScrollBarVisibility.Disabled; scrollInfo.CanVerticallyScroll = sv.VerticalScrollBarVisibility !== ScrollBarVisibility.Disabled; } sv._UpdateScrollBarVisibility(); return; } if (d instanceof ListBox) { var listbox = <ListBox>d; if (listbox.$TemplateScrollViewer) listbox.$TemplateScrollViewer.SetValue(args.Property, args.NewValue); return; } } static HorizontalScrollBarVisibilityProperty = DependencyProperty.RegisterAttachedCore("HorizontalScrollBarVisibility", () => new Enum(ScrollBarVisibility), ScrollViewer, ScrollBarVisibility.Disabled, ScrollViewer._ScrollBarVisibilityChanged); static GetHorizontalScrollBarVisibility(d: DependencyObject): ScrollBarVisibility { return d.GetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty); } static SetHorizontalScrollBarVisibility(d: DependencyObject, value: ScrollBarVisibility) { d.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, value); } get HorizontalScrollBarVisibility(): ScrollBarVisibility { return this.GetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty); } set HorizontalScrollBarVisibility(value: ScrollBarVisibility) { this.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, value); } static VerticalScrollBarVisibilityProperty = DependencyProperty.RegisterAttachedCore("VerticalScrollBarVisibility", () => new Enum(ScrollBarVisibility), ScrollViewer, ScrollBarVisibility.Disabled, ScrollViewer._ScrollBarVisibilityChanged); static GetVerticalScrollBarVisibility(d: DependencyObject): ScrollBarVisibility { return d.GetValue(ScrollViewer.VerticalScrollBarVisibilityProperty); } static SetVerticalScrollBarVisibility(d: DependencyObject, value: ScrollBarVisibility) { d.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, value); } get VerticalScrollBarVisibility(): ScrollBarVisibility { return this.GetValue(ScrollViewer.VerticalScrollBarVisibilityProperty); } set VerticalScrollBarVisibility(value: ScrollBarVisibility) { this.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, value); } static ComputedHorizontalScrollBarVisibilityProperty = DependencyProperty.RegisterReadOnlyCore("ComputedHorizontalScrollBarVisibility", () => new Enum(Visibility), ScrollViewer); static ComputedVerticalScrollBarVisibilityProperty = DependencyProperty.RegisterReadOnlyCore("ComputedVerticalScrollBarVisibility", () => new Enum(Visibility), ScrollViewer); static HorizontalOffsetProperty = DependencyProperty.RegisterReadOnlyCore("HorizontalOffset", () => Number, ScrollViewer); static VerticalOffsetProperty = DependencyProperty.RegisterReadOnlyCore("VerticalOffset", () => Number, ScrollViewer); static ScrollableWidthProperty = DependencyProperty.RegisterReadOnlyCore("ScrollableWidth", () => Number, ScrollViewer); static ScrollableHeightProperty = DependencyProperty.RegisterReadOnlyCore("ScrollableHeight", () => Number, ScrollViewer); static ViewportWidthProperty = DependencyProperty.RegisterReadOnlyCore("ViewportWidth", () => Number, ScrollViewer); static ViewportHeightProperty = DependencyProperty.RegisterReadOnlyCore("ViewportHeight", () => Number, ScrollViewer); static ExtentWidthProperty = DependencyProperty.RegisterReadOnlyCore("ExtentWidth", () => Number, ScrollViewer); static ExtentHeightProperty = DependencyProperty.RegisterReadOnlyCore("ExtentHeight", () => Number, ScrollViewer); ComputedHorizontalScrollBarVisibility: Visibility; ComputedVerticalScrollBarVisibility: Visibility; HorizontalOffset: number; VerticalOffset: number; ScrollableWidth: number; ScrollableHeight: number; ViewportWidth: number; ViewportHeight: number; ExtentWidth: number; ExtentHeight: number; $TemplatedParentHandlesScrolling: boolean = false; $ScrollContentPresenter: ScrollContentPresenter; private $HorizontalScrollBar: Primitives.ScrollBar; private $VerticalScrollBar: Primitives.ScrollBar; constructor() { super(); //this.RequestBringIntoView.Subscribe(this._OnRequestBringIntoView, this); this.DefaultStyleKey = ScrollViewer; } private _ScrollInfo: Primitives.IScrollInfo; get ScrollInfo(): Primitives.IScrollInfo { return this._ScrollInfo; } set ScrollInfo(value: Primitives.IScrollInfo) { this._ScrollInfo = value; if (value) { value.CanHorizontallyScroll = this.HorizontalScrollBarVisibility !== ScrollBarVisibility.Disabled; value.CanVerticallyScroll = this.VerticalScrollBarVisibility !== ScrollBarVisibility.Disabled; } } InvalidateScrollInfo() { var scrollInfo = this.ScrollInfo; if (scrollInfo) { this.SetCurrentValue(ScrollViewer.ExtentWidthProperty, scrollInfo.ExtentWidth); this.SetCurrentValue(ScrollViewer.ExtentHeightProperty, scrollInfo.ExtentHeight); this.SetCurrentValue(ScrollViewer.ViewportWidthProperty, scrollInfo.ViewportWidth); this.SetCurrentValue(ScrollViewer.ViewportHeightProperty, scrollInfo.ViewportHeight); this._UpdateScrollBar(Orientation.Horizontal, scrollInfo.HorizontalOffset); this._UpdateScrollBar(Orientation.Vertical, scrollInfo.VerticalOffset); this._UpdateScrollBarVisibility(); } var lu = this.XamlNode.LayoutUpdater; var w = Math.max(0, this.ExtentWidth - this.ViewportWidth); if (w !== this.ScrollableWidth) { this.SetCurrentValue(ScrollViewer.ScrollableWidthProperty, w); lu.invalidateMeasure(); } var h = Math.max(0, this.ExtentHeight - this.ViewportHeight); if (h !== this.ScrollableHeight) { this.SetCurrentValue(ScrollViewer.ScrollableHeightProperty, h); lu.invalidateMeasure(); } } private _UpdateScrollBarVisibility() { var lu = this.XamlNode.LayoutUpdater; var scrollInfo = this.ScrollInfo; var horizontalVisibility = Visibility.Visible; var hsbv = this.HorizontalScrollBarVisibility; switch (hsbv) { case ScrollBarVisibility.Visible: break; case ScrollBarVisibility.Disabled: case ScrollBarVisibility.Hidden: horizontalVisibility = Visibility.Collapsed; break; case ScrollBarVisibility.Auto: default: horizontalVisibility = (!scrollInfo || scrollInfo.ExtentWidth <= scrollInfo.ViewportWidth) ? Visibility.Collapsed : Visibility.Visible; break; } if (horizontalVisibility !== this.ComputedHorizontalScrollBarVisibility) { this.SetCurrentValue(ScrollViewer.ComputedHorizontalScrollBarVisibilityProperty, horizontalVisibility); lu.invalidateMeasure(); } var verticalVisibility = Fayde.Visibility.Visible; var vsbv = this.VerticalScrollBarVisibility; switch (vsbv) { case ScrollBarVisibility.Visible: break; case ScrollBarVisibility.Disabled: case ScrollBarVisibility.Hidden: verticalVisibility = Fayde.Visibility.Collapsed; break; case ScrollBarVisibility.Auto: default: verticalVisibility = (!scrollInfo || scrollInfo.ExtentHeight <= scrollInfo.ViewportHeight) ? Fayde.Visibility.Collapsed : Fayde.Visibility.Visible; break; } if (verticalVisibility !== this.ComputedVerticalScrollBarVisibility) { this.SetCurrentValue(ScrollViewer.ComputedVerticalScrollBarVisibilityProperty, verticalVisibility); lu.invalidateMeasure(); } } private _UpdateScrollBar (orientation: Orientation, value: number) { var propd: DependencyProperty; var sb: Primitives.ScrollBar; if (orientation === Orientation.Horizontal) { propd = ScrollViewer.HorizontalOffsetProperty; sb = this.$HorizontalScrollBar; } else { propd = ScrollViewer.VerticalOffsetProperty; sb = this.$VerticalScrollBar; } try { this.SetCurrentValue(propd, value); if (sb) sb.SetCurrentValue(Primitives.RangeBase.ValueProperty, value); } finally { } } OnApplyTemplate() { super.OnApplyTemplate(); this.$ScrollContentPresenter = <ScrollContentPresenter>this.GetTemplateChild("ScrollContentPresenter", ScrollContentPresenter); this.$HorizontalScrollBar = <Primitives.ScrollBar>this.GetTemplateChild("HorizontalScrollBar", Primitives.ScrollBar); if (this.$HorizontalScrollBar) { this.$HorizontalScrollBar.Scroll.on((sender, e: Primitives.ScrollEventArgs) => this._HandleScroll(Orientation.Horizontal, e), this); } this.$VerticalScrollBar = <Primitives.ScrollBar>this.GetTemplateChild("VerticalScrollBar", Primitives.ScrollBar); if (this.$VerticalScrollBar) { this.$VerticalScrollBar.Scroll.on((sender, e: Primitives.ScrollEventArgs) => this._HandleScroll(Orientation.Vertical, e), this); } this._UpdateScrollBarVisibility(); } OnMouseLeftButtonDown(e: Input.MouseButtonEventArgs) { if (!e.Handled && this.Focus()) e.Handled = true; super.OnMouseLeftButtonDown(e); } OnMouseWheel(e: Input.MouseWheelEventArgs) { super.OnMouseWheel(e); if (e.Handled) return; var scrollInfo = this.ScrollInfo; if (!scrollInfo) return; if ((e.Delta > 0 && scrollInfo.VerticalOffset !== 0) || (e.Delta < 0 && scrollInfo.VerticalOffset < this.ScrollableHeight)) { if (e.Delta >= 0) scrollInfo.MouseWheelUp(); else scrollInfo.MouseWheelDown(); e.Handled = true; } } private _TouchOrigin: Point; private _Delta = new Point(); private _TouchInitialOffset = new Point(); OnTouchDown(e: Input.TouchEventArgs) { super.OnTouchDown(e); var scrollInfo = this.ScrollInfo; if (e.Handled || !this.IsEnabled || !scrollInfo) return; e.Handled = true; this.Focus(); e.Device.Capture(this); var offset = this._TouchInitialOffset; offset.x = scrollInfo.HorizontalOffset; offset.y = scrollInfo.VerticalOffset; this._TouchOrigin = e.GetTouchPoint(this).Position; } OnTouchUp(e: Input.TouchEventArgs) { super.OnTouchUp(e); if (e.Handled || !this.IsEnabled) return; e.Handled = true; e.Device.ReleaseCapture(this); } OnTouchMove(e: Input.TouchEventArgs) { super.OnTouchMove(e); if (e.Handled || e.Device.Captured !== this) return; var tp = e.GetTouchPoint(this); var pos = tp.Position; var delta = this._Delta; var origin = this._TouchOrigin; delta.x = pos.x - origin.x; delta.y = pos.y - origin.y; this.ScrollToHorizontalOffset(this._TouchInitialOffset.x + delta.x); this.ScrollToVerticalOffset(this._TouchInitialOffset.y + delta.y); } OnKeyDown(e: Input.KeyEventArgs) { super.OnKeyDown(e); if (e.Handled) return; if (this.$TemplatedParentHandlesScrolling) return; var orientation = Orientation.Vertical; var scrollEventType = Primitives.ScrollEventType.ThumbTrack; //TODO: FlowDirection //var flowDirection = this.FlowDirection === Fayde.FlowDirection.RightToLeft; switch (e.Key) { case Input.Key.PageUp: scrollEventType = Primitives.ScrollEventType.LargeDecrement; break; case Input.Key.PageDown: scrollEventType = Primitives.ScrollEventType.LargeIncrement; break; case Input.Key.End: if (!e.Modifiers.Ctrl) orientation = Orientation.Horizontal; scrollEventType = Primitives.ScrollEventType.Last; break; case Input.Key.Home: if (!e.Modifiers.Ctrl) orientation = Orientation.Horizontal; scrollEventType = Primitives.ScrollEventType.First; break; case Input.Key.Left: orientation = Orientation.Horizontal; scrollEventType = Primitives.ScrollEventType.SmallDecrement; case Input.Key.Up: scrollEventType = Primitives.ScrollEventType.SmallDecrement; break; case Input.Key.Right: orientation = Orientation.Horizontal; scrollEventType = Primitives.ScrollEventType.SmallIncrement; case Input.Key.Down: scrollEventType = Primitives.ScrollEventType.SmallIncrement; break; } if (scrollEventType !== Primitives.ScrollEventType.ThumbTrack) e.Handled = !!this._HandleScroll(orientation, new Primitives.ScrollEventArgs(scrollEventType, 0)); } ScrollInDirection(key: Input.Key) { switch (key) { case Input.Key.PageUp: this.PageUp(); break; case Input.Key.PageDown: this.PageDown(); break; case Input.Key.End: this.PageEnd(); break; case Input.Key.Home: this.PageHome(); break; case Input.Key.Left: this.LineLeft(); break; case Input.Key.Up: this.LineUp(); break; case Input.Key.Right: this.LineRight(); break; case Input.Key.Down: this.LineDown(); break; } } ScrollToHorizontalOffset(offset: number) { this._HandleHorizontalScroll(new Primitives.ScrollEventArgs(Primitives.ScrollEventType.ThumbPosition, offset)); } ScrollToVerticalOffset(offset: number) { this._HandleVerticalScroll(new Primitives.ScrollEventArgs(Primitives.ScrollEventType.ThumbPosition, offset)); } LineUp() { this._HandleVerticalScroll(new Primitives.ScrollEventArgs(Primitives.ScrollEventType.SmallDecrement, 0)); } LineDown() { this._HandleVerticalScroll(new Primitives.ScrollEventArgs(Primitives.ScrollEventType.SmallIncrement, 0)); } LineLeft() { this._HandleHorizontalScroll(new Primitives.ScrollEventArgs(Primitives.ScrollEventType.SmallDecrement, 0)); } LineRight() { this._HandleHorizontalScroll(new Primitives.ScrollEventArgs(Primitives.ScrollEventType.SmallIncrement, 0)); } PageHome() { this._HandleHorizontalScroll(new Primitives.ScrollEventArgs(Primitives.ScrollEventType.First, 0)); } PageEnd() { this._HandleHorizontalScroll(new Primitives.ScrollEventArgs(Primitives.ScrollEventType.Last, 0)); } PageUp() { this._HandleVerticalScroll(new Primitives.ScrollEventArgs(Primitives.ScrollEventType.LargeDecrement, 0)); } PageDown() { this._HandleVerticalScroll(new Primitives.ScrollEventArgs(Primitives.ScrollEventType.LargeIncrement, 0)); } PageLeft() { this._HandleHorizontalScroll(new Primitives.ScrollEventArgs(Primitives.ScrollEventType.LargeDecrement, 0)); } PageRight() { this._HandleHorizontalScroll(new Primitives.ScrollEventArgs(Primitives.ScrollEventType.LargeIncrement, 0)); } private _HandleScroll(orientation: Orientation, e: Primitives.ScrollEventArgs): boolean { if (orientation !== Orientation.Horizontal) return this._HandleVerticalScroll(e); return this._HandleHorizontalScroll(e); } private _HandleHorizontalScroll(e: Primitives.ScrollEventArgs): boolean { var scrollInfo = this.ScrollInfo; if (!scrollInfo) return false; var offset = scrollInfo.HorizontalOffset; var newValue = offset; switch (e.ScrollEventType) { case Primitives.ScrollEventType.SmallDecrement: return scrollInfo.LineLeft(); case Primitives.ScrollEventType.SmallIncrement: return scrollInfo.LineRight(); case Primitives.ScrollEventType.LargeDecrement: return scrollInfo.PageLeft(); case Primitives.ScrollEventType.LargeIncrement: return scrollInfo.PageRight(); case Primitives.ScrollEventType.ThumbPosition: case Primitives.ScrollEventType.ThumbTrack: newValue = e.Value; break; case Primitives.ScrollEventType.First: newValue = Number.NEGATIVE_INFINITY; break; case Primitives.ScrollEventType.Last: newValue = Number.POSITIVE_INFINITY; break; } newValue = Math.max(newValue, 0); newValue = Math.min(this.ScrollableWidth, newValue); if (NumberEx.AreClose(offset, newValue)) return false; scrollInfo.SetHorizontalOffset(newValue); return true; } private _HandleVerticalScroll(e: Primitives.ScrollEventArgs): boolean { var scrollInfo = this.ScrollInfo; if (!scrollInfo) return false; var offset = scrollInfo.VerticalOffset; var newValue = offset; switch (e.ScrollEventType) { case Primitives.ScrollEventType.SmallDecrement: return scrollInfo.LineUp(); case Primitives.ScrollEventType.SmallIncrement: return scrollInfo.LineDown(); break; case Primitives.ScrollEventType.LargeDecrement: return scrollInfo.PageUp(); break; case Primitives.ScrollEventType.LargeIncrement: return scrollInfo.PageDown(); break; case Primitives.ScrollEventType.ThumbPosition: case Primitives.ScrollEventType.ThumbTrack: newValue = e.Value; break; case Primitives.ScrollEventType.First: newValue = Number.NEGATIVE_INFINITY; break; case Primitives.ScrollEventType.Last: newValue = Number.POSITIVE_INFINITY; break; } newValue = Math.max(newValue, 0); newValue = Math.min(this.ScrollableHeight, newValue); if (NumberEx.AreClose(offset, newValue)) return false; return scrollInfo.SetVerticalOffset(newValue); } } Fayde.CoreLibrary.add(ScrollViewer); TemplateParts(ScrollViewer, { Name: "ScrollContentPresenter", Type: ScrollContentPresenter }, { Name: "HorizontalScrollBar", Type: Primitives.ScrollBar }, { Name: "VerticalScrollBar", Type: Primitives.ScrollBar }); }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement, Operator } from "../shared"; /** * Statement provider for service [quicksight](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonquicksight.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Quicksight extends PolicyStatement { public servicePrefix = 'quicksight'; /** * Statement provider for service [quicksight](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonquicksight.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 cancel a SPICE ingestions on a dataset * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_CancelIngestion.html */ public toCancelIngestion() { return this.to('CancelIngestion'); } /** * Grants permission to create an account customization for QuickSight account or namespace * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_CreateAccountCustomization.html */ public toCreateAccountCustomization() { return this.to('CreateAccountCustomization'); } /** * Grants permission to provision Amazon QuickSight administrators, authors, and readers * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/quicksight/latest/user/iam-actions.html */ public toCreateAdmin() { return this.to('CreateAdmin'); } /** * Grants permission to create an analysis from a template * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_CreateAnalysis.html */ public toCreateAnalysis() { return this.to('CreateAnalysis'); } /** * Grants permission to create a custom permissions resource for restricting user access * * Access Level: Permissions management * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/user/iam-actions.html */ public toCreateCustomPermissions() { return this.to('CreateCustomPermissions'); } /** * Grants permission to create a QuickSight Dashboard * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_CreateDashboard.html */ public toCreateDashboard() { return this.to('CreateDashboard'); } /** * Grants permission to create a dataset * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * Dependent actions: * - quicksight:PassDataSource * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_CreateDataSet.html */ public toCreateDataSet() { return this.to('CreateDataSet'); } /** * Grants permission to create a data source * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_CreateDataSource.html */ public toCreateDataSource() { return this.to('CreateDataSource'); } /** * Grants permission to create a QuickSight folder * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_CreateFolder.html */ public toCreateFolder() { return this.to('CreateFolder'); } /** * Grants permission to add a QuickSight Dashboard, Analysis or Dataset to a QuickSight Folder * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_CreateFolderMembership.html */ public toCreateFolderMembership() { return this.to('CreateFolderMembership'); } /** * Grants permission to create a QuickSight group * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_CreateGroup.html */ public toCreateGroup() { return this.to('CreateGroup'); } /** * Grants permission to add a QuickSight user to a QuickSight group * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_CreateGroupMembership.html */ public toCreateGroupMembership() { return this.to('CreateGroupMembership'); } /** * Grants permission to create an assignment with one specified IAM Policy ARN that will be assigned to specified groups or users of QuickSight * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_CreateIAMPolicyAssignment.html */ public toCreateIAMPolicyAssignment() { return this.to('CreateIAMPolicyAssignment'); } /** * Grants permission to start a SPICE ingestion on a dataset * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_CreateIngestion.html */ public toCreateIngestion() { return this.to('CreateIngestion'); } /** * Grants permission to create an QuickSight namespace * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_CreateNamespace.html */ public toCreateNamespace() { return this.to('CreateNamespace'); } /** * Grants permission to provision Amazon QuickSight readers * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/quicksight/latest/user/iam-actions.html */ public toCreateReader() { return this.to('CreateReader'); } /** * Grants permission to create a template * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_CreateTemplate.html */ public toCreateTemplate() { return this.to('CreateTemplate'); } /** * Grants permission to create a template alias * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_CreateTemplateAlias.html */ public toCreateTemplateAlias() { return this.to('CreateTemplateAlias'); } /** * Grant permission to create a theme * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_CreateTheme.html */ public toCreateTheme() { return this.to('CreateTheme'); } /** * Grants permission to create an alias for a theme version * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_CreateThemeAlias.html */ public toCreateThemeAlias() { return this.to('CreateThemeAlias'); } /** * Grants permission to provision Amazon QuickSight authors and readers * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/quicksight/latest/user/iam-actions.html */ public toCreateUser() { return this.to('CreateUser'); } /** * Grants permission to create a VPC connection * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/user/vpc-creating-a-connection-in-quicksight.html */ public toCreateVPCConnection() { return this.to('CreateVPCConnection'); } /** * Grants permission to delete an account customization for QuickSight account or namespace * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DeleteAccountCustomization.html */ public toDeleteAccountCustomization() { return this.to('DeleteAccountCustomization'); } /** * Grants permissions to delete an analysis * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DeleteAnalysis.html */ public toDeleteAnalysis() { return this.to('DeleteAnalysis'); } /** * Grants permission to delete a custom permissions resource * * Access Level: Permissions management * * https://docs.aws.amazon.com/quicksight/latest/user/iam-actions.html */ public toDeleteCustomPermissions() { return this.to('DeleteCustomPermissions'); } /** * Grants permission to delete a QuickSight Dashboard * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DeleteDashboard.html */ public toDeleteDashboard() { return this.to('DeleteDashboard'); } /** * Grants permission to delete a dataset * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DeleteDataSet.html */ public toDeleteDataSet() { return this.to('DeleteDataSet'); } /** * Grants permission to delete a data source * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DeleteDataSource.html */ public toDeleteDataSource() { return this.to('DeleteDataSource'); } /** * Grants permission to delete a QuickSight Folder * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DeleteFolder.html */ public toDeleteFolder() { return this.to('DeleteFolder'); } /** * Grants permission to remove a QuickSight Dashboard, Analysis or Dataset from a QuickSight Folder * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DeleteFolderMembership.html */ public toDeleteFolderMembership() { return this.to('DeleteFolderMembership'); } /** * Grants permission to remove a user group from QuickSight * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DeleteGroup.html */ public toDeleteGroup() { return this.to('DeleteGroup'); } /** * Grants permission to remove a user from a group so that he/she is no longer a member of the group * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DeleteGroupMembership.html */ public toDeleteGroupMembership() { return this.to('DeleteGroupMembership'); } /** * Grants permission to update an existing assignment * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DeleteIAMPolicyAssignment.html */ public toDeleteIAMPolicyAssignment() { return this.to('DeleteIAMPolicyAssignment'); } /** * Grants permission to delete a QuickSight namespace * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DeleteNamespace.html */ public toDeleteNamespace() { return this.to('DeleteNamespace'); } /** * Grants permission to delete a template * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DeleteTemplate.html */ public toDeleteTemplate() { return this.to('DeleteTemplate'); } /** * Grants permission to delete a template alias * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DeleteTemplateAlias.html */ public toDeleteTemplateAlias() { return this.to('DeleteTemplateAlias'); } /** * Grants permission to delete a theme * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DeleteTheme.html */ public toDeleteTheme() { return this.to('DeleteTheme'); } /** * Grants permission to delete the alias of a theme * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DeleteThemeAlias.html */ public toDeleteThemeAlias() { return this.to('DeleteThemeAlias'); } /** * Grants permission to delete a QuickSight user, given the user name * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DeleteUser.html */ public toDeleteUser() { return this.to('DeleteUser'); } /** * Grants permission to deletes a user identified by its principal ID * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DeleteUserByPrincipalId.html */ public toDeleteUserByPrincipalId() { return this.to('DeleteUserByPrincipalId'); } /** * Grants permission to delete a VPC connection * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/user/vpc-creating-a-connection-in-quicksight.html */ public toDeleteVPCConnection() { return this.to('DeleteVPCConnection'); } /** * Grants permission to describe an account customization for QuickSight account or namespace * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeAccountCustomization.html */ public toDescribeAccountCustomization() { return this.to('DescribeAccountCustomization'); } /** * Grants permission to describe the administrative account settings for QuickSight account * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeAccountSettings.html */ public toDescribeAccountSettings() { return this.to('DescribeAccountSettings'); } /** * Grants permission to describe an analysis * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeAnalysis.html */ public toDescribeAnalysis() { return this.to('DescribeAnalysis'); } /** * Grants permission to describe permissions for an analysis * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeAnalysisPermissions.html */ public toDescribeAnalysisPermissions() { return this.to('DescribeAnalysisPermissions'); } /** * Grants permission to describe a custom permissions resource in a QuickSight account * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/user/iam-actions.html */ public toDescribeCustomPermissions() { return this.to('DescribeCustomPermissions'); } /** * Grants permission to describe a QuickSight Dashboard * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeDashboard.html */ public toDescribeDashboard() { return this.to('DescribeDashboard'); } /** * Grants permission to describe permissions for a QuickSight Dashboard * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeDashboardPermissions.html */ public toDescribeDashboardPermissions() { return this.to('DescribeDashboardPermissions'); } /** * Grants permission to describe a dataset * * Access Level: Read * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeDataSet.html */ public toDescribeDataSet() { return this.to('DescribeDataSet'); } /** * Grants permission to describe the resource policy of a dataset * * Access Level: Permissions management * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeDataSetPermissions.html */ public toDescribeDataSetPermissions() { return this.to('DescribeDataSetPermissions'); } /** * Grants permission to describe a data source * * Access Level: Read * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeDataSource.html */ public toDescribeDataSource() { return this.to('DescribeDataSource'); } /** * Grants permission to describe the resource policy of a data source * * Access Level: Permissions management * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeDataSourcePermissions.html */ public toDescribeDataSourcePermissions() { return this.to('DescribeDataSourcePermissions'); } /** * Grants permission to describe a QuickSight Folder * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeFolder.html */ public toDescribeFolder() { return this.to('DescribeFolder'); } /** * Grants permission to describe permissions for a QuickSight Folder * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeFolderPermissions.html */ public toDescribeFolderPermissions() { return this.to('DescribeFolderPermissions'); } /** * Grants permission to describe resolved permissions for a QuickSight Folder * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeFolderResolvedPermissions.html */ public toDescribeFolderResolvedPermissions() { return this.to('DescribeFolderResolvedPermissions'); } /** * Grants permission to describe a QuickSight group * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeGroup.html */ public toDescribeGroup() { return this.to('DescribeGroup'); } /** * Grants permission to describe an existing assignment * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeIAMPolicyAssignment.html */ public toDescribeIAMPolicyAssignment() { return this.to('DescribeIAMPolicyAssignment'); } /** * Grants permission to describe a SPICE ingestion on a dataset * * Access Level: Read * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeIngestion.html */ public toDescribeIngestion() { return this.to('DescribeIngestion'); } /** * Grants permission to describe a QuickSight namespace * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeNamespace.html */ public toDescribeNamespace() { return this.to('DescribeNamespace'); } /** * Grants permission to describe a template * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeTemplate.html */ public toDescribeTemplate() { return this.to('DescribeTemplate'); } /** * Grants permission to describe a template alias * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeTemplateAlias.html */ public toDescribeTemplateAlias() { return this.to('DescribeTemplateAlias'); } /** * Grants permission to describe permissions for a template * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeTemplatePermissions.html */ public toDescribeTemplatePermissions() { return this.to('DescribeTemplatePermissions'); } /** * Grants permission to describe a theme * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeTheme.html */ public toDescribeTheme() { return this.to('DescribeTheme'); } /** * Grants permission to describe a theme alias * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeThemeAlias.html */ public toDescribeThemeAlias() { return this.to('DescribeThemeAlias'); } /** * Grants permission to describe permissions for a theme * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeThemePermissions.html */ public toDescribeThemePermissions() { return this.to('DescribeThemePermissions'); } /** * Grants permission to describe a QuickSight user given the user name * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DescribeUser.html */ public toDescribeUser() { return this.to('DescribeUser'); } /** * Grants permission to generate a URL used to embed a QuickSight Dashboard for a user not registered with QuickSight * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_GenerateEmbedUrlForAnonymousUser.html */ public toGenerateEmbedUrlForAnonymousUser() { return this.to('GenerateEmbedUrlForAnonymousUser'); } /** * Grants permission to generate a URL used to embed a QuickSight Dashboard for a user registered with QuickSight * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_GenerateEmbedUrlForRegisteredUser.html */ public toGenerateEmbedUrlForRegisteredUser() { return this.to('GenerateEmbedUrlForRegisteredUser'); } /** * Grants permission to get a URL used to embed a QuickSight Dashboard for a user not registered with QuickSight * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_GetDashboardEmbedUrl.html */ public toGetAnonymousUserEmbedUrl() { return this.to('GetAnonymousUserEmbedUrl'); } /** * Grants permission to get an auth code representing a QuickSight user * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/user/iam-actions.html */ public toGetAuthCode() { return this.to('GetAuthCode'); } /** * Grants permission to get a URL used to embed a QuickSight Dashboard * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_GetDashboardEmbedUrl.html */ public toGetDashboardEmbedUrl() { return this.to('GetDashboardEmbedUrl'); } /** * Grants permission to use Amazon QuickSight, in Enterprise edition, to identify and display the Microsoft Active Directory (Microsoft Active Directory) directory groups that are mapped to roles in Amazon QuickSight * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/user/iam-actions.html */ public toGetGroupMapping() { return this.to('GetGroupMapping'); } /** * Grants permission to get a URL to embed QuickSight console experience * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_GetSessionEmbedUrl.html */ public toGetSessionEmbedUrl() { return this.to('GetSessionEmbedUrl'); } /** * Grants permission to list all analyses in an account * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListAnalyses.html */ public toListAnalyses() { return this.to('ListAnalyses'); } /** * Grants permission to list custom permissions resources in QuickSight account * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/user/iam-actions.html */ public toListCustomPermissions() { return this.to('ListCustomPermissions'); } /** * Grants permission to list all versions of a QuickSight Dashboard * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListDashboardVersions.html */ public toListDashboardVersions() { return this.to('ListDashboardVersions'); } /** * Grants permission to list all Dashboards in a QuickSight Account * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListDashboards.html */ public toListDashboards() { return this.to('ListDashboards'); } /** * Grants permission to list all datasets * * Access Level: List * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListDataSets.html */ public toListDataSets() { return this.to('ListDataSets'); } /** * Grants permission to list all data sources * * Access Level: List * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListDataSources.html */ public toListDataSources() { return this.to('ListDataSources'); } /** * Grants permission to list all members in a folder * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListFolderMembers.html */ public toListFolderMembers() { return this.to('ListFolderMembers'); } /** * Grants permission to list all Folders in a QuickSight Account * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListFolders.html */ public toListFolders() { return this.to('ListFolders'); } /** * Grants permission to list member users in a group * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListGroupMemberships.html */ public toListGroupMemberships() { return this.to('ListGroupMemberships'); } /** * Grants permission to list all user groups in QuickSight * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListGroups.html */ public toListGroups() { return this.to('ListGroups'); } /** * Grants permission to list all assignments in the current Amazon QuickSight account * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListIAMPolicyAssignments.html */ public toListIAMPolicyAssignments() { return this.to('ListIAMPolicyAssignments'); } /** * Grants permission to list all assignments assigned to a user and the groups it belongs * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListIAMPolicyAssignmentsForUser.html */ public toListIAMPolicyAssignmentsForUser() { return this.to('ListIAMPolicyAssignmentsForUser'); } /** * Grants permission to list all SPICE ingestions on a dataset * * Access Level: List * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListIngestions.html */ public toListIngestions() { return this.to('ListIngestions'); } /** * Grants permission to lists all namespaces in a QuickSight account * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListNamespaces.html */ public toListNamespaces() { return this.to('ListNamespaces'); } /** * Grants permission to list tags of a QuickSight resource * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to list all aliases for a template * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListTemplateAliases.html */ public toListTemplateAliases() { return this.to('ListTemplateAliases'); } /** * Grants permission to list all versions of a template * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListTemplateVersions.html */ public toListTemplateVersions() { return this.to('ListTemplateVersions'); } /** * Grants permission to list all templates in a QuickSight account * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListTemplates.html */ public toListTemplates() { return this.to('ListTemplates'); } /** * Grants permission to list all aliases of a theme * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListThemeAliases.html */ public toListThemeAliases() { return this.to('ListThemeAliases'); } /** * Grants permission to list all versions of a theme * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListThemeVersions.html */ public toListThemeVersions() { return this.to('ListThemeVersions'); } /** * Grants permission to list all themes in an account * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListThemes.html */ public toListThemes() { return this.to('ListThemes'); } /** * Grants permission to list groups that a given user is a member of * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListUserGroups.html */ public toListUserGroups() { return this.to('ListUserGroups'); } /** * Grants permission to list all of the QuickSight users belonging to this account * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ListUsers.html */ public toListUsers() { return this.to('ListUsers'); } /** * Grants permission to use a dataset for a template * * Access Level: Read * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/qs-api-overview.html */ public toPassDataSet() { return this.to('PassDataSet'); } /** * Grants permission to use a data source for a data set * * Access Level: Read * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/qs-api-overview.html */ public toPassDataSource() { return this.to('PassDataSource'); } /** * Grants permission to create a QuickSight user, whose identity is associated with the IAM identity/role specified in the request * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_RegisterUser.html */ public toRegisterUser() { return this.to('RegisterUser'); } /** * Grants permission to restore a deleted analysis * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_RestoreAnalysis.html */ public toRestoreAnalysis() { return this.to('RestoreAnalysis'); } /** * Grants permission to search for a sub-set of analyses * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_SearchAnalyses.html */ public toSearchAnalyses() { return this.to('SearchAnalyses'); } /** * Grants permission to search for a sub-set of QuickSight Dashboards * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_SearchDashboards.html */ public toSearchDashboards() { return this.to('SearchDashboards'); } /** * Grants permission to use Amazon QuickSight, in Enterprise edition, to display your Microsoft Active Directory directory groups so that you can choose which ones to map to roles in Amazon QuickSight * * Access Level: List * * https://docs.aws.amazon.com/quicksight/latest/user/iam-actions.html */ public toSearchDirectoryGroups() { return this.to('SearchDirectoryGroups'); } /** * Grants permission to search for a sub-set of QuickSight Folders * * Access Level: Read * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_SearchFolders.html */ public toSearchFolders() { return this.to('SearchFolders'); } /** * Grants permission to use Amazon QuickSight, in Enterprise edition, to display your Microsoft Active Directory directory groups so that you can choose which ones to map to roles in Amazon QuickSight * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/user/iam-actions.html */ public toSetGroupMapping() { return this.to('SetGroupMapping'); } /** * Grants permission to subscribe to Amazon QuickSight, and also to allow the user to upgrade the subscription to Enterprise edition * * Access Level: Write * * Possible conditions: * - .ifEdition() * - .ifDirectoryType() * * https://docs.aws.amazon.com/quicksight/latest/user/iam-actions.html */ public toSubscribe() { return this.to('Subscribe'); } /** * Grants permission to add tags to a QuickSight resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to unsubscribe from Amazon QuickSight, which permanently deletes all users and their resources from Amazon QuickSight * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/user/iam-actions.html */ public toUnsubscribe() { return this.to('Unsubscribe'); } /** * Grants permission to remove tags from a QuickSight resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update an account customization for QuickSight account or namespace * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateAccountCustomization.html */ public toUpdateAccountCustomization() { return this.to('UpdateAccountCustomization'); } /** * Grants permission to update the administrative account settings for QuickSight account * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateAccountSettings.html */ public toUpdateAccountSettings() { return this.to('UpdateAccountSettings'); } /** * Grants permission to update an analysis * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateAnalysis.html */ public toUpdateAnalysis() { return this.to('UpdateAnalysis'); } /** * Grants permission to update permissions for an analysis * * Access Level: Permissions management * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateAnalysisPermissions.html */ public toUpdateAnalysisPermissions() { return this.to('UpdateAnalysisPermissions'); } /** * Grants permission to update a custom permissions resource * * Access Level: Permissions management * * https://docs.aws.amazon.com/quicksight/latest/user/iam-actions.html */ public toUpdateCustomPermissions() { return this.to('UpdateCustomPermissions'); } /** * Grants permission to update a QuickSight Dashboard * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateDashboard.html */ public toUpdateDashboard() { return this.to('UpdateDashboard'); } /** * Grants permission to update permissions for a QuickSight Dashboard * * Access Level: Permissions management * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateDashboardPermissions.html */ public toUpdateDashboardPermissions() { return this.to('UpdateDashboardPermissions'); } /** * Grants permission to update a QuickSight Dashboard’s Published Version * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateDashboardPublishedVersion.html */ public toUpdateDashboardPublishedVersion() { return this.to('UpdateDashboardPublishedVersion'); } /** * Grants permission to update a dataset * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * Dependent actions: * - quicksight:PassDataSource * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateDataSet.html */ public toUpdateDataSet() { return this.to('UpdateDataSet'); } /** * Grants permission to update the resource policy of a dataset * * Access Level: Permissions management * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateDataSetPermissions.html */ public toUpdateDataSetPermissions() { return this.to('UpdateDataSetPermissions'); } /** * Grants permission to update a data source * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateDataSource.html */ public toUpdateDataSource() { return this.to('UpdateDataSource'); } /** * Grants permission to update the resource policy of a data source * * Access Level: Permissions management * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateDataSourcePermissions.html */ public toUpdateDataSourcePermissions() { return this.to('UpdateDataSourcePermissions'); } /** * Grants permission to update a QuickSight Folder * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateFolder.html */ public toUpdateFolder() { return this.to('UpdateFolder'); } /** * Grants permission to update permissions for a QuickSight Folder * * Access Level: Permissions management * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateFolderPermissions.html */ public toUpdateFolderPermissions() { return this.to('UpdateFolderPermissions'); } /** * Grants permission to change group description * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateGroup.html */ public toUpdateGroup() { return this.to('UpdateGroup'); } /** * Grants permission to update an existing assignment * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateIAMPolicyAssignment.html */ public toUpdateIAMPolicyAssignment() { return this.to('UpdateIAMPolicyAssignment'); } /** * Grants permission to update a template * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateTemplate.html */ public toUpdateTemplate() { return this.to('UpdateTemplate'); } /** * Grants permission to update a template alias * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateTemplateAlias.html */ public toUpdateTemplateAlias() { return this.to('UpdateTemplateAlias'); } /** * Grants permission to update permissions for a template * * Access Level: Permissions management * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateTemplatePermissions.html */ public toUpdateTemplatePermissions() { return this.to('UpdateTemplatePermissions'); } /** * Grants permission to update a theme * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateTheme.html */ public toUpdateTheme() { return this.to('UpdateTheme'); } /** * Grants permission to update the alias of a theme * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateThemeAlias.html */ public toUpdateThemeAlias() { return this.to('UpdateThemeAlias'); } /** * Grants permission to update permissions for a theme * * Access Level: Permissions management * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateThemePermissions.html */ public toUpdateThemePermissions() { return this.to('UpdateThemePermissions'); } /** * Grants permission to update an Amazon QuickSight user * * Access Level: Write * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateUser.html */ public toUpdateUser() { return this.to('UpdateUser'); } protected accessLevelList: AccessLevelList = { "Write": [ "CancelIngestion", "CreateAccountCustomization", "CreateAdmin", "CreateAnalysis", "CreateDashboard", "CreateDataSet", "CreateDataSource", "CreateFolder", "CreateFolderMembership", "CreateGroup", "CreateGroupMembership", "CreateIAMPolicyAssignment", "CreateIngestion", "CreateNamespace", "CreateReader", "CreateTemplate", "CreateTemplateAlias", "CreateTheme", "CreateThemeAlias", "CreateUser", "CreateVPCConnection", "DeleteAccountCustomization", "DeleteAnalysis", "DeleteDashboard", "DeleteDataSet", "DeleteDataSource", "DeleteFolder", "DeleteFolderMembership", "DeleteGroup", "DeleteGroupMembership", "DeleteIAMPolicyAssignment", "DeleteNamespace", "DeleteTemplate", "DeleteTemplateAlias", "DeleteTheme", "DeleteThemeAlias", "DeleteUser", "DeleteUserByPrincipalId", "DeleteVPCConnection", "DescribeCustomPermissions", "GenerateEmbedUrlForAnonymousUser", "GenerateEmbedUrlForRegisteredUser", "ListCustomPermissions", "RegisterUser", "RestoreAnalysis", "SetGroupMapping", "Subscribe", "Unsubscribe", "UpdateAccountCustomization", "UpdateAccountSettings", "UpdateAnalysis", "UpdateDashboard", "UpdateDashboardPublishedVersion", "UpdateDataSet", "UpdateDataSource", "UpdateFolder", "UpdateGroup", "UpdateIAMPolicyAssignment", "UpdateTemplate", "UpdateTemplateAlias", "UpdateTheme", "UpdateThemeAlias", "UpdateUser" ], "Permissions management": [ "CreateCustomPermissions", "DeleteCustomPermissions", "DescribeDataSetPermissions", "DescribeDataSourcePermissions", "UpdateAnalysisPermissions", "UpdateCustomPermissions", "UpdateDashboardPermissions", "UpdateDataSetPermissions", "UpdateDataSourcePermissions", "UpdateFolderPermissions", "UpdateTemplatePermissions", "UpdateThemePermissions" ], "Read": [ "DescribeAccountCustomization", "DescribeAccountSettings", "DescribeAnalysis", "DescribeAnalysisPermissions", "DescribeDashboard", "DescribeDashboardPermissions", "DescribeDataSet", "DescribeDataSource", "DescribeFolder", "DescribeFolderPermissions", "DescribeFolderResolvedPermissions", "DescribeGroup", "DescribeIAMPolicyAssignment", "DescribeIngestion", "DescribeNamespace", "DescribeTemplate", "DescribeTemplateAlias", "DescribeTemplatePermissions", "DescribeTheme", "DescribeThemeAlias", "DescribeThemePermissions", "DescribeUser", "GetAnonymousUserEmbedUrl", "GetAuthCode", "GetDashboardEmbedUrl", "GetGroupMapping", "GetSessionEmbedUrl", "ListFolderMembers", "ListTagsForResource", "PassDataSet", "PassDataSource", "SearchFolders" ], "List": [ "ListAnalyses", "ListDashboardVersions", "ListDashboards", "ListDataSets", "ListDataSources", "ListFolders", "ListGroupMemberships", "ListGroups", "ListIAMPolicyAssignments", "ListIAMPolicyAssignmentsForUser", "ListIngestions", "ListNamespaces", "ListTemplateAliases", "ListTemplateVersions", "ListTemplates", "ListThemeAliases", "ListThemeVersions", "ListThemes", "ListUserGroups", "ListUsers", "SearchAnalyses", "SearchDashboards", "SearchDirectoryGroups" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type user to the statement * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_User.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 onUser(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:quicksight:${Region}:${Account}:user/${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 group to the statement * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_Group.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 onGroup(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:quicksight:${Region}:${Account}:group/${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 analysis to the statement * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_Analysis.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 onAnalysis(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:quicksight:${Region}:${Account}:analysis/${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 dashboard to the statement * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_Dashboard.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 onDashboard(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:quicksight:${Region}:${Account}:dashboard/${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 template to the statement * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_Template.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 onTemplate(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:quicksight:${Region}:${Account}:template/${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 datasource to the statement * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DataSource.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 onDatasource(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:quicksight:${Region}:${Account}:datasource/${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 dataset to the statement * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_DataSet.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 onDataset(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:quicksight:${Region}:${Account}:dataset/${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 ingestion to the statement * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_Ingestion.html * * @param datasetId - Identifier for the datasetId. * @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 onIngestion(datasetId: string, resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:quicksight:${Region}:${Account}:dataset/${DatasetId}/ingestion/${ResourceId}'; arn = arn.replace('${DatasetId}', datasetId); 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 theme to the statement * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_Theme.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 onTheme(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:quicksight:${Region}:${Account}:theme/${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 assignment to the statement * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_IAMPolicyAssignment.html * * @param resourceId - Identifier for the resourceId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onAssignment(resourceId: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:quicksight::${Account}:assignment/${ResourceId}'; arn = arn.replace('${ResourceId}', resourceId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type customization to the statement * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_AccountCustomization.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 onCustomization(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:quicksight:${Region}:${Account}:customization/${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 namespace to the statement * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_Namespace.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 onNamespace(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:quicksight:${Region}:${Account}:namespace/${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 folder to the statement * * https://docs.aws.amazon.com/quicksight/latest/APIReference/API_Folder.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 onFolder(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:quicksight:${Region}:${Account}:folder/${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); } /** * Filters access based on the user management options * * https://docs.aws.amazon.com/quicksight/latest/user/security-scp.html * * Applies to actions: * - .toSubscribe() * * @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 ifDirectoryType(value: string | string[], operator?: Operator | string) { return this.if(`DirectoryType`, value, operator || 'StringLike'); } /** * Filters access based on the edition of QuickSight * * https://docs.aws.amazon.com/quicksight/latest/user/security-scp.html * * Applies to actions: * - .toSubscribe() * * @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 ifEdition(value: string | string[], operator?: Operator | string) { return this.if(`Edition`, value, operator || 'StringLike'); } /** * Filters access by IAM user or role ARN * * https://docs.aws.amazon.com/quicksight/latest/user/iam-actions.html * * Applies to actions: * - .toRegisterUser() * * @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 ifIamArn(value: string | string[], operator?: Operator | string) { return this.if(`IamArn`, value, operator || 'StringLike'); } /** * Filters access by session name * * https://docs.aws.amazon.com/quicksight/latest/user/iam-actions.html * * Applies to actions: * - .toRegisterUser() * * @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 ifSessionName(value: string | string[], operator?: Operator | string) { return this.if(`SessionName`, value, operator || 'StringLike'); } /** * Filters access by user name * * https://docs.aws.amazon.com/quicksight/latest/user/iam-actions.html * * Applies to actions: * - .toCreateGroupMembership() * - .toDeleteGroupMembership() * * @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 ifUserName(value: string | string[], operator?: Operator | string) { return this.if(`UserName`, value, operator || 'StringLike'); } }
the_stack
import type { JSONSchema4, JSONSchema6, JSONSchema7 } from "json-schema"; interface Map<T> { [key: string]: T; } export interface OpenApiObject { openapi: string; info: InfoObject; servers?: ServerObject[]; paths: PathsObject; components?: ComponentsObject; security?: SecurityRequirementObject[]; tags?: TagObject[]; externalDocs?: ExternalDocumentationObject; } export interface OpenApiObjectWithRef { openapi: string; info: InfoObject; servers?: ServerObject[]; paths: PathsObjectWithRef; components?: ComponentsObjectWithRef; security?: SecurityRequirementObject[]; tags?: TagObject[]; externalDocs?: ExternalDocumentationObject; } export interface InfoObject { title: string; description?: string; termsOfService?: string; contact?: ContactObject; license?: LicenseObject; version: string; } export interface ContactObject { name?: string; url?: string; email?: string; } export interface LicenseObject { name: string; url?: string; } export interface ServerObject { url: string; description?: string; variables?: Map<ServerVariable>; } export interface ServerVariable { enum?: string[]; default: string; description?: string; } export interface ComponentsObject { schemas?: Map<SchemaObject>; responses?: Map<ResponseObject>; parameters?: Map<ParameterObject>; examples?: Map<ExampleObject>; requestBodies?: Map<RequestBodyObject>; headers?: Map<HeaderObject>; securitySchemes?: Map<SecuritySchemeObject>; links?: Map<LinkObject>; callbacks?: Map<CallbackObject>; } export interface ComponentsObjectWithRef { schemas?: Map<SchemaObjectWithRef | ReferenceObject>; responses?: Map<ResponseObjectWithRef | ReferenceObject>; parameters?: Map<ParameterObjectWithRef | ReferenceObject>; examples?: Map<ExampleObject | ReferenceObject>; requestBodies?: Map<RequestBodyObjectWithRef | ReferenceObject>; headers?: Map<HeaderObjectWithRef | ReferenceObject>; securitySchemes?: Map<SecuritySchemeObject | ReferenceObject>; links?: Map<LinkObject | ReferenceObject>; callbacks?: Map<CallbackObjectWithRef | ReferenceObject>; } export type PathsObject = Map<PathItemObject>; export type PathsObjectWithRef = Map<PathItemObjectWithRef>; export interface PathItemObject { $ref?: string; summary?: string; description?: string; get?: OperationObject; put?: OperationObject; post?: OperationObject; delete?: OperationObject; options?: OperationObject; head?: OperationObject; patch?: OperationObject; trace?: OperationObject; servers?: ServerObject[]; parameters?: ParameterObject[]; } export interface PathItemObjectWithRef { $ref?: string; summary?: string; description?: string; get?: OperationObjectWithRef; put?: OperationObjectWithRef; post?: OperationObjectWithRef; delete?: OperationObjectWithRef; options?: OperationObjectWithRef; head?: OperationObjectWithRef; patch?: OperationObjectWithRef; trace?: OperationObjectWithRef; servers?: ServerObject[]; parameters?: (ParameterObjectWithRef | ReferenceObject)[]; } export interface OperationObject { tags?: string[]; summary?: string; description?: string; externalDocs?: ExternalDocumentationObject; operationId?: string; parameters?: ParameterObject[]; requestBody?: RequestBodyObject; responses: ResponsesObject; callbacks?: Map<CallbackObject>; deprecated?: boolean; security?: SecurityRequirementObject[]; servers?: ServerObject[]; // extensions "x-deprecated-description"?: string; } export interface OperationObjectWithRef { tags?: string[]; summary?: string; description?: string; externalDocs?: ExternalDocumentationObject; operationId?: string; parameters?: (ParameterObjectWithRef | ReferenceObject)[]; requestBody?: RequestBodyObjectWithRef | ReferenceObject; responses: ResponsesObjectWithRef; callbacks?: Map<CallbackObjectWithRef | ReferenceObject>; deprecated?: boolean; security?: SecurityRequirementObject[]; servers?: ServerObject[]; // extensions "x-deprecated-description"?: string; } export interface ExternalDocumentationObject { description?: string; url: string; } export interface ParameterObject { name: string; in: string; description?: string; required?: boolean; deprecated?: boolean; allowEmptyValue?: boolean; // style?: string; explode?: string; allowReserved?: boolean; schema?: SchemaObject; example?: any; examples?: Map<ExampleObject>; // content?: Map<MediaTypeObject>; // ignoring stylings: matrix, label, form, simple, spaceDelimited, // pipeDelimited and deepObject } export interface ParameterObjectWithRef { name: string; in: string; description?: string; required?: boolean; deprecated?: boolean; allowEmptyValue?: boolean; // style?: string; explode?: string; allowReserved?: boolean; schema?: SchemaObjectWithRef | ReferenceObject; example?: any; examples?: Map<ExampleObject | ReferenceObject>; // content?: Map<MediaTypeObjectWithRef>; // ignoring stylings: matrix, label, form, simple, spaceDelimited, // pipeDelimited and deepObject } export interface RequestBodyObject { description?: string; content: Map<MediaTypeObject>; required?: boolean; } export interface RequestBodyObjectWithRef { description?: string; content: Map<MediaTypeObjectWithRef>; required?: boolean; } export interface MediaTypeObject { schema?: SchemaObject; example?: any; examples?: Map<ExampleObject>; encoding?: Map<EncodingObject>; } export interface MediaTypeObjectWithRef { schema?: SchemaObjectWithRef | ReferenceObject; example?: any; examples?: Map<ExampleObject | ReferenceObject>; encoding?: Map<EncodingObjectWithRef>; } export interface EncodingObject { contentType?: string; headers?: Map<HeaderObject>; style?: string; explode?: boolean; allowReserved?: boolean; } export interface EncodingObjectWithRef { contentType?: string; headers?: Map<HeaderObjectWithRef | ReferenceObject>; style?: string; explode?: boolean; allowReserved?: boolean; } export type ResponsesObject = Map<ResponseObject>; export type ResponsesObjectWithRef = Map< ResponseObjectWithRef | ReferenceObject >; export interface ResponseObject { description: string; headers?: Map<HeaderObject>; content?: Map<MediaTypeObject>; links?: Map<LinkObject>; } export interface ResponseObjectWithRef { description: string; headers?: Map<HeaderObjectWithRef | ReferenceObject>; content?: Map<MediaTypeObjectWithRef>; links?: Map<LinkObject | ReferenceObject>; } export type CallbackObject = Map<PathItemObject>; export type CallbackObjectWithRef = Map<PathItemObjectWithRef>; export interface ExampleObject { summary?: string; description?: string; value?: any; externalValue?: string; } export interface LinkObject { operationRef?: string; operationId?: string; parameters?: Map<any>; requestBody?: any; description?: string; server?: ServerObject; } export type HeaderObject = Omit<ParameterObject, "name" | "in">; export type HeaderObjectWithRef = Omit<ParameterObjectWithRef, "name" | "in">; export interface TagObject { name: string; description?: string; externalDocs?: ExternalDocumentationObject; } export interface ReferenceObject { $ref: string; } export type JSONSchema = JSONSchema4 | JSONSchema6 | JSONSchema7; export type SchemaObject = Omit< JSONSchema, | "type" | "allOf" | "oneOf" | "anyOf" | "not" | "items" | "properties" | "additionalProperties" > & { // OpenAPI specific overrides type?: "string" | "number" | "integer" | "boolean" | "object" | "array"; allOf?: SchemaObject[]; oneOf?: SchemaObject[]; anyOf?: SchemaObject[]; not?: SchemaObject; items?: SchemaObject; properties?: Map<SchemaObject>; additionalProperties?: boolean | SchemaObject; // OpenAPI additions nullable?: boolean; discriminator?: DiscriminatorObject; readOnly?: boolean; writeOnly?: boolean; xml?: XMLObject; externalDocs?: ExternalDocumentationObject; example?: any; deprecated?: boolean; }; export type SchemaObjectWithRef = Omit< JSONSchema, | "type" | "allOf" | "oneOf" | "anyOf" | "not" | "items" | "properties" | "additionalProperties" > & { // OpenAPI specific overrides type?: "string" | "number" | "integer" | "boolean" | "object" | "array"; allOf?: (SchemaObject | ReferenceObject)[]; oneOf?: (SchemaObject | ReferenceObject)[]; anyOf?: (SchemaObject | ReferenceObject)[]; not?: SchemaObject | ReferenceObject; items?: SchemaObject | ReferenceObject; properties?: Map<SchemaObject | ReferenceObject>; additionalProperties?: boolean | SchemaObject | ReferenceObject; // OpenAPI additions nullable?: boolean; discriminator?: DiscriminatorObject; readOnly?: boolean; writeOnly?: boolean; xml?: XMLObject; externalDocs?: ExternalDocumentationObject; example?: any; deprecated?: boolean; }; export interface DiscriminatorObject { propertyName: string; mapping?: Map<string>; } export interface XMLObject { name?: string; namespace?: string; prefix?: string; attribute?: boolean; wrapped?: boolean; } export type SecuritySchemeObject = | ApiKeySecuritySchemeObject | HttpSecuritySchemeObject | Oauth2SecuritySchemeObject | OpenIdConnectSecuritySchemeObject; export interface ApiKeySecuritySchemeObject { type: "apiKey"; description?: string; name: string; in: "query" | "header" | "cookie"; } export interface HttpSecuritySchemeObject { type: "http"; description?: string; scheme: string; bearerFormat?: string; } export interface Oauth2SecuritySchemeObject { type: "oauth2"; description?: string; flows: OAuthFlowsObject; } export interface OpenIdConnectSecuritySchemeObject { type: "openIdConnect"; description?: string; openIdConnectUrl: string; } export interface OAuthFlowsObject { implicit?: OAuthFlowObject; password?: OAuthFlowObject; clientCredentials?: OAuthFlowObject; authorizationCode?: OAuthFlowObject; } export interface OAuthFlowObject { authorizationUrl?: string; // required for some tokenUrl?: string; // required for some refreshUrl?: string; scopes: Map<string>; } export type SecurityRequirementObject = Map<string[]>;
the_stack
import Victor from 'victor'; import entityData from './defaultentities'; import Blueprint from './index'; type PositionGrid = { [location: string]: Entity }; type Side = 1 | 2 | 'in' | 'out'; type Color = 'red' | 'green'; type Priority = 'left' | 'right'; type DirectionType = 'input' | 'output'; interface Connection { entity: Entity; color: Color; side: Side; id?: string; } interface CombinatorData { left?: string; right?: string; operator?: string; out?: string; controlEnable?: boolean; readContents?: boolean; readMode?: string; countFromInput?: boolean; } interface Constant { name: string; count: number; } interface AlertParameters { showAlert?: boolean; showOnMap?: boolean; icon?: string | { type: string; name: string }; message?: string; } export default class Entity { id: number; bp: Blueprint; name: string; position: Victor; direction: number; rawConnections: any; connections: Connection[]; rawNeighbours?: number[]; neighbours: Entity[]; circuitParameters: any; condition: CombinatorData; constants?: { [position: number]: Constant }; constantEnabled: boolean; parameters: any; alertParameters: AlertParameters; filters: { [position: number]: string }; requestFilters: { [position: number]: Constant }; directionType: DirectionType; recipe?: string; bar: number; modules: any; splitterFilter?: string; inputPriority: Priority | undefined; outputPriority: Priority | undefined; size: Victor; HAS_DIRECTION_TYPE: boolean; CAN_HAVE_RECIPE: boolean; CAN_HAVE_MODULES: number; INVENTORY_SIZE: number; constructor(data: any, bp: Blueprint, center: boolean) { if (!entityData[bp.checkName(data.name)]) entityData[bp.checkName(data.name)] = {}; let myData = entityData[bp.checkName(data.name)]; // entityData contains info like width, height, filterAmount, etc this.id = -1; // Id used when generating blueprint this.bp = bp; // Blueprint this.name = this.bp.checkName(data.name); // Name or "type" this.position = Victor.fromObject(data.position); // Position of top left corner this.direction = 0; // Direction (usually 0, 2, 4, or 6) this.rawConnections = data.connections; // Used in parsing connections from existing entity this.connections = []; // Wire connections this.rawNeighbours = data.neighbors; this.neighbours = []; this.circuitParameters = data.circuit_parameters || null; this.condition = this.parseCondition(data); // Condition in combinator this.constants = this.parseConstants(data); this.constantEnabled = data.control_behavior && data.control_behavior.is_on !== undefined ? data.control_behavior.is_on : true; // Is constant combinator on/off this.parameters = data.paramaters || (myData.parameters ? {} : null); this.alertParameters = data.alert_parameters || (myData.alertParameters ? {} : null); this.filters = {}; // Filters for container this.requestFilters = {}; // Request filters for requester chest this.directionType = data.type || 'input'; // Underground belts input/output this.recipe = data.recipe ? this.bp.checkName(data.recipe) : undefined; this.bar = data.bar || -1; this.modules = data.items ? Object.keys(data.items).reduce( (obj: { [module: string]: number }, key) => { obj[this.bp.checkName(key)] = data.items[key]; return obj; }, {}, ) : {}; this.splitterFilter = data.filter ? this.bp.checkName(data.filter) : undefined; this.inputPriority = data.input_priority || undefined; this.outputPriority = data.output_priority || undefined; this.size = myData ? new Victor(myData.width || 0, myData.height || 0) // Size in Victor form : entityData[this.name] ? new Victor( entityData[this.name].width || 0, entityData[this.name].height || 0, ) : new Victor(1, 1); this.HAS_DIRECTION_TYPE = myData.directionType || false; this.CAN_HAVE_RECIPE = myData.recipe || false; this.CAN_HAVE_MODULES = myData.modules || 0; this.INVENTORY_SIZE = myData.inventorySize || 0; this.setDirection(data.direction || 0); this.parseFilters(data.filters); this.parseRequestFilters(data.request_filters); if (center) { this.position .add(new Victor(0.5, 0.5)) .subtract(this.size.clone().divide(new Victor(2, 2))); } this.position = new Victor( Math.round(this.position.x * 100) / 100, Math.round(this.position.y * 100) / 100, ); } // Beautiful string format /*toString() { let str = this.id+') '+this.name + ' =>\n'; str += ' position: '+this.position+'\n'; str += ' direction: '+this.direction+'\n'; str += ' connections: '; if (!this.connections.length) str += 'none\n'; else { str += '\n'; const two = this.name == 'arithmetic_combinator' || this.name == 'decider_combinator'; for (let i = 1; i <= (two ? 2 : 1); i++) { const side = two && i == 2 ? 'out' : 'in' const conns = this.connections.filter(c => c.side == i); if (conns.length) { if (two) str += ' '+side+':\n'; for (let j = 0; j < 2; j++) { const color = j == 0 ? 'red' : 'green'; const exactConns = conns.filter(c => c.color == color); if (exactConns.length) str += ' '+color+': '+exactConns.map(c => c.entity.id).join(',')+'\n'; } } } } if (this.condition) { str += ' condition:\n'; str += ' expr: '+this.condition.left+' '+this.condition.operator+' '+this.condition.right+'\n'; str += this.condition.countFromInput != undefined ? ' countFromInput: '+(this.condition.countFromInput || false)+'\n' : ''; str += this.condition.out != undefined ? ' out: '+this.condition.out+'\n' : ''; } return str; }*/ ///////////////////////////////////// ///// Parsing from existing blueprint ///////////////////////////////////// // Parse connections into standard Entity format parseConnections(entityList: any) { const conns = this.rawConnections; if (conns) { for (let side in conns) { if (side != '1' && side != '2') return; // Not a number! for (let color in conns[side]) { for (let i = 0; i < conns[side][color].length; i++) { const id = conns[side][color][i]['entity_id']; const connection: Connection = { entity: entityList[id - 1], color: color == 'red' ? 'red' : 'green', // Garbage to make typescript shut up side: parseInt(side) == 1 ? 1 : 2, id: conns[side][color][i]['circuit_id'], }; this.connections.push(connection); } } } } if (this.rawNeighbours) { this.neighbours = this.rawNeighbours.map(id => entityList[id - 1]); } } // Parse filters into standard Entity format parseFilters(filters: any) { // Parse filters from json (for constructor) if (!filters) return []; for (let i = 0; i < filters.length; i++) { const name = this.bp.checkName(filters[i].name); const final_position = filters[i].index - 1; const final_name = name; this.setFilter(final_position, final_name); } } // Parse request filters into standard Entity format parseRequestFilters(request_filters: any) { // Parse request_filters from json (for constructor) if (!request_filters) return []; for (let i = 0; i < request_filters.length; i++) { request_filters[i].name = this.bp.checkName(request_filters[i].name); this.setRequestFilter( request_filters[i].index - 1, request_filters[i].name, request_filters[i].count, ); } } // Parse condition into standard Entity format parseCondition(data: any) { const controlBehavior = data.control_behavior; const condition = (controlBehavior && (controlBehavior.decider_conditions || controlBehavior.arithmetic_conditions || controlBehavior.circuit_condition)) || {}; if (!controlBehavior) return {}; if (condition.first_signal) condition.first_signal.name = this.bp.checkName( condition.first_signal.name, ); if (condition.second_signal) condition.second_signal.name = this.bp.checkName( condition.second_signal.name, ); if (condition.output_signal) condition.output_signal.name = this.bp.checkName( condition.output_signal.name, ); const out: CombinatorData = { left: condition.first_signal ? condition.first_signal.name : undefined, right: condition.second_signal ? condition.second_signal.name : condition.constant ? parseInt(condition.constant) : undefined, out: condition.output_signal ? condition.output_signal.name : undefined, operator: undefined, controlEnable: controlBehavior.circuit_enable_disable, // circuit_enable_disable, true/false readContents: controlBehavior.circuit_read_hand_contents, // circuit_read_hand_contents, true/false readMode: controlBehavior.circuit_contents_read_mode != undefined ? condition.circuit_contents_read_mode == 0 ? 'pulse' : 'hold' : undefined, countFromInput: undefined, }; [ condition.first_signal, condition.second_signal, condition.output_signal, ].forEach(signal => { if (signal && !entityData[signal.name]) entityData[signal.name] = { type: signal.type }; }); if (this.name == 'decider_combinator') { out.countFromInput = condition.copy_count_from_input == 'true'; } if (condition.comparator) // Set operator out.operator = condition.comparator == ':' ? '=' : condition.comparator; else out.operator = condition.operation; return out; } // Parse constants if this is a constant combinator parseConstants(data: any) { if (this.name != 'constant_combinator') return undefined; else if (!data.control_behavior || !data.control_behavior.filters) return {}; const constants: { [position: number]: { name: string; count: number }; } = {}; data.control_behavior.filters.forEach((filter: any) => { if (!entityData[this.bp.checkName(filter.signal.name)]) { entityData[this.bp.checkName(filter.signal.name)] = { type: filter.signal.type }; } constants[parseInt(filter.index) - 1] = { name: this.bp.checkName(filter.signal.name), count: filter.count || 0, }; }); return constants; } //////////////// //////////////// //////////////// // Sets values in BP (tile data, parses connections). // Typically, when loading from an existing blueprint, all entities are creating at the same time, // and then all are placed at the same time (so each entity can parse the connections of the others) place(positionGrid: PositionGrid, entityList: any[]) { this.setTileData(positionGrid); this.parseConnections(entityList); return this; } // Remove entity from blueprint remove() { return this.bp.removeEntity(this); } // Cleans up tile data after removing removeCleanup(positionGrid: PositionGrid) { this.removeTileData(positionGrid); return this; } // Quick corner/center positions topLeft() { return this.position.clone(); } topRight() { return this.position .clone() .add(this.size.clone().multiply(new Victor(1, 0))); } bottomRight() { return this.position.clone().add(this.size); } bottomLeft() { return this.position .clone() .add(this.size.clone().multiply(new Victor(0, 1))); } center() { return this.position .clone() .add(this.size.clone().divide(new Victor(2, 2))); } // Adds self to grid array setTileData(positionGrid: PositionGrid) { this.tileDataAction( positionGrid, (x, y) => (positionGrid[x + ',' + y] = this), ); return this; } // Removes self from grid array removeTileData(positionGrid: PositionGrid) { this.tileDataAction( positionGrid, (x, y) => delete positionGrid[x + ',' + y], ); return this; } // Return true if this entity overlaps with no other checkNoOverlap(positionGrid: PositionGrid) { const ent = this.getOverlap(positionGrid); if (!ent) return true; if ( (this.name == 'gate' && ent.name == 'straight_rail') || (ent.name == 'gate' && this.name == 'straight_rail') ) return true; return false; } // Returns an item this entity overlaps with (or null) getOverlap(positionGrid: PositionGrid): Entity | null { let item: Entity | null = null; this.tileDataAction(positionGrid, (x, y) => { item = positionGrid[x + ',' + y] || item; }); return item; } // Do an action on every tile that this entity overlaps in a given positionGrid tileDataAction( positionGrid: PositionGrid, fn: (x: number, y: number) => void, ) { if (!positionGrid) return; const topLeft = this.topLeft(); const bottomRight = this.bottomRight().subtract(new Victor(0.9, 0.9)); for (let x = Math.floor(topLeft.x); x < bottomRight.x; x++) { for (let y = Math.floor(topLeft.y); y < bottomRight.y; y++) { fn(x, y); } } } // Connect current entity to another entity via wire connect( ent: Entity, mySide: Side = 1, theirSide: Side = 1, color: Color = 'red', ) { mySide = convertSide(mySide, this); theirSide = convertSide(theirSide, ent); const checkCombinator = (name: string) => { return name == 'decider_combinator' || name == 'arithmetic_combinator'; }; color = color == 'green' ? color : 'red'; this.connections.push({ entity: ent, color: color, side: mySide, id: checkCombinator(ent.name) ? theirSide.toString() : undefined, }); ent.connections.push({ entity: this, color: color, side: theirSide, id: checkCombinator(this.name) ? mySide.toString() : undefined, }); return this; } // Remove a specific wire connection given all details removeConnection( ent: Entity, mySide: Side = 1, theirSide: Side = 1, color: Color = 'red', ) { mySide = convertSide(mySide, this); theirSide = convertSide(theirSide, ent); color = color || 'red'; for (let i = 0; i < this.connections.length; i++) { if ( this.connections[i].entity == ent && this.connections[i].side == mySide && this.connections[i].color == color ) { this.connections.splice(i, 1); break; } } for (let i = 0; i < ent.connections.length; i++) { if ( ent.connections[i].entity == this && ent.connections[i].side == theirSide && ent.connections[i].color == color ) { ent.connections.splice(i, 1); break; } } return this; } // Remove all wire connections with entity (optionally of a specific color) removeConnectionsWithEntity(ent: Entity, color: Color) { for (let i = this.connections.length - 1; i >= 0; i--) { if ( this.connections[i].entity == ent && (!color || this.connections[i].color == color) ) this.connections.splice(i, 1); } for (let i = ent.connections.length - 1; i >= 0; i--) { if ( ent.connections[i].entity == this && (!color || ent.connections[i].color == color) ) ent.connections.splice(i, 1); } return this; } // Remove all wire connections removeAllConnections() { for (let i = 0; i < this.connections.length; i++) { let ent = this.connections[i].entity; for (let j = 0; j < ent.connections.length; j++) { if (ent.connections[j].entity == this) { ent.connections.splice(j, 1); break; } } } this.connections = []; return this; } setFilter(pos: number, name: string) { if (pos < 0) throw new Error('Filter index cannot be less than 0!'); name = this.bp.checkName(name); if (name == null) delete this.filters[pos]; else this.filters[pos] = name; return this; } setRequestFilter(pos: number, name: string, count: number) { if (pos < 0) throw new Error('Filter index cannot be less than 0!'); name = this.bp.checkName(name); if (name == null) delete this.requestFilters[pos]; else this.requestFilters[pos] = { name, count, }; return this; } removeAllFilters() { this.filters = {}; return this; } removeAllRequestFilters() { this.requestFilters = {}; return this; } // Sets condition of entity (for combinators) setCondition(opt: CombinatorData) { if (opt.countFromInput != undefined && this.name != 'decider_combinator') throw new Error('Cannot set countFromInput for ' + this.name); else if (opt.readMode && opt.readMode != 'pulse' && opt.readMode != 'hold') throw new Error('readMode in a condition must be "pulse" or "hold"!'); else if ( this.name == 'arithmetic_combinator' && (opt.left == 'signal_everything' || opt.out == 'signal_everything' || opt.left == 'signal_anything' || opt.out == 'signal_anything') ) throw new Error( 'Only comparitive conditions can contain signal_everything or signal_anything. Instead use signal_each', ); else if (opt.out == 'signal_each' && opt.left != 'signal_each') throw new Error( 'Left condition must be signal_each for output to be signal_each.' + (this.name != 'arithmetic_combinator' ? ' Use signal_everything for the output instead' : ''), ); if (opt.left) opt.left = this.bp.checkName(opt.left); if (typeof opt.right == 'string') opt.right = this.bp.checkName(opt.right); if (opt.out) opt.out = this.bp.checkName(opt.out); if (!this.condition) this.condition = {}; this.condition = { left: this.condition.left || opt.left, right: this.condition.right || opt.right, operator: this.condition.operator || opt.operator, countFromInput: this.condition.countFromInput || opt.countFromInput, out: this.condition.out || opt.out, controlEnable: this.condition.controlEnable || opt.controlEnable, // circuit_enable_disable, true/false readContents: this.condition.readContents || opt.readContents, // circuit_read_hand_contents, true/false readMode: this.condition.readMode || opt.readMode, // circuit_contents_read_mode, 0 or 1 }; return this; } // Sets direction of entity setDirection(dir: number) { // if (this.direction == null) return this; // Prevent rotation when we know what things can rotate in defaultentities.js this.size = new Victor( dir % 4 == this.direction % 4 ? this.size.x : this.size.y, dir % 4 == this.direction % 4 ? this.size.y : this.size.x, ); this.direction = dir; return this; } setDirectionType(type: DirectionType) { if (!this.HAS_DIRECTION_TYPE) throw new Error( 'This type of item does not have a directionType! Usually only underground belts have these.', ); this.directionType = type; return this; } setRecipe(recipe: string) { if (!this.CAN_HAVE_RECIPE) throw new Error('This entity cannot have a recipe.'); this.recipe = this.bp.checkName(recipe); return this; } setBar(num: number) { if (!this.INVENTORY_SIZE) throw new Error('Only entities with inventories can have bars!'); else if (typeof num == 'number' && num < 0) throw new Error('You must provide a positive value to setBar()'); this.bar = typeof num != 'number' || num >= this.INVENTORY_SIZE ? -1 : num; return this; } setCircuitParameters(obj: any) { if (!this.circuitParameters) this.circuitParameters = {}; Object.keys(obj).forEach(key => (this.circuitParameters[key] = obj[key])); return this; } setParameters(obj: any) { if (!this.parameters) this.parameters = {}; Object.keys(obj).forEach(key => (this.parameters[key] = obj[key])); return this; } setAlertParameters(opt: AlertParameters) { if (!this.alertParameters) this.alertParameters = {}; Object.keys(opt).forEach( // @ts-ignore (key: keyof AlertParameters) => (this.alertParameters[key] = opt[key]), ); return this; } setConstant(pos: number, name: string, count: number) { if (this.name != 'constant_combinator') throw new Error('Can only set constants for constant combinators!'); else if (pos < 0 || pos >= 18) throw new Error( pos + ' is an invalid position (must be between 0 and 17 inclusive)', ); if (!this.constants) { this.constants = {}; } if (!name) delete this.constants[pos]; else this.constants[pos] = { name: this.bp.checkName(name), count: count == undefined ? 0 : count, }; return this; } setSplitterFilter(name: string) { this.splitterFilter = name; return this; } setInputPriority(priority?: Priority) { this.inputPriority = priority; return this; } setOutputPriority(priority?: Priority) { this.outputPriority = priority; return this; } getData() { const useValueOrDefault = (val: any, def: any) => val != undefined ? val : def; const getOptionData = (append: any = {}) => { if (!this.condition) return append; append.circuit_enable_disable = this.condition.controlEnable; append.circuit_read_hand_contents = this.condition.readContents; append.circuit_contents_read_mode = this.condition.readMode != undefined ? this.condition.readMode == 'pulse' ? 0 : 1 : undefined; return append; }; const getCondition = () => { // let key = this.name == 'arithmetic_combinator' ? 'arithmetic' : (this.name == 'decider_combinator' ? 'decider' : 'circuit'); const out: any = {}; out.first_signal = this.condition.left ? { type: entityData[this.condition.left].type, name: this.condition.left.replace(/_/g, '-'), } : undefined; out.second_signal = typeof this.condition.right == 'string' ? { type: entityData[this.condition.right].type, name: this.condition.right.replace(/_/g, '-'), } : undefined; out.constant = typeof this.condition.right == 'number' ? this.condition.right : undefined; out.operation = undefined; out.comparator = undefined; out.output_signal = this.condition.out ? { type: entityData[this.condition.out].type, name: this.condition.out.replace(/_/g, '-'), } : undefined; if (this.name != 'arithmetic_combinator') { out.comparator = this.condition.operator; out.copy_count_from_input = this.condition.countFromInput != undefined ? (!!this.condition.countFromInput).toString() : undefined; } else { out.operation = this.condition.operator; } return out; }; const getAlertParameters = ({ showAlert = false, showOnMap = true, message = '', icon = undefined, }: AlertParameters) => { if (icon) { // Allow shorthand (icon name only) by // looking up type if (typeof icon === 'string') { icon = { type: entityData[icon].type || '', name: icon.replace(/_/g, '-'), }; } else { icon = { type: icon.type.replace(/_/g, '-'), name: icon.name.replace(/_/g, '-'), }; } } return { show_alert: showAlert, show_on_map: showOnMap, alert_message: message, icon_signal_id: icon, }; }; return { name: this.bp.fixName(this.name), position: this.center().subtract(new Victor(0.5, 0.5)) as { x: number; y: number; }, direction: this.direction || 0, entity_number: -1, type: /*this.HAS_DIRECTION_TYPE*/ this.directionType ? this.directionType : undefined, recipe: /*this.CAN_HAVE_RECIPE &&*/ this.recipe ? this.bp.fixName(this.recipe) : undefined, bar: /*this.INVENTORY_SIZE &&*/ this.bar != -1 ? this.bar : undefined, filter: this.splitterFilter ? this.bp.fixName(this.splitterFilter) : undefined, input_priority: this.inputPriority || undefined, output_priority: this.outputPriority || undefined, items: /*this.CAN_HAVE_MODULES &&*/ this.modules && Object.keys(this.modules).length ? Object.keys(this.modules).reduce( (obj: { [name: string]: number }, key) => { obj[this.bp.fixName(key)] = this.modules[key]; return obj; }, {}, ) : undefined, filters: makeEmptyArrayUndefined( Object.keys(this.filters).map((filterPosition: string) => { return { index: parseInt(filterPosition) + 1, name: this.bp.fixName(this.filters[parseInt(filterPosition)]), }; }), ), request_filters: makeEmptyArrayUndefined( Object.keys(this.requestFilters).map((index: string) => { const rFilter = this.requestFilters[parseInt(index)]; return { name: this.bp.fixName(rFilter.name), count: rFilter.count, index: parseInt(index) + 1, }; }), ), connections: this.connections.length || this.condition || Object.keys(this.condition).length || Object.keys(this.circuitParameters).length ? this.connections.reduce( ( obj: { [side: string]: { [color: string]: { entity_id: number; circuit_id?: string; }[]; }; }, connection, ) => { let side = connection.side; let color = connection.color; if (!obj[side]) obj[side] = {}; if (!obj[side][color]) obj[side][color] = []; obj[side][color].push({ entity_id: connection.entity.id, circuit_id: connection.id, }); return obj; }, {}, ) : undefined, neighbours: this.neighbours.map(ent => ent.id), parameters: this.parameters ? { playback_volume: useValueOrDefault(this.parameters.volume, 1.0), playback_globally: useValueOrDefault( this.parameters.playGlobally, false, ), allow_polyphony: useValueOrDefault( this.parameters.allowPolyphony, true, ), } : undefined, alert_parameters: this.alertParameters ? getAlertParameters(this.alertParameters) : undefined, control_behavior: this.constants || this.condition || this.name == 'decider_combinator' || this.name == 'arithmetic_combinator' ? getOptionData({ filters: this.constants && Object.keys(this.constants).length ? Object.keys(this.constants).map((key, i) => { // @ts-ignore const data = this.constants[key]; return { signal: { name: this.bp.fixName(data.name), type: entityData[data.name].type, }, count: data.count != undefined ? data.count : 0, index: parseInt(key) + 1, }; }) : undefined, decider_conditions: this.name == 'decider_combinator' ? getCondition() : undefined, arithmetic_conditions: this.name == 'arithmetic_combinator' ? getCondition() : undefined, circuit_condition: !this.name.includes('combinator') && this.condition.left ? getCondition() : undefined, is_on: this.name == 'constant_combinator' && !this.constantEnabled ? this.constantEnabled : undefined, circuit_parameters: this.circuitParameters ? { signal_value_is_pitch: useValueOrDefault( this.circuitParameters.signalIsPitch, false, ), instrument_id: useValueOrDefault( this.circuitParameters.instrument, 0, ), note_id: useValueOrDefault(this.circuitParameters.note, 0), } : undefined, }) : undefined, }; } } // Lib Functions // Convert 'in' or 'out' of wires (only combinators have both of these) to a 1 or 2. function convertSide(side: Side, ent: Entity) { if (!side) return 1; if (side == 1 || side == 2) return side; else if (side == 'in' || side == 'out') { if ( ent && ent.name != 'arithmetic_combinator' && ent.name != 'decider_combinator' ) return 1; else return side == 'in' ? 1 : 2; } else throw new Error('Invalid side'); } function makeEmptyArrayUndefined(arr: any[]) { return arr.length ? arr : undefined; }
the_stack
import Store from '@src/store/store'; import root from '@src/store/root'; import layout from '@src/store/layout'; import seriesData from '@src/store/seriesData'; import category from '@src/store/category'; import legend from '@src/store/legend'; import optionsStore from '@src/store/options'; import theme from '@src/store/theme'; import EventEmitter from '@src/eventEmitter'; import ComponentManager from '@src/component/componentManager'; import Painter from '@src/painter'; import Animator from '@src/animator'; import { debounce, isBoolean, isNumber, isUndefined, pick, isAutoValue } from '@src/helpers/utils'; import { ChartProps, Point, AnimationOptions, SeriesDataInput, Size, DataInput, ChartSizeInput, } from '@t/options'; import { RespondersModel } from '@src/component/component'; import { responderDetectors } from '@src/responderDetectors'; import { ChartState, Options, StoreModule, UsingContainerSize } from '@t/store/store'; import Component from '@src/component/component'; import { CheckedLegendType } from '@t/components/legend'; import { message } from '@src/message'; import { sendHostname } from '@src/helpers/googleAnalytics'; import { makeObservableObjectToNormal } from '@src/store/reactive'; import { SelectSeriesInfo, AddSeriesDataInfo } from '@t/charts'; import { CustomEventType, EventListener } from '@t/eventEmitter'; import { isMouseInRect } from '@src/helpers/coordinate'; export const DEFAULT_ANIM_DURATION = 500; export interface SelectSeriesHandlerParams<T extends Options> extends SelectSeriesInfo { state: ChartState<T>; } function getUsingContainerSize( eventName: 'initOptions' | 'updateOptions', usingContainerSize: UsingContainerSize, width?: ChartSizeInput, height?: ChartSizeInput ) { const { width: usingContainerWidth, height: usingContainerHeight } = usingContainerSize; const isAutoWidth = isAutoValue(width); const isAutoHeight = isAutoValue(height); return eventName === 'updateOptions' ? { width: !isUndefined(width) && usingContainerWidth !== isAutoWidth ? isAutoWidth : usingContainerWidth, height: !isUndefined(height) && usingContainerHeight !== isAutoHeight ? isAutoHeight : usingContainerHeight, } : { width: isAutoWidth, height: isAutoHeight, }; } /** * @class * @abstract * Abstract class used to implement each chart. */ export default abstract class Chart<T extends Options> { store: Store<T>; ___animId___ = null; animator: Animator; readonly containerEl: HTMLElement; el: HTMLDivElement; ctx!: CanvasRenderingContext2D; painter = new Painter(this); readonly eventBus: EventEmitter = new EventEmitter(); readonly componentManager: ComponentManager<T>; modules: StoreModule[]; enteredComponents: Component[] = []; animationControlFlag = { resizing: false, updating: false, }; resizeObserver: ResizeObserver | null = null; private getAnimationDuration(animationOption?: AnimationOptions) { const { firstRendering } = this.animator; const { resizing, updating } = this.animationControlFlag; let duration; if ((!firstRendering && !resizing) || isUndefined(animationOption)) { duration = DEFAULT_ANIM_DURATION; } else if (isBoolean(animationOption)) { duration = animationOption ? DEFAULT_ANIM_DURATION : 0; } else if (isNumber(animationOption.duration)) { duration = animationOption.duration; } if (updating) { duration = 0; } this.animationControlFlag.updating = false; return duration; } createChartWrapper() { const el = document.createElement('div'); el.classList.add('toastui-chart-wrapper'); return el; } constructor(props: ChartProps<T>) { const { el, options, series, categories, modules } = props; this.modules = modules ?? []; if (isUndefined(options.usageStatistics) || options.usageStatistics) { sendHostname(); } this.containerEl = el; this.el = this.createChartWrapper(); this.containerEl.appendChild(this.el); this.animator = new Animator(); this.store = new Store({ series, categories, options, }); this.componentManager = new ComponentManager({ store: this.store, eventBus: this.eventBus, }); this.eventBus.on( 'needLoop', debounce(() => { let duration = this.getAnimationDuration(options.chart?.animation); if (this.animationControlFlag.resizing) { duration = isUndefined(options.responsive) ? this.getAnimationDuration() : this.getAnimationDuration(options.responsive?.animation); this.animationControlFlag.resizing = false; } this.eventBus.emit('loopStart'); this.animator.add({ onCompleted: () => { this.eventBus.emit('loopComplete'); }, chart: this, duration, requester: this, }); }, 10) ); this.eventBus.on('needSubLoop', (opts) => { this.animator.add({ ...opts, chart: this }); }); this.eventBus.on( 'needDraw', debounce(() => { this.draw(); }, 10) ); this.initialize(); this.store.observe(() => { this.painter.setup(); }); if (isAutoValue(options?.chart?.width) || isAutoValue(options?.chart?.height)) { this.setResizeEvent(); } } resizeChartSize(containerWidth?: number, containerHeight?: number) { this.animationControlFlag.resizing = true; const { usingContainerSize: { width: usingContainerWidth, height: usingContainerHeight }, chart: { width, height }, } = this.store.state; if ( !(usingContainerWidth || usingContainerHeight) || !(containerWidth || containerHeight) || (containerWidth === width && containerHeight === height) ) { this.animationControlFlag.resizing = false; return; } // @TODO: For updates where the data doesn't change, it looks good to recalculate the selected series position. this.resetSeries(); this.store.dispatch('setChartSize', { width: usingContainerWidth ? containerWidth : width, height: usingContainerHeight ? containerHeight : height, }); this.draw(); } private debounceResizeEvent = debounce(() => { const { offsetWidth, offsetHeight } = this.containerEl; this.resizeChartSize(offsetWidth, offsetHeight); }, 100); setResizeEvent() { const { usingContainerSize } = this.store.state; if ( (usingContainerSize.height && !this.containerEl.style.height.length) || (usingContainerSize.width && !this.containerEl.style.width.length) ) { throw new Error(message.AUTO_LAYOUT_CONTAINER_SIZE_ERROR); } const isResizeObserverAPIExist = typeof ResizeObserver === 'undefined'; if (isResizeObserverAPIExist) { window.addEventListener('resize', this.debounceResizeEvent); } else { this.resizeObserver = new ResizeObserver((entries) => { entries.forEach(() => { this.debounceResizeEvent(); }); }); this.resizeObserver.observe(this.containerEl); } } clearResizeEvent() { if (this.resizeObserver) { this.resizeObserver.unobserve(this.containerEl); this.resizeObserver.disconnect(); this.resizeObserver = null; } else { window.removeEventListener('resize', this.debounceResizeEvent); } } handleCanvasMouseEvent(eventType: string, mousePosition: Point) { const newEnteredComponents: Component[] = []; this.componentManager.forEach((component) => { if (eventType === 'mousemove') { const exist = this.enteredComponents.some( (enteredComponent) => enteredComponent === component ); if (isMouseInRect(component.rect, mousePosition)) { newEnteredComponents.push(component); if (!exist && component.onMouseenterComponent) { component.onMouseenterComponent(); } } else if (exist && component.onMouseoutComponent) { component.onMouseoutComponent(); } } else if (eventType === 'mouseout' && component.onMouseoutComponent) { component.onMouseoutComponent(); } }); this.enteredComponents = newEnteredComponents; } handleResponderEvent(event: MouseEvent, mousePosition: Point) { const eventType = event.type; const delegationMethod = `on${eventType[0].toUpperCase() + eventType.substring(1)}`; const allResponders: RespondersModel = []; this.componentManager.forEach((component) => { if (!component[delegationMethod]) { return; } if (!responderDetectors.rect(mousePosition, component.rect)) { return; } const detected = (component.responders || []).filter((m) => { return responderDetectors[m.type](mousePosition, m, component.rect); }); if (detected.length) { allResponders.push({ component, detected }); } component[delegationMethod]({ mousePosition, responders: detected }, event); }); if (this.handleEventForAllResponders) { this.handleEventForAllResponders(event, allResponders, delegationMethod, mousePosition); } } handleEvent(event: MouseEvent) { const { clientX, clientY, type: eventType } = event; const canvas = this.painter.ctx.canvas; const { width, height, left, top } = canvas.getBoundingClientRect(); // Calculate scale for chart affected by a CSS transform. const scaleX = width / canvas.offsetWidth; const scaleY = height / canvas.offsetHeight; const mousePosition = { x: (clientX - left) / scaleX, y: (clientY - top) / scaleY, }; if (eventType === 'mousemove' || eventType === 'mouseout') { this.handleCanvasMouseEvent(eventType, mousePosition); } this.handleResponderEvent(event, mousePosition); } protected initStore() { [ root, optionsStore, theme, seriesData, legend, layout, category, ...this.modules, ].forEach((module) => this.store.setModule(module)); } protected initialize() { this.initStore(); this.store.dispatch('initChartSize', this.containerEl); } draw() { this.painter.beforeFrame(); this.componentManager.forEach((component) => { if (!component.isShow) { return; } this.painter.beforeDraw(component.rect.x, component.rect.y); if (component.beforeDraw) { component.beforeDraw(this.painter); } component.draw(this.painter); this.painter.afterDraw(); }); } update(delta: number) { this.componentManager.invoke('update', delta); } initUpdate(delta: number) { this.componentManager.invoke('initUpdate', delta); } protected handleEventForAllResponders?( event: MouseEvent, responderModels: RespondersModel, delegationMethod: string, mousePosition: Point ): void; /** * Get checked legend chart type and label, checked state. * @returns {Array<{checked: boolean, chartType: string, label: string}>} Array data that whether series has checked * @api * @example * const checkedLegend = chart.getCheckedLegend() */ public getCheckedLegend = (): CheckedLegendType => { const { data } = this.store.state.legend; return data .filter((datum) => datum.checked) .map((datum) => pick(datum, 'chartType', 'label', 'checked')); }; public abstract updateOptions(options: Options): void; public abstract setOptions(options: Options): void; public abstract showTooltip(info: SelectSeriesInfo): void; public abstract hideTooltip(): void; /** * Returns the currently applied chart options. * @returns {Object} options * @api * @example * const options = chart.getOptions(); */ public getOptions = () => { return makeObservableObjectToNormal(this.store.initStoreState.options); }; public abstract addSeries(data: SeriesDataInput, dataInfo?: AddSeriesDataInfo): void; /** * Register of user custom event. * @param {string} eventName - Event name. 'clickLegendLabel', 'clickLegendCheckbox', 'selectSeries', 'unselectSeries', 'hoverSeries', 'unhoverSeries', 'zoom', 'resetZoom' is available. * @param {Function} handler - Event handler * @api */ public on = (eventName: CustomEventType, handler: EventListener) => { /** * Register Events that occur when click legend label * @event ChartBase#clickLegendLabel * @param {object} info selected legend information * @api * @example * chart.on('clickLegendLabel', (info) => { * console.log(info); * }); */ /** * Register Events that occur when click legend checkbox * @event ChartBase#clickLegendCheckbox * @param {object} info selected legend info * @api * @example * chart.on('clickLegendCheckbox', (info) => { * console.log(info); * }); */ /** * Register Events that occur when select series * @event ChartBase#selectSeries * @param {object} info selected series info * @api * @example * chart.on('selectSeries', (info) => { * console.log(info); * }); */ /** * Register Events that occur when unselect series * @event ChartBase#unselectSeries * @param {object} info unselected series info * @api * @example * chart.on('unselectSeries', (info) => { * console.log(info); * }); */ /** * Register Events that occur when hover to series * @event ChartBase#hoverSeries * @param {object} info hovered series info * @api * @example * chart.on('hoverSeries', (info) => { * console.log(info); * }); */ /** * Register Events that occur when unhover from series * @event ChartBase#unhoverSeries * @param {object} info unhovered series info * @api * @example * chart.on('unhoverSeries', (info) => { * console.log(info); * }); */ /** * Register Events that occur when zooming * @event ChartBase#zoom * @param {string[]} dataRange - [] * @api * @example * chart.on('zoom', (dataRange) => { * console.log(dataRange); * }); */ /** * Register Events that occur when zoom is reset * @event ChartBase#resetZoom * @api * @example * chart.on('resetZoom', () => {}); */ this.eventBus.on(eventName, handler); }; public abstract setData(data: DataInput): void; /** * Destroys the instance. * @api * @example * chart.destroy(); */ public destroy = () => { this.componentManager.clear(); this.clearResizeEvent(); this.containerEl.innerHTML = ''; }; private isSelectableSeries() { return this.store.initStoreState.options.series?.selectable; } /** * Select series. It works only when the selectable option is true. * @param {Object} seriesInfo - Information of the series to be selected * @param {number} [seriesInfo.seriesIndex] - Index of series * @param {number} [seriesInfo.index] - Index of data within series * @param {string} [seriesInfo.name] - Specify name for NestedPie Chart * @param {string} [seriesInfo.chartType] - Specify which chart to select when using LineArea, LineScatter, and ColumnLine charts.specifies which chart to select when using LineArea, LineScatter, and ColumnLine charts. * @api * @example * chart.selectSeries({index: 1, seriesIndex: 2}); */ public selectSeries = (seriesInfo: SelectSeriesInfo) => { if (!this.isSelectableSeries()) { throw new Error(message.SELECT_SERIES_API_SELECTABLE_ERROR); } this.eventBus.emit('selectSeries', { ...seriesInfo, state: this.store.state }); }; /** * Unselect selected series. It works only when the selectable option is true. * @api * @example * chart.unselectSeries(); */ public unselectSeries = () => { if (!this.isSelectableSeries()) { throw new Error(message.SELECT_SERIES_API_SELECTABLE_ERROR); } this.store.dispatch('setAllLegendActiveState', true); this.eventBus.emit('resetSelectedSeries'); }; /** * Resize chart size. * @param {Object} size Chart size * @param {number} [size.width] Width * @param {number} [size.height] Height * @api * @example * chart.resize({height: 100, width: 200}); */ public resize = (size: Partial<Size>) => { this.resetSeries(); this.dispatchOptionsEvent('updateOptions', { chart: { ...size } }); }; /** * Set tooltip offset. * @param {Object} offset - Offset size * @param {number} [offset.x] Offset value to move title horizontally * @param {number} [offset.y] Offset value to move title vertically * @api * @example * chart.setTooltipOffset({x: 10, y: -20}); */ public setTooltipOffset(offset: Partial<Point>) { const { x: offsetX, y: offsetY } = offset; this.store.dispatch('updateOptions', { options: { tooltip: { offsetX, offsetY } } }); } resetSeries = () => { this.eventBus.emit('resetHoveredSeries'); this.eventBus.emit('resetSelectedSeries'); }; private setResizeEventListeners = ( eventName: 'initOptions' | 'updateOptions', options: Options ) => { const { usingContainerSize } = this.store.state; const { width: usingContainerWidth, height: usingContainerHeight } = usingContainerSize; const width = options?.chart?.width; const height = options?.chart?.height; const isAutoWidth = isAutoValue(width); const isAutoHeight = isAutoValue(height); this.store.dispatch( 'setUsingContainerSize', getUsingContainerSize(eventName, usingContainerSize, width, height) ); if ((usingContainerWidth || usingContainerHeight) && isNumber(width) && isNumber(height)) { this.clearResizeEvent(); } else if (!(usingContainerWidth || usingContainerHeight) && (isAutoWidth || isAutoHeight)) { this.setResizeEvent(); } }; protected dispatchOptionsEvent(eventName: 'initOptions' | 'updateOptions', options: Options) { this.setResizeEventListeners(eventName, options); const { offsetWidth, offsetHeight } = this.containerEl; this.store.dispatch(eventName, { options, containerSize: { width: offsetWidth, height: offsetHeight }, }); } }
the_stack
import { expect } from "chai"; import * as ERROR_MSGS from "../../src/constants/error_msgs"; import * as METADATA_KEY from "../../src/constants/metadata_keys"; import { Container, decorate, inject, injectable, interfaces, multiInject, named, tagged, targetName, unmanaged } from "../../src/inversify"; import { MetadataReader } from "../../src/planning/metadata_reader"; import { getDependencies } from "../../src/planning/reflection_utils"; import { getFunctionName, getServiceIdentifierAsString } from "../../src/utils/serialization"; describe("Bugs", () => { it("Should throw when args length of base and derived class not match", () => { @injectable() class Warrior { public rank: string; public constructor(rank: string) { // length = 1 this.rank = rank; } } @injectable() class SamuraiMaster extends Warrior { public constructor() { // length = 0 super("master"); } } const container = new Container(); container.bind<SamuraiMaster>(SamuraiMaster).to(SamuraiMaster); const shouldThrow = function () { container.get<SamuraiMaster>(SamuraiMaster); }; const error = ERROR_MSGS.ARGUMENTS_LENGTH_MISMATCH("SamuraiMaster"); expect(shouldThrow).to.throw(error); }); it("Should not throw when args length of base and derived class match (property setter)", () => { @injectable() class Warrior { public rank: string | null; public constructor() { // length = 0 this.rank = null; } } @injectable() class SamuraiMaster extends Warrior { public constructor() { // length = 0 super(); this.rank = "master"; } } const container = new Container(); container.bind<SamuraiMaster>(SamuraiMaster).to(SamuraiMaster); const master = container.get<SamuraiMaster>(SamuraiMaster); expect(master.rank).eql("master"); }); it("Should not throw when args length of base and derived class match", () => { // Injecting into the derived class @injectable() class Warrior { protected rank: string; public constructor(rank: string) { // length = 1 this.rank = rank; } } const TYPES = { Rank: "Rank" }; @injectable() class SamuraiMaster extends Warrior { public constructor( @inject(TYPES.Rank) @named("master") public rank: string // length = 1 ) { super(rank); } } const container = new Container(); container.bind<SamuraiMaster>(SamuraiMaster).to(SamuraiMaster); container.bind<string>(TYPES.Rank) .toConstantValue("master") .whenTargetNamed("master"); const master = container.get<SamuraiMaster>(SamuraiMaster); expect(master.rank).eql("master"); }); it("Should not throw when args length of base and derived class match", () => { // Injecting into the derived class with multiple args @injectable() class Warrior { protected rank: string; public constructor(rank: string) { // length = 1 this.rank = rank; } } interface Weapon { name: string; } @injectable() class Katana implements Weapon { public name: string; public constructor() { this.name = "Katana"; } } const TYPES = { Rank: "Rank", Weapon: "Weapon" }; @injectable() class SamuraiMaster extends Warrior { public weapon: Weapon; public constructor( @inject(TYPES.Rank) @named("master") public rank: string, @inject(TYPES.Weapon) weapon: Weapon ) { // length = 2 super(rank); this.weapon = weapon; } } const container = new Container(); container.bind<Weapon>(TYPES.Weapon).to(Katana); container.bind<SamuraiMaster>(SamuraiMaster).to(SamuraiMaster); container.bind<string>(TYPES.Rank) .toConstantValue("master") .whenTargetNamed("master"); const master = container.get<SamuraiMaster>(SamuraiMaster); expect(master.rank).eql("master"); expect(master.weapon.name).eql("Katana"); }); it("Should be able to convert a Symbol value to a string", () => { interface Weapon { } const TYPES = { Weapon: Symbol.for("Weapon") }; const container = new Container(); const throwF = () => { container.get<Weapon>(TYPES.Weapon); }; expect(throwF).to.throw(`${ERROR_MSGS.NOT_REGISTERED} ${getServiceIdentifierAsString(TYPES.Weapon)}`); }); it("Should be not require @inject annotation in toConstructor bindings", () => { interface ICategorySortingFn { } interface IContentSortingFn { } interface Collection { } @injectable() class Category { public constructor( public id: string, public title: string, public categoryFirstPermalink: string, public categoryPermalink: string, public pagination: number, public categorySortingFn: ICategorySortingFn, public contentSortingFn: IContentSortingFn, public belongsToCollection: Collection ) { // do nothing } } const container = new Container(); container.bind<interfaces.Newable<Category>>("Newable<Category>").toConstructor(Category); const expected = container.get<interfaces.Newable<Category>>("Newable<Category>"); expect(expected).eql(Category); }); it("Should be able to combine tagged injection and constant value bindings", () => { const container = new Container(); interface Intl { } container.bind<Intl>("Intl").toConstantValue({ hello: "bonjour" }).whenTargetTagged("lang", "fr"); container.bind<Intl>("Intl").toConstantValue({ goodbye: "au revoir" }).whenTargetTagged("lang", "fr"); const f = function () { container.getTagged<Intl>("Intl", "lang", "fr"); }; expect(f).to.throw(); }); it("Should be able to combine dynamic value with singleton scope", () => { const container = new Container(); container.bind<number>("transient_random").toDynamicValue((context: interfaces.Context) => Math.random()).inTransientScope(); container.bind<number>("singleton_random").toDynamicValue((context: interfaces.Context) => Math.random()).inSingletonScope(); const a = container.get<number>("transient_random"); const b = container.get<number>("transient_random"); expect(a).not.to.eql(b); const c = container.get<number>("singleton_random"); const d = container.get<number>("singleton_random"); expect(c).to.eql(d); }); it("Should be able to use an abstract class as the serviceIdentifier", () => { @injectable() abstract class Animal { protected name: string; public constructor(@unmanaged() name: string) { this.name = name; } public abstract makeSound(input: string): string; public move(meters: number) { return `${this.name} moved ${meters}m`; } } @injectable() class Snake extends Animal { public constructor() { super("Snake"); } public makeSound(input: string): string { return "sssss" + input; } public move() { return "Slithering... " + super.move(5); } } @injectable() class Jungle { public animal: Animal; public constructor(@inject(Animal) animal: Animal) { this.animal = animal; } } const container = new Container(); container.bind<Animal>(Animal).to(Snake); container.bind<Jungle>(Jungle).to(Jungle); const jungle = container.get(Jungle); expect(jungle.animal.makeSound("zzz")).to.eql("ssssszzz"); expect(jungle.animal.move(5)).to.eql("Slithering... Snake moved 5m"); }); it("Should be able to identify is a target is tagged", () => { const TYPES = { Dependency1: Symbol.for("Dependency1"), Dependency2: Symbol.for("Dependency2"), Dependency3: Symbol.for("Dependency3"), Dependency4: Symbol.for("Dependency4"), Dependency5: Symbol.for("Dependency5"), Test: Symbol.for("Test") }; const TAGS = { somename: "somename", sometag: "sometag" }; @injectable() class Dependency1 { public name = "Dependency1"; } @injectable() class Dependency2 { public name = "Dependency1"; } @injectable() class Dependency3 { public name = "Dependency1"; } @injectable() class Dependency4 { public name = "Dependency1"; } @injectable() class Dependency5 { public name = "Dependency1"; } @injectable() class Base { public baseProp: string; public constructor( @unmanaged() baseProp: string ) { this.baseProp = baseProp; } } @injectable() class Test extends Base { private _prop1: Dependency1; private _prop2: Dependency2[]; private _prop3: Dependency3; private _prop4: Dependency4; private _prop5: Dependency5; public constructor( @inject(TYPES.Dependency1) prop1: Dependency1, // inject @multiInject(TYPES.Dependency2) prop2: Dependency2[], // multi inject @inject(TYPES.Dependency3) @named(TAGS.somename) prop3: Dependency3, // named @inject(TYPES.Dependency4) @tagged(TAGS.sometag, true) prop4: Dependency4, // tagged @inject(TYPES.Dependency5) @targetName("prop6") prop5: Dependency5 // targetName ) { super("unmanaged!"); this._prop1 = prop1; this._prop2 = prop2; this._prop3 = prop3; this._prop4 = prop4; this._prop5 = prop5; } public debug() { return { prop1: this._prop1, prop2: this._prop2, prop3: this._prop3, prop4: this._prop4, prop5: this._prop5 }; } } const container = new Container(); container.bind<Test>(TYPES.Test).to(Test); container.bind<Dependency1>(TYPES.Dependency1).to(Dependency1); container.bind<Dependency2>(TYPES.Dependency2).to(Dependency2); container.bind<Dependency3>(TYPES.Dependency3).to(Dependency3); container.bind<Dependency4>(TYPES.Dependency4).to(Dependency4); container.bind<Dependency5>(TYPES.Dependency5).to(Dependency5); function logger(next: interfaces.Next): interfaces.Next { return (args: interfaces.NextArgs) => { const nextContextInterceptor = args.contextInterceptor; args.contextInterceptor = (context: interfaces.Context) => { context.plan.rootRequest.childRequests.forEach((request, index) => { if (request === null || request.target === null) { throw new Error("Request should not be null!"); } switch (index) { case 0: expect(request.target.isNamed()).to.eql(false); expect(request.target.isTagged()).to.eql(false); break; case 1: expect(request.target.isNamed()).to.eql(false); expect(request.target.isTagged()).to.eql(false); break; case 2: expect(request.target.isNamed()).to.eql(true); expect(request.target.isTagged()).to.eql(false); break; case 3: expect(request.target.isNamed()).to.eql(false); expect(request.target.isTagged()).to.eql(true); break; case 4: expect(request.target.isNamed()).to.eql(false); expect(request.target.isTagged()).to.eql(false); } }); if (nextContextInterceptor !== null) { return nextContextInterceptor(context); } else { throw new Error("nextContextInterceptor should not be null!"); } }; const result = next(args); return result; }; } container.applyMiddleware(logger); container.get<Test>(TYPES.Test); }); it("Helper getFunctionName should not throw when using an anonymous function", () => { const name = getFunctionName(function (options: unknown) { return options; }); expect(name).to.eql("Anonymous function: " + (function (options: unknown) { return options; }).toString()); }); it("Should be able to get all the available bindings for a service identifier", () => { const controllerId = "SomeControllerID"; const tagA = "A"; const tagB = "B"; interface Controller { name: string; } const container = new Container(); @injectable() class AppController implements Controller { public name: string; public constructor() { this.name = "AppController"; } } @injectable() class AppController2 implements Controller { public name: string; public constructor() { this.name = "AppController2"; } } container.bind(controllerId).to(AppController).whenTargetNamed(tagA); container.bind(controllerId).to(AppController2).whenTargetNamed(tagB); function wrongNamedBinding() { container.getAllNamed<Controller>(controllerId, "Wrong"); } expect(wrongNamedBinding).to.throw(); const appControllerNamedRight = container.getAllNamed<Controller>(controllerId, tagA); expect(appControllerNamedRight.length).to.eql(1, "getAllNamed"); expect(appControllerNamedRight[0]?.name).to.eql("AppController"); function wrongTaggedBinding() { container.getAllTagged<Controller>(controllerId, "Wrong", "Wrong"); } expect(wrongTaggedBinding).to.throw(); const appControllerTaggedRight = container.getAllTagged<Controller>(controllerId, METADATA_KEY.NAMED_TAG, tagB); expect(appControllerTaggedRight.length).to.eql(1, "getAllTagged"); expect(appControllerTaggedRight[0]?.name).to.eql("AppController2"); const getAppController = () => { const matches = container.getAll<Controller>(controllerId); expect(matches.length).to.eql(2); expect(matches[0]?.name).to.eql("AppController"); expect(matches[1]?.name).to.eql("AppController2"); }; expect(getAppController).not.to.throw(); }); it("Should not be able to get a named dependency if no named bindings are registered", () => { const TYPES = { Weapon: "Weapon" }; interface Weapon { name: string; } @injectable() class Katana implements Weapon { public name: string; public constructor() { this.name = "Katana"; } } const container = new Container(); container.bind<Weapon>(TYPES.Weapon).to(Katana).whenTargetNamed("sword"); const throws = () => { container.getNamed<Weapon>(TYPES.Weapon, "bow"); }; const error = "No matching bindings found for serviceIdentifier: Weapon\n Weapon " + "- named: bow \n\nRegistered bindings:\n Katana - named: sword "; expect(throws).to.throw(error); }); it("Should throw a friendly error when binding a non-class using toSelf", () => { const container = new Container(); const throws = () => { container.bind("testId").toSelf(); }; expect(throws).to.throw(ERROR_MSGS.INVALID_TO_SELF_VALUE); }); it("Should generate correct metadata when the spread operator is used", () => { const BAR = Symbol.for("BAR"); const FOO = Symbol.for("FOO"); interface Bar { name: string; } @injectable() class Foo { public bar: Bar[]; public constructor(@multiInject(BAR) ...args: Bar[][]) { this.bar = args[0] as Bar[]; } } // is the metadata correct? const serviceIdentifiers = Reflect.getMetadata(METADATA_KEY.TAGGED, Foo); expect(serviceIdentifiers["0"][0].value.toString()).to.be.eql("Symbol(BAR)"); // is the plan correct? const dependencies = getDependencies(new MetadataReader(), Foo); expect(dependencies.length).to.be.eql(1); expect(dependencies[0]?.serviceIdentifier.toString()).to.be.eql("Symbol(BAR)"); // integration test const container = new Container(); container.bind<Bar>(BAR).toConstantValue({ name: "bar1" }); container.bind<Bar>(BAR).toConstantValue({ name: "bar2" }); container.bind<Foo>(FOO).to(Foo); const foo = container.get<Foo>(FOO); expect(foo.bar.length).to.eql(2); expect(foo.bar[0]?.name).to.eql("bar1"); expect(foo.bar[1]?.name).to.eql("bar2"); }); it("Should be able to inject into an abstract class", () => { interface Weapon { } @injectable() abstract class BaseSoldier { public weapon: Weapon; public constructor( @inject("Weapon") weapon: Weapon ) { this.weapon = weapon; } } @injectable() class Soldier extends BaseSoldier { } @injectable() class Archer extends BaseSoldier { } @injectable() class Knight extends BaseSoldier { } @injectable() class Sword implements Weapon { } @injectable() class Bow implements Weapon { } @injectable() class DefaultWeapon implements Weapon { } const container = new Container(); container.bind<Weapon>("Weapon").to(DefaultWeapon).whenInjectedInto(Soldier); container.bind<Weapon>("Weapon").to(Sword).whenInjectedInto(Knight); container.bind<Weapon>("Weapon").to(Bow).whenInjectedInto(Archer); container.bind<BaseSoldier>("BaseSoldier").to(Soldier).whenTargetNamed("default"); container.bind<BaseSoldier>("BaseSoldier").to(Knight).whenTargetNamed("knight"); container.bind<BaseSoldier>("BaseSoldier").to(Archer).whenTargetNamed("archer"); const soldier = container.getNamed<BaseSoldier>("BaseSoldier", "default"); const knight = container.getNamed<BaseSoldier>("BaseSoldier", "knight"); const archer = container.getNamed<BaseSoldier>("BaseSoldier", "archer"); expect(soldier.weapon instanceof DefaultWeapon).to.eql(true); expect(knight.weapon instanceof Sword).to.eql(true); expect(archer.weapon instanceof Bow).to.eql(true); }); it("Should be able apply inject to property shortcut", () => { interface Weapon { use(): string; } @injectable() class Katana implements Weapon { public use() { return "Used Katana!"; } } @injectable() class Ninja { public constructor(@inject("Weapon") @named("sword") private _weapon: Weapon) { // } public fight() { return this._weapon.use(); } } const container = new Container(); container.bind<Weapon>("Weapon").to(Katana).whenTargetNamed("sword"); container.bind<Ninja>(Ninja).toSelf(); const ninja = container.get<Ninja>(Ninja); expect(ninja.fight()).eql("Used Katana!"); }); it("Should be able to inject into abstract base class without decorators", () => { const TYPES = { Warrior: "Warrior", Weapon: "Weapon" }; const TAGS = { Primary: "Primary", Priority: "Priority", Secondary: "Secondary" }; interface Weapon { name: string; } @injectable() class Katana implements Weapon { public name: string; public constructor() { this.name = "Katana"; } } @injectable() class Shuriken implements Weapon { public name: string; public constructor() { this.name = "Shuriken"; } } interface Warrior { name: string; primaryWeapon: Weapon; } abstract class BaseWarrior implements Warrior { public name: string; public primaryWeapon!: Weapon; public constructor(@unmanaged() name: string) { this.name = name; } } // @injectable() decorate(injectable(), BaseWarrior); // @inject(TYPES.Weapon) inject(TYPES.Weapon)(BaseWarrior.prototype, "primaryWeapon"); // @tagged(TAGS.Priority, TAGS.Primary) tagged(TAGS.Priority, TAGS.Primary)(BaseWarrior.prototype, "primaryWeapon"); @injectable() class Samurai extends BaseWarrior { @inject(TYPES.Weapon) @tagged(TAGS.Priority, TAGS.Secondary) public secondaryWeapon!: Weapon; public constructor() { super("Samurai"); } } const container = new Container(); container.bind<Warrior>(TYPES.Warrior).to(Samurai); container.bind<Weapon>(TYPES.Weapon).to(Katana).whenTargetTagged(TAGS.Priority, TAGS.Primary); container.bind<Weapon>(TYPES.Weapon).to(Shuriken).whenTargetTagged(TAGS.Priority, TAGS.Secondary); const samurai = container.get<Samurai>(TYPES.Warrior); expect(samurai.name).to.eql("Samurai"); expect(samurai.secondaryWeapon).not.to.eql(undefined); expect(samurai.secondaryWeapon.name).to.eql("Shuriken"); expect(samurai.primaryWeapon).not.to.eql(undefined); expect(samurai.primaryWeapon.name).to.eql("Katana"); }); it("Should be able to combine unmanaged and managed injections ", () => { interface Model<T> { instance: T; } interface RepoBaseInterface<T> { model: Model<T>; } class Type { public name: string; public constructor() { this.name = "Type"; } } @injectable() class RepoBase<T> implements RepoBaseInterface<T> { public model: Model<T>; public constructor( // using @unmanaged() here is right // because entityType is NOT Injected by inversify @unmanaged() entityType: new () => T ) { this.model = { instance: new entityType() }; } } @injectable() class TypedRepo extends RepoBase<Type> { public constructor() { super(Type); // unmanaged injection (NOT Injected by inversify) } } @injectable() class BLBase<T> { public repository: RepoBaseInterface<T>; public constructor( // using @unmanaged() here would wrong // because repository is injected by inversify repository: RepoBaseInterface<T> ) { this.repository = repository; } } @injectable() class TypedBL extends BLBase<Type> { public constructor( repository: TypedRepo // Injected by inversify (no @inject required) ) { super(repository); // managed injection (Injected by inversify) } } const container = new Container(); container.bind<TypedRepo>(TypedRepo).toSelf(); container.bind<TypedBL>("TypedBL").to(TypedBL); const typedBL = container.get<TypedBL>("TypedBL"); expect(typedBL.repository.model.instance.name).to.eq(new Type().name); }); it("Should detect missing annotations in base classes", () => { @injectable() class Katana implements Katana { public hit() { return "cut!"; } } abstract class Warrior { private _katana: Katana; public constructor( @unmanaged() katana: Katana ) { this._katana = katana; } public fight() { return this._katana.hit(); } } @injectable() class Ninja extends Warrior { public constructor( @inject("Katana") katana: Katana ) { super(katana); } } const container = new Container(); container.bind<Warrior>("Ninja").to(Ninja); container.bind<Katana>("Katana").to(Katana); const tryGet = () => { container.get<Ninja>("Ninja"); }; expect(tryGet).to.throw("Missing required @injectable annotation in: Warrior."); }); });
the_stack
* Unit tests for pooling.ts. */ import * as tfc from '@tensorflow/tfjs-core'; import {Tensor, tensor2d, Tensor2D, tensor3d, tensor4d, tensor5d, Tensor4D, Tensor5D, util} from '@tensorflow/tfjs-core'; import {SymbolicTensor} from '../engine/topology'; import * as tfl from '../index'; import {DataFormat, PaddingMode, PoolMode} from '../keras_format/common'; import {convOutputLength} from '../utils/conv_utils'; import {describeMathCPUAndGPU, expectTensorsClose} from '../utils/test_utils'; import {pool2d, pool3d} from './pooling'; describeMathCPUAndGPU('pool2d', () => { const x4by4Data = [[[ [10, 30, 50, 70], [20, 40, 60, 80], [-10, -30, -50, -70], [-20, -40, -60, -80] ]]]; const x5by5Data = [[[ [0, 1, 3, 5, 7], [0, 2, 4, 6, 8], [0, 0, 0, 0, 0], [0, -1, -3, -5, -7], [0, -2, -4, -6, -8] ]]]; const poolModes: PoolMode[] = [undefined, 'max', 'avg']; const dataFormats: DataFormat[] = [undefined, 'channelsFirst', 'channelsLast']; const stridesArray = [1, 2]; for (const poolMode of poolModes) { for (const dataFormat of dataFormats) { for (const stride of stridesArray) { const testTitle = `4x4, ${stride}, same, ${dataFormat}, ` + `${poolMode}`; it(testTitle, () => { let x: Tensor = tensor4d(x4by4Data, [1, 1, 4, 4]); if (dataFormat !== 'channelsFirst') { x = tfc.transpose(x, [0, 2, 3, 1]); // NCHW -> NHWC. } let yExpected: Tensor; if (poolMode === 'avg') { if (stride === 1) { yExpected = tensor4d( [[[ [25, 45, 65, 75], [5, 5, 5, 5], [-25, -45, -65, -75], [-30, -50, -70, -80] ]]], [1, 1, 4, 4]); } else { yExpected = tensor4d([[[[25, 65], [-25, -65]]]], [1, 1, 2, 2]); } } else { if (stride === 1) { yExpected = tensor4d( [[[ [40, 60, 80, 80], [40, 60, 80, 80], [-10, -30, -50, -70], [-20, -40, -60, -80] ]]], [1, 1, 4, 4]); } else if (stride === 2) { yExpected = tensor4d([[[[40, 80], [-10, -50]]]], [1, 1, 2, 2]); } } if (dataFormat !== 'channelsFirst') { yExpected = tfc.transpose(yExpected, [0, 2, 3, 1]); } const y = pool2d(x, [2, 2], [stride, stride], 'same', dataFormat, poolMode); expectTensorsClose(y, yExpected); }); } } } for (const poolMode of poolModes) { it(`5x5, 2, same, CHANNEL_FIRST, ${poolMode}`, () => { const x5by5 = tensor4d(x5by5Data, [1, 1, 5, 5]); let yExpected = tensor4d(x4by4Data, [1, 1, 4, 4]); if (poolMode === 'avg') { yExpected = tensor4d( [[[[0.75, 4.5, 7.5], [-0.25, -2, -3.5], [-1, -5, -8]]]], [1, 1, 3, 3]); } else { yExpected = tensor4d([[[[2, 6, 8], [0, 0, 0], [0, -4, -8]]]], [1, 1, 3, 3]); } const y = pool2d(x5by5, [2, 2], [2, 2], 'same', 'channelsFirst', poolMode); expectTensorsClose(y, yExpected); }); } for (const poolMode of poolModes) { it(`5x5, 2, valid, CHANNEL_LAST, ${poolMode}`, () => { const x5by5 = tfc.transpose(tensor4d(x5by5Data, [1, 1, 5, 5]), [0, 2, 3, 1]); let yExpected: Tensor4D; if (poolMode === 'avg') { yExpected = tensor4d([[[[0.75, 4.5], [-0.25, -2]]]], [1, 1, 2, 2]); } else { yExpected = tensor4d([[[[2, 6], [0, 0]]]], [1, 1, 2, 2]); } const y = pool2d(x5by5, [2, 2], [2, 2], 'valid', 'channelsLast', poolMode); expectTensorsClose(y, tfc.transpose(yExpected, [0, 2, 3, 1])); }); } }); describeMathCPUAndGPU('pool3d', () => { const x4by4by4Data = [[[ [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], [[17, 18, 19, 20], [21, 22, 23, 24], [25, 26, 27, 28], [19, 30, 31, 32]], [[33 ,34, 35 ,36], [37, 38, 39, 40], [41, 42, 43, 44], [45, 46, 47, 48]], [[49, 50, 51, 52], [53, 54, 55, 56], [57, 58, 59, 60], [61, 62, 63 ,64]] ]]]; const x5by5by5Data = [[[ [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25] ], [ [26, 27, 28, 29, 30], [31, 32, 33, 34, 35], [36, 37, 38, 39, 40], [41, 42, 43, 44, 45], [46, 47, 48, 49, 50] ], [ [51, 52, 53, 54, 55], [56, 57, 58, 59, 60], [61, 62, 63, 64, 65], [66, 67, 68, 69, 70], [71, 72, 73, 74, 75] ], [ [76, 77, 78, 79, 80], [81, 82, 83, 84, 85], [86, 87, 88, 89, 90], [91, 92, 93, 94, 95], [96, 97, 98, 99, 100] ], [ [101, 102, 103, 104, 105], [106, 107, 108, 109, 110], [111, 112, 113, 114, 115], [116, 117, 118, 119, 120], [121, 122, 123, 124, 125] ] ]]]; const poolModes: PoolMode[] = [undefined, 'max', 'avg']; const dataFormats: DataFormat[] = [undefined, 'channelsFirst', 'channelsLast']; const stridesArray = [1, 2]; for (const poolMode of poolModes) { for (const dataFormat of dataFormats) { for (const stride of stridesArray) { const testTitle = `4x4x4, ${stride}, same, ${dataFormat}, ` + `${poolMode}`; it(testTitle, () => { let x: Tensor5D = tensor5d(x4by4by4Data, [1, 1, 4, 4, 4]); if (dataFormat !== 'channelsFirst') { x = tfc.transpose(x, [0, 2, 3, 4, 1]); // NDHWC -> NCDHW. } let yExpected: Tensor5D; if (poolMode === 'avg') { if (stride === 1) { yExpected = tensor5d( [[[ [ [11.5, 12.5, 13.5, 14], [15.5, 16.5, 17.5, 18], [18.25, 20.5, 21.5, 22], [19, 22.5, 23.5, 24] ], [ [27.5, 28.5, 29.5, 30], [31.5, 32.5, 33.5, 34], [34.25, 36.5, 37.5, 38], [35, 38.5, 39.5, 40] ], [ [43.5, 44.5, 45.5, 46], [47.5, 48.5, 49.5, 50], [51.5, 52.5, 53.5, 54], [53.5, 54.5, 55.5, 56] ], [ [51.5, 52.5, 53.5, 54], [55.5, 56.5, 57.5, 58], [59.5, 60.5, 61.5, 62], [61.5, 62.5, 63.5, 64]] ]]], [1, 1, 4, 4, 4]); } else { yExpected = tensor5d([[[[[11.5, 13.5], [18.25, 21.5]], [[43.5, 45.5], [51.5, 53.5]]]]], [1, 1, 2, 2, 2]); } } else { if (stride === 1) { yExpected = tensor5d( [[[ [ [22, 23, 24, 24], [26, 27, 28, 28], [30, 31, 32, 32], [30, 31, 32, 32] ], [ [38, 39, 40, 40], [42, 43, 44, 44], [46, 47, 48, 48], [46, 47, 48, 48] ], [ [54, 55, 56, 56], [58, 59, 60, 60], [62, 63, 64, 64], [62, 63, 64, 64] ], [ [54, 55, 56, 56], [58, 59, 60, 60], [62, 63, 64, 64], [62, 63, 64, 64]] ]]], [1, 1, 4, 4, 4]); } else if (stride === 2) { yExpected = tensor5d([[[[[22, 24], [30, 32]], [[54, 56], [62, 64]]]]], [1, 1, 2, 2, 2]); } } if (dataFormat !== 'channelsFirst') { yExpected = tfc.transpose(yExpected, [0, 2, 3, 4, 1]); } const y = pool3d(x, [2, 2, 2], [stride, stride, stride], 'same', dataFormat, poolMode); expectTensorsClose(y, yExpected as Tensor); }); } } } for (const poolMode of poolModes) { it(`5x5x5, 2, same, CHANNEL_FIRST, ${poolMode}`, () => { const x5by5by5 = tensor5d(x5by5by5Data, [1, 1, 5, 5, 5]); let yExpected: Tensor5D; if (poolMode === 'avg') { yExpected = tensor5d([[[ [[16.5, 18.5, 20], [26.5, 28.5, 30], [34, 36, 37.5]], [[66.5, 68.5, 70], [76.5, 78.5, 80], [84, 86, 87.5]], [[104, 106, 107.5], [114, 116, 117.5], [121.5, 123.5, 125]] ]]], [1, 1, 3, 3, 3]); } else { yExpected = tensor5d([[[ [[32, 34, 35], [42, 44, 45], [47, 49, 50]], [[82, 84, 85], [92, 94, 95], [97, 99, 100]], [[107, 109, 110], [117, 119, 120], [122, 124, 125]] ]]], [1, 1, 3, 3, 3]); } const y = pool3d(x5by5by5, [2, 2, 2], [2, 2, 2], 'same', 'channelsFirst', poolMode); expectTensorsClose(y, yExpected as Tensor); }); } for (const poolMode of poolModes) { it(`5x5x5, 2, valid, CHANNEL_LAST, ${poolMode}`, () => { const x5by5by5 = tfc.transpose( tensor5d(x5by5by5Data, [1, 1, 5, 5, 5]), [0, 2, 3, 4, 1]); let yExpected: Tensor5D; if (poolMode === 'avg') { yExpected = tensor5d( [[[[[16.5, 18.5], [26.5, 28.5]], [[66.5, 68.5], [76.5, 78.5]]]]], [1, 1, 2, 2, 2]); } else { yExpected = tensor5d( [[[[[32, 34], [42, 44]], [[82, 84], [92, 94]]]]], [1, 1, 2, 2, 2]); } const y = pool3d(x5by5by5, [2, 2, 2], [2, 2, 2], 'valid', 'channelsLast', poolMode); expectTensorsClose(y, tfc.transpose(yExpected, [0, 2, 3, 4, 1])); }); } }); describe('Pooling Layers 1D: Symbolic', () => { const poolSizes = [2, 3]; const stridesList = [null, 1, 2]; const poolModes: PoolMode[] = ['avg', 'max']; const paddingModes: PaddingMode[] = [undefined, 'valid', 'same']; for (const poolMode of poolModes) { for (const paddingMode of paddingModes) { for (const poolSize of poolSizes) { for (const strides of stridesList) { const testTitle = `poolSize=${poolSize}, ` + `${paddingMode}, ${poolMode}`; it(testTitle, () => { const inputLength = 16; const inputNumChannels = 11; const inputBatchSize = 2; const inputShape = [inputBatchSize, inputLength, inputNumChannels]; const symbolicInput = new SymbolicTensor('float32', inputShape, null, [], null); const poolConstructor = poolMode === 'avg' ? tfl.layers.averagePooling1d : tfl.layers.maxPooling1d; const poolingLayer = poolConstructor({ poolSize, strides, padding: paddingMode, }); const output = poolingLayer.apply(symbolicInput) as SymbolicTensor; const expectedOutputLength = convOutputLength( inputLength, poolSize, paddingMode, strides ? strides : poolSize); const expectedShape = [inputBatchSize, expectedOutputLength, inputNumChannels]; expect(output.shape).toEqual(expectedShape); expect(output.dtype).toEqual(symbolicInput.dtype); }); } } } } }); describeMathCPUAndGPU('Pooling Layers 1D: Tensor', () => { const poolModes = ['avg', 'max']; const strides = [2, 4]; const poolSizes = [2, 4]; const batchSize = 2; for (const poolMode of poolModes) { for (const stride of strides) { for (const poolSize of poolSizes) { const testTitle = `stride=${stride}, ${poolMode}, ` + `poolSize=${poolSize}`; it(testTitle, () => { const x2by8 = tensor2d([ [10, 30, 50, 70, 20, 40, 60, 80], [-10, -30, -50, -70, -20, -40, -60, -80] ]); const x2by8by1 = tfc.expandDims(x2by8, 2); const poolConstructor = poolMode === 'avg' ? tfl.layers.averagePooling1d : tfl.layers.maxPooling1d; const poolingLayer = poolConstructor({ poolSize, strides: stride, padding: 'valid', }); const output = poolingLayer.apply(x2by8by1) as Tensor; let outputLength: number; let expectedOutputVals: number[][][]; if (poolSize === 2) { if (stride === 2) { outputLength = 4; if (poolMode === 'avg') { expectedOutputVals = [[[20], [60], [30], [70]], [[-20], [-60], [-30], [-70]]]; } else { expectedOutputVals = [[[30], [70], [40], [80]], [[-10], [-50], [-20], [-60]]]; } } else if (stride === 4) { outputLength = 2; if (poolMode === 'avg') { expectedOutputVals = [[[20], [30]], [[-20], [-30]]]; } else { expectedOutputVals = [[[30], [40]], [[-10], [-20]]]; } } } else if (poolSize === 4) { if (stride === 2) { outputLength = 3; if (poolMode === 'avg') { expectedOutputVals = [[[40], [45], [50]], [[-40], [-45], [-50]]]; } else { expectedOutputVals = [[[70], [70], [80]], [[-10], [-20], [-20]]]; } } else if (stride === 4) { outputLength = 2; if (poolMode === 'avg') { expectedOutputVals = [[[40], [50]], [[-40], [-50]]]; } else { expectedOutputVals = [[[70], [80]], [[-10], [-20]]]; } } } const expectedShape: [number, number, number] = [batchSize, outputLength, 1]; expectTensorsClose( output, tensor3d(expectedOutputVals, expectedShape)); }); } } } it('Handles poolSize and strides passed as number arrays', async () => { const model = tfl.sequential(); model.add(tfl.layers.maxPool1d( {poolSize: [2], strides: [2], inputShape: [4, 3]})); const xs = tfc.ones([1, 4, 3]); const ys = model.predict(xs) as Tensor; expectTensorsClose(ys, [1, 1, 1, 1, 1, 1]); expect(ys.shape).toEqual([1, 2, 3]); const config = model.layers[0].getConfig(); expect(config['poolSize']).toEqual([2]); expect(config['strides']).toEqual([2]); }); }); describe('Pooling Layers 2D: Symbolic', () => { const poolSizes = [2, 3]; const poolModes = ['avg', 'max']; const paddingModes: PaddingMode[] = [undefined, 'valid', 'same']; const dataFormats: DataFormat[] = ['channelsFirst', 'channelsLast']; const poolSizeIsNumberValues = [false, true]; for (const poolMode of poolModes) { for (const paddingMode of paddingModes) { for (const dataFormat of dataFormats) { for (const poolSize of poolSizes) { for (const poolSizeIsNumber of poolSizeIsNumberValues) { const testTitle = `poolSize=${poolSize}, ` + `${dataFormat}, ${paddingMode}, ` + `${poolMode}, ` + `poollSizeIsNumber=${poolSizeIsNumber}`; it(testTitle, () => { const inputShape = dataFormat === 'channelsFirst' ? [2, 16, 11, 9] : [2, 11, 9, 16]; const symbolicInput = new SymbolicTensor('float32', inputShape, null, [], null); const poolConstructor = poolMode === 'avg' ? tfl.layers.averagePooling2d : tfl.layers.maxPooling2d; const poolingLayer = poolConstructor({ poolSize: poolSizeIsNumber ? poolSize : [poolSize, poolSize], padding: paddingMode, dataFormat, }); const output = poolingLayer.apply(symbolicInput) as SymbolicTensor; let outputRows = poolSize === 2 ? 5 : 3; if (paddingMode === 'same') { outputRows++; } let outputCols = poolSize === 2 ? 4 : 3; if (paddingMode === 'same' && poolSize === 2) { outputCols++; } let expectedShape: [number, number, number, number]; if (dataFormat === 'channelsFirst') { expectedShape = [2, 16, outputRows, outputCols]; } else { expectedShape = [2, outputRows, outputCols, 16]; } expect(output.shape).toEqual(expectedShape); expect(output.dtype).toEqual(symbolicInput.dtype); }); } } } } } const stridesValues: Array<number|[number, number]> = [1, [1, 1], [2, 1]]; for (const strides of stridesValues) { it(`custom strides: ${strides}`, () => { const inputShape = [2, 16, 11, 3]; const symbolicInput = new SymbolicTensor('float32', inputShape, null, [], null); const poolingLayer = tfl.layers.maxPooling2d({poolSize: [2, 2], strides}); const output = poolingLayer.apply(symbolicInput) as tfl.SymbolicTensor; if (Array.isArray(strides) && util.arraysEqual(strides, [1, 1])) { expect(output.shape).toEqual([2, 15, 10, 3]); } else if (Array.isArray(strides) && util.arraysEqual(strides, [2, 1])) { expect(output.shape).toEqual([2, 8, 10, 3]); } else { // strides = 1 expect(output.shape).toEqual([2, 15, 10, 3]); } }); } it('Incorrect strides array length leads to error', () => { // tslint:disable-next-line:no-any expect(() => tfl.layers.maxPooling2d({poolSize: 2, strides: [2]} as any)) .toThrowError(/expected to have a length of 2/); expect( // tslint:disable-next-line:no-any () => tfl.layers.maxPooling2d({poolSize: 2, strides: [2, 3, 3]} as any)) .toThrowError(/expected to have a length of 2/); }); it('Invalid poolSize', () => { expect(() => tfl.layers.maxPooling2d({poolSize: 2.5, strides: 2})) .toThrowError(/poolSize.*positive integer.*2\.5\.$/); expect(() => tfl.layers.maxPooling2d({poolSize: 0, strides: 2})) .toThrowError(/poolSize.*positive integer.*0\.$/); expect(() => tfl.layers.maxPooling2d({poolSize: -2, strides: 2})) .toThrowError(/poolSize.*positive integer.*-2\.$/); }); it('Invalid strides leads to Error', () => { expect(() => tfl.layers.maxPooling2d({poolSize: 3, strides: 2.5})) .toThrowError(/strides.*positive integer.*2\.5\.$/); expect(() => tfl.layers.maxPooling2d({poolSize: 3, strides: 0})) .toThrowError(/strides.*positive integer.*0\.$/); expect(() => tfl.layers.maxPooling2d({poolSize: 3, strides: -2})) .toThrowError(/strides.*positive integer.*-2\.$/); }); }); describeMathCPUAndGPU('Pooling Layers 2D: Tensor', () => { const x4by4Data = [10, 30, 50, 70, 20, 40, 60, 80, -10, -30, -50, -70, -20, -40, -60, -80]; const poolModes: PoolMode[] = ['avg', 'max']; const strides = [1, 2]; const batchSizes = [2, 4]; const channelsArray = [1, 3]; for (const poolMode of poolModes) { for (const stride of strides) { for (const batchSize of batchSizes) { for (const channels of channelsArray) { const testTitle = `stride=${stride}, ${poolMode}, ` + `batchSize=${batchSize}, channels=${channels}`; it(testTitle, () => { let xArrayData: number[] = []; for (let b = 0; b < batchSize; ++b) { for (let c = 0; c < channels; ++c) { xArrayData = xArrayData.concat(x4by4Data); } } const x4by4 = tensor4d(xArrayData, [batchSize, channels, 4, 4]); const poolConstructor = poolMode === 'avg' ? tfl.layers.averagePooling2d : tfl.layers.maxPooling2d; const poolingLayer = poolConstructor({ poolSize: [2, 2], strides: [stride, stride], padding: 'valid', dataFormat: 'channelsFirst', }); const output = poolingLayer.apply(x4by4) as Tensor; let expectedShape: [number, number, number, number]; let expectedOutputSlice: number[]; if (poolMode === 'avg') { if (stride === 1) { expectedShape = [batchSize, channels, 3, 3]; expectedOutputSlice = [25, 45, 65, 5, 5, 5, -25, -45, -65]; } else if (stride === 2) { expectedShape = [batchSize, channels, 2, 2]; expectedOutputSlice = [25, 65, -25, -65]; } } else { if (stride === 1) { expectedShape = [batchSize, channels, 3, 3]; expectedOutputSlice = [40, 60, 80, 40, 60, 80, -10, -30, -50]; } else if (stride === 2) { expectedShape = [batchSize, channels, 2, 2]; expectedOutputSlice = [40, 80, -10, -50]; } } let expectedOutputArray: number[] = []; for (let b = 0; b < batchSize; ++b) { for (let c = 0; c < channels; ++c) { expectedOutputArray = expectedOutputArray.concat(expectedOutputSlice); } } expectTensorsClose( output, tensor4d(expectedOutputArray, expectedShape)); }); } } } } it('Handles strides passed as number arrays', async () => { const model = tfl.sequential(); model.add(tfl.layers.maxPooling2d( {poolSize: 2, strides: [2, 2], inputShape: [4, 4, 3]})); const xs = tfc.ones([1, 4, 4, 3]); const ys = model.predict(xs) as Tensor; expectTensorsClose(ys, tfc.ones([1, 2, 2, 3])); expect(ys.shape).toEqual([1, 2, 2, 3]); const config = model.layers[0].getConfig(); expect(config['poolSize']).toEqual([2, 2]); expect(config['strides']).toEqual([2, 2]); }); }); describe('Pooling Layers 3D: Symbolic', () => { const poolSizes = [2, 3]; const poolModes = ['avg', 'max']; const paddingModes: PaddingMode[] = [undefined, 'valid', 'same']; const dataFormats: DataFormat[] = ['channelsFirst', 'channelsLast']; const poolSizeIsNumberValues = [false, true]; for (const poolMode of poolModes) { for (const paddingMode of paddingModes) { for (const dataFormat of dataFormats) { for (const poolSize of poolSizes) { for (const poolSizeIsNumber of poolSizeIsNumberValues) { const testTitle = `poolSize=${poolSize}, ` + `${dataFormat}, ${paddingMode}, ` + `${poolMode}, ` + `poollSizeIsNumber=${poolSizeIsNumber}`; it(testTitle, () => { const inputShape = dataFormat === 'channelsFirst' ? [2, 16, 11, 9, 7] : [2, 11, 9, 7, 16]; const symbolicInput = new SymbolicTensor('float32', inputShape, null, [], null); const poolConstructor = poolMode === 'avg' ? tfl.layers.averagePooling3d : tfl.layers.maxPooling3d; const poolingLayer = poolConstructor({ poolSize: poolSizeIsNumber ? poolSize : [poolSize, poolSize, poolSize], padding: paddingMode, dataFormat, }); const output = poolingLayer.apply(symbolicInput) as SymbolicTensor; let outputDepths = poolSize === 2 ? 5: 3; if (paddingMode === 'same') { outputDepths++; } let outputRows = poolSize === 2 ? 4 : 3; if (paddingMode === 'same' && poolSize === 2) { outputRows++; } let outputCols = poolSize === 2 ? 3 : 2; if (paddingMode === 'same') { outputCols++; } let expectedShape: [number, number, number, number, number]; if (dataFormat === 'channelsFirst') { expectedShape = [2, 16, outputDepths, outputRows, outputCols]; } else { expectedShape = [2, outputDepths, outputRows, outputCols, 16]; } expect(output.shape).toEqual(expectedShape); expect(output.dtype).toEqual(symbolicInput.dtype); }); } } } } } const stridesValues: Array<number|[number, number, number]> = [1, [1, 1, 1], [2, 1, 2]]; for (const strides of stridesValues) { it(`custom strides: ${strides}`, () => { const inputShape = [2, 16, 11, 15, 3]; const symbolicInput = new SymbolicTensor('float32', inputShape, null, [], null); const poolingLayer = tfl.layers.maxPooling3d({poolSize: [2, 2, 2], strides}); const output = poolingLayer.apply(symbolicInput) as tfl.SymbolicTensor; if (Array.isArray(strides) && util.arraysEqual(strides, [1, 1, 1])) { expect(output.shape).toEqual([2, 15, 10, 14, 3]); } else if (Array.isArray(strides) && util.arraysEqual(strides, [2, 1, 2])) { expect(output.shape).toEqual([2, 8, 10, 7, 3]); } else { // strides = 1 expect(output.shape).toEqual([2, 15, 10, 14, 3]); } }); } it('Incorrect strides array length leads to error', () => { // tslint:disable-next-line:no-any expect(() => tfl.layers.maxPooling3d({poolSize: 2, strides: [2]} as any)) .toThrowError(/expected to have a length of 3/); expect( // tslint:disable-next-line:no-any () => tfl.layers.maxPooling3d({poolSize: 2, strides: [2, 3]} as any)) .toThrowError(/expected to have a length of 3/); expect(() => tfl.layers.averagePooling3d( // tslint:disable-next-line:no-any {poolSize: 2, strides: [2]} as any)) .toThrowError(/expected to have a length of 3/); expect(() => tfl.layers.averagePooling3d( // tslint:disable-next-line:no-any {poolSize: 2, strides: [2, 3]} as any)) .toThrowError(/expected to have a length of 3/); }); it('Invalid poolSize', () => { expect(() => tfl.layers.maxPooling3d({poolSize: 2.5, strides: 2})) .toThrowError(/poolSize.*positive integer.*2\.5\.$/); expect(() => tfl.layers.maxPooling3d({poolSize: 0, strides: 2})) .toThrowError(/poolSize.*positive integer.*0\.$/); expect(() => tfl.layers.maxPooling3d({poolSize: -2, strides: 2})) .toThrowError(/poolSize.*positive integer.*-2\.$/); expect(() => tfl.layers.averagePooling3d({poolSize: 2.5, strides: 2})) .toThrowError(/poolSize.*positive integer.*2\.5\.$/); expect(() => tfl.layers.averagePooling3d({poolSize: 0, strides: 2})) .toThrowError(/poolSize.*positive integer.*0\.$/); expect(() => tfl.layers.averagePooling3d({poolSize: -2, strides: 2})) .toThrowError(/poolSize.*positive integer.*-2\.$/); }); it('Invalid strides leads to Error', () => { expect(() => tfl.layers.maxPooling3d({poolSize: 3, strides: 2.5})) .toThrowError(/strides.*positive integer.*2\.5\.$/); expect(() => tfl.layers.maxPooling3d({poolSize: 3, strides: 0})) .toThrowError(/strides.*positive integer.*0\.$/); expect(() => tfl.layers.maxPooling3d({poolSize: 3, strides: -2})) .toThrowError(/strides.*positive integer.*-2\.$/); expect(() => tfl.layers.averagePooling3d({poolSize: 3, strides: 2.5})) .toThrowError(/strides.*positive integer.*2\.5\.$/); expect(() => tfl.layers.averagePooling3d({poolSize: 3, strides: 0})) .toThrowError(/strides.*positive integer.*0\.$/); expect(() => tfl.layers.averagePooling3d({poolSize: 3, strides: -2})) .toThrowError(/strides.*positive integer.*-2\.$/); }); }); describeMathCPUAndGPU('Pooling Layers 3D: Tensor', () => { const x4by4by4Data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64]; const poolModes: PoolMode[] = ['avg', 'max']; const strides = [1, 2]; const batchSizes = [2, 4]; const channelsArray = [1, 3]; for (const poolMode of poolModes) { for (const stride of strides) { for (const batchSize of batchSizes) { for (const channels of channelsArray) { const testTitle = `stride=${stride}, ${poolMode}, ` + `batchSize=${batchSize}, channels=${channels}`; it(testTitle, () => { let xArrayData: number[] = []; for (let b = 0; b < batchSize; ++b) { for (let c = 0; c < channels; ++c) { xArrayData = xArrayData.concat(x4by4by4Data); } } const x4by4by4 = tensor5d(xArrayData, [batchSize, channels, 4, 4, 4]); const poolConstructor = poolMode === 'avg' ? tfl.layers.averagePooling3d : tfl.layers.maxPooling3d; const poolingLayer = poolConstructor({ poolSize: [2, 2, 2], strides: [stride, stride, stride], padding: 'valid', dataFormat: 'channelsFirst', }); const output = poolingLayer.apply(x4by4by4 as Tensor) as Tensor; let expectedShape: [number, number, number, number, number]; let expectedOutputSlice: number[]; if (poolMode === 'avg') { if (stride === 1) { expectedShape = [batchSize, channels, 3, 3, 3]; expectedOutputSlice = [11.5, 12.5, 13.5, 15.5, 16.5, 17.5, 19.5, 20.5, 21.5, 27.5, 28.5, 29.5, 31.5, 32.5, 33.5, 35.5, 36.5, 37.5, 43.5, 44.5, 45.5, 47.5, 48.5, 49.5, 51.5, 52.5, 53.5]; } else if (stride === 2) { expectedShape = [batchSize, channels, 2, 2, 2]; expectedOutputSlice = [11.5, 13.5, 19.5, 21.5, 43.5, 45.5, 51.5, 53.5]; } } else { if (stride === 1) { expectedShape = [batchSize, channels, 3, 3, 3]; expectedOutputSlice = [22, 23, 24, 26, 27, 28, 30, 31, 32, 38, 39, 40, 42, 43, 44, 46, 47, 48, 54, 55, 56, 58, 59, 60, 62, 63, 64]; } else if (stride === 2) { expectedShape = [batchSize, channels, 2, 2, 2]; expectedOutputSlice = [22, 24, 30, 32, 54, 56, 62, 64]; } } let expectedOutputArray: number[] = []; for (let b = 0; b < batchSize; ++b) { for (let c = 0; c < channels; ++c) { expectedOutputArray = expectedOutputArray.concat(expectedOutputSlice); } } expectTensorsClose(output, tensor5d(expectedOutputArray, expectedShape) as Tensor); }); } } } } }); describe('1D Global pooling Layers: Symbolic', () => { const globalPoolingLayers = [tfl.layers.globalAveragePooling1d, tfl.layers.globalMaxPooling1d]; for (const globalPoolingLayer of globalPoolingLayers) { for (const hasArgs of [true, false]) { const testTitle = `layer=${globalPoolingLayer.name}; hasArgs=${hasArgs}`; it(testTitle, () => { const inputShape = [2, 11, 9]; const symbolicInput = new SymbolicTensor('float32', inputShape, null, [], null); const layer = globalPoolingLayer(hasArgs ? {} : undefined); const output = layer.apply(symbolicInput) as SymbolicTensor; const expectedShape = [2, 9]; expect(output.shape).toEqual(expectedShape); expect(output.dtype).toEqual(symbolicInput.dtype); }); } } it('Invalid poolSize', () => { expect(() => tfl.layers.avgPooling1d({ poolSize: 2.5 })).toThrowError(/poolSize.*positive integer.*2\.5/); expect(() => tfl.layers.avgPooling1d({ poolSize: 0 })).toThrowError(/poolSize.*positive integer.*0\.$/); expect(() => tfl.layers.avgPooling1d({ poolSize: -3 })).toThrowError(/poolSize.*positive integer.*-3\.$/); }); it('Invalid strides leads to Error', () => { expect(() => tfl.layers.avgPooling1d({poolSize: 3, strides: 4.5})) .toThrowError(/strides.*positive integer.*4\.5\.$/); }); }); describeMathCPUAndGPU('1D Global Pooling Layers: Tensor', () => { const x3DimData = [ [[4, -1], [0, -2], [40, -10], [0, -20]], [[-4, 1], [0, 2], [-40, 10], [0, 20]] ]; const globalPoolingLayers = [tfl.layers.globalAveragePooling1d, tfl.layers.globalMaxPooling1d]; for (const globalPoolingLayer of globalPoolingLayers) { const testTitle = `globalPoolingLayer=${globalPoolingLayer.name}`; it(testTitle, () => { const x = tensor3d(x3DimData, [2, 4, 2]); const layer = globalPoolingLayer({}); const output = layer.apply(x) as Tensor; let expectedOutput: Tensor2D; if (globalPoolingLayer === tfl.layers.globalAveragePooling1d) { expectedOutput = tensor2d([[11, -8.25], [-11, 8.25]], [2, 2]); } else { expectedOutput = tensor2d([[40, -1], [0, 20]], [2, 2]); } expectTensorsClose(output, expectedOutput); }); } }); describe('2D Global pooling Layers: Symbolic', () => { const globalPoolingLayers = [tfl.layers.globalAveragePooling2d, tfl.layers.globalMaxPooling2d]; const dataFormats: DataFormat[] = ['channelsFirst', 'channelsLast']; for (const globalPoolingLayer of globalPoolingLayers) { for (const dataFormat of dataFormats) { const testTitle = `layer=${globalPoolingLayer.name}, ${dataFormat}`; it(testTitle, () => { const inputShape = [2, 16, 11, 9]; const symbolicInput = new SymbolicTensor('float32', inputShape, null, [], null); const layer = globalPoolingLayer({dataFormat}); const output = layer.apply(symbolicInput) as SymbolicTensor; const expectedShape = dataFormat === 'channelsLast' ? [2, 9] : [2, 16]; expect(output.shape).toEqual(expectedShape); expect(output.dtype).toEqual(symbolicInput.dtype); }); } } }); describeMathCPUAndGPU('2D Global Pooling Layers: Tensor', () => { const x4DimData = [ [[[4, -1], [0, -2]], [[40, -10], [0, -20]]], [[[4, -1], [0, -2]], [[40, -10], [0, -20]]] ]; const dataFormats: DataFormat[] = ['channelsFirst', 'channelsLast']; const globalPoolingLayers = [tfl.layers.globalAveragePooling2d, tfl.layers.globalMaxPooling2d]; for (const globalPoolingLayer of globalPoolingLayers) { for (const dataFormat of dataFormats) { const testTitle = `globalPoolingLayer=${globalPoolingLayer.name}, ${dataFormat}`; it(testTitle, () => { const x = tensor4d(x4DimData, [2, 2, 2, 2]); const layer = globalPoolingLayer({dataFormat}); const output = layer.apply(x) as Tensor; let expectedOutput: Tensor2D; if (globalPoolingLayer === tfl.layers.globalAveragePooling2d) { if (dataFormat === 'channelsFirst') { expectedOutput = tensor2d([[0.25, 2.5], [0.25, 2.5]], [2, 2]); } else { expectedOutput = tensor2d([[11, -8.25], [11, -8.25]], [2, 2]); } } else { if (dataFormat === 'channelsFirst') { expectedOutput = tensor2d([[4, 40], [4, 40]], [2, 2]); } else { expectedOutput = tensor2d([[40, -1], [40, -1]], [2, 2]); } } expectTensorsClose(output, expectedOutput); const config = layer.getConfig(); expect(config.dataFormat).toEqual(dataFormat); }); } } });
the_stack
import sinon = require('sinon') const chai = require('chai') const sinonChai = require('sinon-chai') const expect = chai.expect chai.use(sinonChai) const cache = require('../../data/datacache') const security = require('../../lib/insecurity') const config = require('config') const utils = require('../../lib/utils') describe('verify', () => { const verify = require('../../routes/verify') const challenges = require('../../data/datacache').challenges let req: any let res: any let next: any let save: any let err: any beforeEach(() => { req = { body: {}, headers: {} } res = { json: sinon.spy() } next = sinon.spy() save = () => ({ then () { } }) }) describe('"forgedFeedbackChallenge"', () => { beforeEach(() => { security.authenticatedUsers.put('token12345', { data: { id: 42, email: 'test@juice-sh.op' } }) challenges.forgedFeedbackChallenge = { solved: false, save: save } }) it('is not solved when an authenticated user passes his own ID when writing feedback', () => { req.body.UserId = 42 req.headers = { authorization: 'Bearer token12345' } verify.forgedFeedbackChallenge()(req, res, next) expect(challenges.forgedFeedbackChallenge.solved).to.equal(false) }) it('is not solved when an authenticated user passes no ID when writing feedback', () => { req.body.UserId = undefined req.headers = { authorization: 'Bearer token12345' } verify.forgedFeedbackChallenge()(req, res, next) expect(challenges.forgedFeedbackChallenge.solved).to.equal(false) }) it('is solved when an authenticated user passes someone elses ID when writing feedback', () => { req.body.UserId = 1 req.headers = { authorization: 'Bearer token12345' } verify.forgedFeedbackChallenge()(req, res, next) expect(challenges.forgedFeedbackChallenge.solved).to.equal(true) }) it('is solved when an unauthenticated user passes someones ID when writing feedback', () => { req.body.UserId = 1 req.headers = {} verify.forgedFeedbackChallenge()(req, res, next) expect(challenges.forgedFeedbackChallenge.solved).to.equal(true) }) }) describe('accessControlChallenges', () => { it('"scoreBoardChallenge" is solved when the 1px.png transpixel is requested', () => { challenges.scoreBoardChallenge = { solved: false, save: save } req.url = 'http://juice-sh.op/public/images/padding/1px.png' verify.accessControlChallenges()(req, res, next) expect(challenges.scoreBoardChallenge.solved).to.equal(true) }) it('"adminSectionChallenge" is solved when the 19px.png transpixel is requested', () => { challenges.adminSectionChallenge = { solved: false, save: save } req.url = 'http://juice-sh.op/public/images/padding/19px.png' verify.accessControlChallenges()(req, res, next) expect(challenges.adminSectionChallenge.solved).to.equal(true) }) it('"tokenSaleChallenge" is solved when the 56px.png transpixel is requested', () => { challenges.tokenSaleChallenge = { solved: false, save: save } req.url = 'http://juice-sh.op/public/images/padding/56px.png' verify.accessControlChallenges()(req, res, next) expect(challenges.tokenSaleChallenge.solved).to.equal(true) }) it('"extraLanguageChallenge" is solved when the Klingon translation file is requested', () => { challenges.extraLanguageChallenge = { solved: false, save: save } req.url = 'http://juice-sh.op/public/i18n/tlh_AA.json' verify.accessControlChallenges()(req, res, next) expect(challenges.extraLanguageChallenge.solved).to.equal(true) }) it('"retrieveBlueprintChallenge" is solved when the blueprint file is requested', () => { challenges.retrieveBlueprintChallenge = { solved: false, save: save } cache.retrieveBlueprintChallengeFile = 'test.dxf' req.url = 'http://juice-sh.op/public/images/products/test.dxf' verify.accessControlChallenges()(req, res, next) expect(challenges.retrieveBlueprintChallenge.solved).to.equal(true) }) it('"missingEncodingChallenge" is solved when the crazy cat photo is requested', () => { challenges.missingEncodingChallenge = { solved: false, save: save } req.url = 'http://juice-sh.op/public/images/uploads/%F0%9F%98%BC-%23zatschi-%23whoneedsfourlegs-1572600969477.jpg' verify.accessControlChallenges()(req, res, next) expect(challenges.missingEncodingChallenge.solved).to.equal(true) }) it('"accessLogDisclosureChallenge" is solved when any server access log file is requested', () => { challenges.accessLogDisclosureChallenge = { solved: false, save: save } req.url = 'http://juice-sh.op/support/logs/access.log.2019-01-15' verify.accessControlChallenges()(req, res, next) expect(challenges.accessLogDisclosureChallenge.solved).to.equal(true) }) }) describe('"errorHandlingChallenge"', () => { beforeEach(() => { challenges.errorHandlingChallenge = { solved: false, save: save } }) it('is solved when an error occurs on a response with OK 200 status code', () => { res.statusCode = 200 err = new Error() verify.errorHandlingChallenge()(err, req, res, next) expect(challenges.errorHandlingChallenge.solved).to.equal(true) }) describe('is solved when an error occurs on a response with error', () => { const httpStatus = [402, 403, 404, 500] httpStatus.forEach(statusCode => { it(`${statusCode} status code`, () => { res.statusCode = statusCode err = new Error() verify.errorHandlingChallenge()(err, req, res, next) expect(challenges.errorHandlingChallenge.solved).to.equal(true) }) }) }) it('is not solved when no error occurs on a response with OK 200 status code', () => { res.statusCode = 200 err = undefined verify.errorHandlingChallenge()(err, req, res, next) expect(challenges.errorHandlingChallenge.solved).to.equal(false) }) describe('is not solved when no error occurs on a response with error', () => { const httpStatus = [401, 402, 404, 500] httpStatus.forEach(statusCode => { it(`${statusCode} status code`, () => { res.statusCode = statusCode err = undefined verify.errorHandlingChallenge()(err, req, res, next) expect(challenges.errorHandlingChallenge.solved).to.equal(false) }) }) }) it('should pass occured error on to next route', () => { res.statusCode = 500 err = new Error() verify.errorHandlingChallenge()(err, req, res, next) expect(next).to.have.been.calledWith(err) }) }) describe('databaseRelatedChallenges', () => { describe('"changeProductChallenge"', () => { const products = require('../../data/datacache').products beforeEach(() => { challenges.changeProductChallenge = { solved: false, save: save } products.osaft = { reload () { return { then (cb: any) { cb() } } } } }) it(`is solved when the link in the O-Saft product goes to ${config.get('challenges.overwriteUrlForProductTamperingChallenge')}`, () => { products.osaft.description = `O-Saft, yeah! <a href="${config.get('challenges.overwriteUrlForProductTamperingChallenge')}" target="_blank">More...</a>` verify.databaseRelatedChallenges()(req, res, next) expect(challenges.changeProductChallenge.solved).to.equal(true) }) it('is not solved when the link in the O-Saft product is changed to an arbitrary URL', () => { products.osaft.description = 'O-Saft, nooo! <a href="http://arbitrary.url" target="_blank">More...</a>' verify.databaseRelatedChallenges()(req, res, next) expect(challenges.changeProductChallenge.solved).to.equal(false) }) it('is not solved when the link in the O-Saft product remained unchanged', () => { let urlForProductTamperingChallenge = null for (const product of config.products) { if (product.urlForProductTamperingChallenge !== undefined) { urlForProductTamperingChallenge = product.urlForProductTamperingChallenge break } } products.osaft.description = `Vanilla O-Saft! <a href="${urlForProductTamperingChallenge}" target="_blank">More...</a>` verify.databaseRelatedChallenges()(req, res, next) expect(challenges.changeProductChallenge.solved).to.equal(false) }) }) }) describe('jwtChallenges', () => { beforeEach(() => { challenges.jwtUnsignedChallenge = { solved: false, save: save } challenges.jwtForgedChallenge = { solved: false, save: save } }) it('"jwtUnsignedChallenge" is solved when forged unsigned token has email jwtn3d@juice-sh.op in the payload', () => { /* Header: { "alg": "none", "typ": "JWT" } Payload: { "data": { "email": "jwtn3d@juice-sh.op" }, "iat": 1508639612, "exp": 9999999999 } */ req.headers = { authorization: 'Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJkYXRhIjp7ImVtYWlsIjoiand0bjNkQGp1aWNlLXNoLm9wIn0sImlhdCI6MTUwODYzOTYxMiwiZXhwIjo5OTk5OTk5OTk5fQ.' } verify.jwtChallenges()(req, res, next) expect(challenges.jwtUnsignedChallenge.solved).to.equal(true) }) it('"jwtUnsignedChallenge" is solved when forged unsigned token has string "jwtn3d@" in the payload', () => { /* Header: { "alg": "none", "typ": "JWT" } Payload: { "data": { "email": "jwtn3d@" }, "iat": 1508639612, "exp": 9999999999 } */ req.headers = { authorization: 'Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJkYXRhIjp7ImVtYWlsIjoiand0bjNkQCJ9LCJpYXQiOjE1MDg2Mzk2MTIsImV4cCI6OTk5OTk5OTk5OX0.' } verify.jwtChallenges()(req, res, next) expect(challenges.jwtUnsignedChallenge.solved).to.equal(true) }) it('"jwtUnsignedChallenge" is not solved via regularly signed token even with email jwtn3d@juice-sh.op in the payload', () => { const token = security.authorize({ data: { email: 'jwtn3d@juice-sh.op' } }) req.headers = { authorization: `Bearer ${token}` } verify.jwtChallenges()(req, res, next) expect(challenges.jwtForgedChallenge.solved).to.equal(false) }) if (!utils.disableOnWindowsEnv()) { it('"jwtForgedChallenge" is solved when forged token HMAC-signed with public RSA-key has email rsa_lord@juice-sh.op in the payload', () => { /* Header: { "alg": "HS256", "typ": "JWT" } Payload: { "data": { "email": "rsa_lord@juice-sh.op" }, "iat": 1508639612, "exp": 9999999999 } */ req.headers = { authorization: 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7ImVtYWlsIjoicnNhX2xvcmRAanVpY2Utc2gub3AifSwiaWF0IjoxNTgyMjIxNTc1fQ.ycFwtqh4ht4Pq9K5rhiPPY256F9YCTIecd4FHFuSEAg' } verify.jwtChallenges()(req, res, next) expect(challenges.jwtForgedChallenge.solved).to.equal(true) }) it('"jwtForgedChallenge" is solved when forged token HMAC-signed with public RSA-key has string "rsa_lord@" in the payload', () => { /* Header: { "alg": "HS256", "typ": "JWT" } Payload: { "data": { "email": "rsa_lord@" }, "iat": 1508639612, "exp": 9999999999 } */ req.headers = { authorization: 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7ImVtYWlsIjoicnNhX2xvcmRAIn0sImlhdCI6MTU4MjIyMTY3NX0.50f6VAIQk2Uzpf3sgH-1JVrrTuwudonm2DKn2ec7Tg8' } verify.jwtChallenges()(req, res, next) expect(challenges.jwtForgedChallenge.solved).to.equal(true) }) it('"jwtForgedChallenge" is not solved when token regularly signed with private RSA-key has email rsa_lord@juice-sh.op in the payload', () => { const token = security.authorize({ data: { email: 'rsa_lord@juice-sh.op' } }) req.headers = { authorization: `Bearer ${token}` } verify.jwtChallenges()(req, res, next) expect(challenges.jwtForgedChallenge.solved).to.equal(false) }) } }) })
the_stack
import { WcListFilterHandler } from '../types/util'; import { MpStackInfo } from '../types/common'; import { WeConsoleScope } from '../types/scope'; export const now = (() => { let p; return (): number => { if (!p) { p = typeof performance !== 'undefined' && 'now' in performance ? performance : Date; } return p.now(); }; })(); export const getGlobal = (() => { let res; return (): any => { if (res) { return res; } if (typeof global === 'object' && global) { res = global; } else if (typeof globalThis === 'object' && globalThis) { res = globalThis; // eslint-disable-next-line @typescript-eslint/no-invalid-this } else if (typeof this === 'object' && this) { // eslint-disable-next-line @typescript-eslint/no-invalid-this res = this; } else if (typeof wx === 'object' && wx) { (wx as any).__wcGlobal__ = wx.__wcGlobal__ || {}; res = wx.__wcGlobal__; } else if (typeof getApp === 'function') { const app = getApp({ allowDefault: true }); app.__wcGlobal__ = app.__wcGlobal__ || {}; res = app.__wcGlobal__; } else { res = {}; } return res; }; })(); export const wcScope = (): WeConsoleScope => { const G = getGlobal(); if (!G.WeConsoleScope) { Object.defineProperty(G, 'WeConsoleScope', { configurable: false, enumerable: true, writable: false, value: {} }); } return G.WeConsoleScope; }; export const wcScopeSingle = (() => { const G = wcScope(); if (!G.SingleMapPromise) { G.SingleMapPromise = {}; } return <T = any>(name: string, creater?: Function): undefined | T | Promise<T> => { if (!G.SingleMap) { G.SingleMap = {}; } if (!(name in G.SingleMap) && creater) { G.SingleMap[name] = creater(); } if (name in G.SingleMap) { if (G.SingleMapPromise[name]) { G.SingleMapPromise[name].forEach((item) => item(G.SingleMap[name])); delete G.SingleMapPromise[name]; } return G.SingleMap[name]; } return new Promise((resolve) => { if (!G.SingleMapPromise[name]) { G.SingleMapPromise[name] = []; } G.SingleMapPromise[name].push(resolve); }); }; })(); export const isMpViewEvent = (obj) => typeof obj === 'object' && obj && 'type' in obj && obj.type && 'currentTarget' in obj && obj.currentTarget; // const STACK_TRACE = '$$$trace_stack$$$'; export const $$getStack = (): MpStackInfo[] => { return []; /* const res: MpStackInfo[] = []; try { throw new Error(STACK_TRACE); } catch (error) { const stack = (error as Error).stack || ''; if (stack) { stack.split('\n').forEach((item, index) => { if (item.indexOf(STACK_TRACE) === -1 && item.indexOf('$$getStack') === -1) { const stack: MpStackInfo = { original: item, target: '' }; item = item.trim(); let file = ''; let target = ''; const hasReal = item.indexOf(']'); if (hasReal !== -1) { const before = item.substr(0, hasReal).split('['); stack.method = before[1].split(' ')[1]; const arr = before[0].split(' '); target = arr[1]; file = item.substr(hasReal + 1).trim(); } else { const arr = item.split(' '); if (arr.length > 1) { if (arr[1].startsWith('http')) { file = `(${arr[1]})`; } else { target = arr[1]; file = arr[2]; } } } if (target) { stack.target = target; stack.ascription = target.substr(0, target.lastIndexOf('.')); const method = target.substr(target.lastIndexOf('.') + 1); if (!(method === '<computed>' && stack.method)) { stack.method = method; } } if (file && file.startsWith('(')) { let fileName: string, lineNumebr: string, column: string; let arr = file.split('.js'); if (arr.length > 1) { fileName = arr[0] + '.js'; if (arr[1] && arr[1].startsWith(':')) { arr = arr[1].substr(1).split(':'); lineNumebr = arr[0]; column = arr[1]; } } else { fileName = arr[0]; } stack.fileName = fileName.substr(1); if (lineNumebr) { stack.lineNumebr = parseInt(lineNumebr); if (isNaN(stack.lineNumebr)) { delete stack.lineNumebr; } } if (column) { column = column.substr(0, column.length - 1); stack.column = parseInt(column); if (isNaN(stack.column)) { delete stack.column; } } } res.push(stack); } }); } } return res; */ }; let errount = 0; export const log = (type = 'log', ...args) => { if (type === 'error' && (typeof args[0] === 'object' ? args[0].message : String(args[0])).indexOf('max') !== 0) { errount++; if (errount > 3) { return; } } if ((console as any).org && (console as any).org[type]) { return (console as any).org[type].apply(null, args); } return console[type].apply(console, args); }; export const FILTER_BREAK = Symbol('break'); export const filter = <T = any>(list: T[], filter: WcListFilterHandler<T>): T[] => { const res: T[] = []; for (let len = list.length, i = 0; i < len; i++) { const temp = filter(list[i], i, list); if (temp) { res.push(list[i]); } if (temp === FILTER_BREAK) { break; } } return res; }; export const hookApiMethodCallback = (apiName: string, onSuccess: Function, onFail: Function, args: any[]) => { if (!apiName.endsWith('Sync') && (!args.length || args[0] === null)) { args[0] = {}; } if (typeof args[0] === 'object' && args[0]) { const { success, fail } = args[0]; args[0].success = function HookApiSuccessCallback(...params) { onSuccess(...params); return success?.apply(this, params); }; args[0].fail = function HookApiFailCallback(...params) { onFail(...params); return fail?.apply(this, params); }; } return args; }; export const toHump = (name: string): string => { name = name.replace(/_(\w)/g, (all, letter) => { return letter.toUpperCase(); }); name = name.replace(/-(\w)/g, (all, letter) => { return letter.toUpperCase(); }); return name; }; export const promiseifyApi = (apiName: string, ...apiArgs: any[]): Promise<any> => { return new Promise((resolve, reject) => { const apiVar = wx; if (typeof apiVar[apiName] === 'function') { hookApiMethodCallback( apiName, (...args) => { if (args.length < 2) { resolve(args[0]); } else { resolve(args); } }, (...args) => { const err = new Error('未知错误'); if (args.length < 2 && args[0] && args[0].errMsg) { err.message = args[0].errMsg; } (err as any).failResult = args; reject(err); }, apiArgs ); if (apiName.indexOf('Sync') === -1) { const apiOptions = apiArgs[0]; const res = apiVar[apiName](apiOptions); if (res && apiOptions && typeof apiOptions.onResultReady === 'function') { apiOptions.onResultReady(res); } } else { try { const res = apiVar[apiName](apiArgs); resolve(res); } catch (error) { reject(error); } } } else { resolve(apiVar[apiName]); } }); }; export const getMpViewType = (obj: any): 'App' | 'Page' | 'Component' | undefined => { if (('route' in obj || '__route__' in obj) && 'setData' in obj) { return 'Page'; } if ('triggerEvent' in obj && 'setData' in obj) { return 'Component'; } if (typeof getApp === 'function' && getApp() === obj) { return 'App'; } }; const _has = Object.prototype.hasOwnProperty; export const has = (obj: any, prop: string): boolean => _has.call(obj, prop); export const EACH_BREAK = Symbol('EACH_BREAK'); export const each = (obj: any, handler: Function) => { if ( Array.isArray(obj) || (obj && 'length' in obj && typeof obj.length === 'number' && parseInt(obj.length) === obj.length) ) { for (let i = 0, len = obj.length; i < len; i++) { if (has(obj, String(i))) { const res = handler(i, obj[i]); if (res === EACH_BREAK) { break; } } } return; } if (typeof obj === 'object' && obj) { for (const prop in obj) { if (has(obj, prop)) { const res = handler(prop, obj[prop]); if (res === EACH_BREAK) { break; } } } } };
the_stack
import { Component } from 'react'; import { ViewProps, NativeSyntheticEvent } from 'react-native'; export type EasingType = | 'Linear' | 'EaseInQuad' | 'EaseOutQuad' | 'EaseInOutQuad' | 'EaseInCubic' | 'EaseOutCubic' | 'EaseInOutCubic' | 'EaseInQuart' | 'EaseOutQuart' | 'EaseInOutQuart' | 'EaseInSine' | 'EaseOutSine' | 'EaseInOutSine' | 'EaseInExpo' | 'EaseOutExpo' | 'EaseInOutExpo' | 'EaseInCirc' | 'EaseOutCirc' | 'EaseInOutCirc' | 'EaseInElastic' | 'EaseOutElastic' | 'EaseInOutElastic' | 'EaseInBack' | 'EaseOutBack' | 'EaseInOutBack' | 'EaseInBounce' | 'EaseOutBounce' | 'EaseInOutBounce'; /** * use `processColor` from `react-native` to generate the corrsponding number from a color (named, hex, rgba, etc.). */ export type Color = number; export type ValueFormatter = ('largeValue' | 'percent' | 'date') | string | string[]; export type AxisDependency = 'LEFT' | 'RIGHT'; export interface ChartDescription { text?: string; textColor?: Color; textSize?: number; positionX?: number; positionY?: number; } export interface ChartLegend { enabled?: boolean; textColor?: Color; textSize?: number; fontFamily?: string; fontStyle?: number; fontWeight?: number; wordWrapEnabled?: boolean; maxSizePercent?: number; horizontalAlignment?: 'LEFT' | 'CENTER' | 'RIGHT'; verticalAlignment?: 'TOP' | 'CENTER' | 'BOTTOM'; orientation?: 'HORIZONTAL' | 'VERTICAL'; drawInside?: boolean; direction?: 'LEFT_TO_RIGHT' | 'RIGHT_TO_LEFT'; form?: 'NONE' | 'EMPTY' | 'DEFAULT' | 'SQUARE' | 'CIRCLE' | 'LINE'; formSize?: number; xEntrySpace?: number; yEntrySpace?: number; formToTextSpace?: number; custom?: { colors?: Color[]; labels?: string[]; }; } export interface Axis { enabled?: boolean; drawLabels?: boolean; drawAxisLines?: boolean; drawGridLines?: boolean; textColor?: Color; textSize?: number; fontFamily?: string; fontStyle?: string; fontWeight?: number; gridColor?: Color; gridLineWidth?: number; axisLineColor?: Color; axisLineWidth?: number; gridDashedLine?: { lineLength?: number; spaceLength?: number; phase?: number; }; limitLines?: Array<{ limit: number; label?: string; lineColor?: Color; lineWidth?: number; valueTextColor?: Color; valueFont?: string; labelPosition?: 'LEFT_TOP' | 'LEFT_BOTTOM' | 'RIGHT_TOP' | 'RIGHT_BOTTOM'; lineDashPhase?: number; lineDashLengths?: number[]; }>; drawLimitLinesBehindData?: boolean; axisMaximum?: number; axisMinimum?: number; granularity?: number; granularityEnabled?: boolean; labelCount?: number; labelCountForce?: boolean; centerAxisLabels?: boolean; valueFormatter?: ValueFormatter; valueFormatterPattern?: string; since?: number; timeUnit?: 'MILLISECONDS' | 'SECONDS' | 'MINUTES' | 'HOURS' | 'DAYS'; } export interface xAxis extends Axis { labelRotationAngle?: number; avoidFirstLastClipping?: boolean; position?: 'TOP' | 'BOTTOM' | 'BOTH_SIDED' | 'TOP_INSIDE' | 'BOTTOM_INSIDE'; yOffset?: number; } export interface yAxis extends Axis { inverted?: boolean; spaceTop?: number; spaceBottom?: number; position?: 'OUTSIDE_CHART' | 'INSIDE_CHART'; maxWidth?: number; minWidth?: number; zeroLine?: { enabled?: boolean; lineWidth?: number; lineColor?: Color; }; } export interface Offsets { top?: number; left?: number; bottom?: number; right?: number; } export interface ChartBase extends ViewProps { animation?: { durationX?: number; durationY?: number; easingX?: EasingType; easingY?: EasingType; }; chartBackgroundColor?: Color; logEnabled?: boolean; noDataText?: string; touchEnabled?: boolean; dragDecelerationEnabled?: boolean; dragDecelerationFrictionCoef?: number; highlightPerTapEnabled?: boolean; chartDescription?: ChartDescription; legend?: ChartLegend; xAxis?: xAxis; marker?: { enabled?: boolean; digits?: number; markerColor?: Color; textColor?: Color; textSize?: number; }; highlights?: Array<{ x: number; dataSetIndex?: number; dataIndex?: number; y?: number; stackIndex?: number; }>; onSelect?: (event: ChartSelectEvent) => void; onChange?: (event: ChartChangeEvent) => void; } export interface BarLineChartBase extends ChartBase { maxHighlightDistance?: number; drawGridBackground?: boolean; gridBackgroundColor?: number; drawBorders?: boolean; borderColor?: Color; borderWidth?: number; minOffset?: number; maxVisibleValueCount?: number; visibleRange?: { x?: { min?: number; max?: number; }; y?: { left?: { min?: number; max?: number; }; right?: { min?: number; max?: number; }; }; }; autoScaleMinMaxEnabled?: boolean; keepPositionOnRotation?: boolean; highlightPerDragEnabled?: boolean; scaleEnabled?: boolean; scaleXEnabled?: boolean; scaleYEnabled?: boolean; dragEnabled?: boolean; pinchZoom?: boolean; doubleTapToZoomEnabled?: boolean; yAxis?: { left?: yAxis; right?: yAxis; }; zoom?: { scaleX: number; scaleY: number; xValue: number; yValue: number; axisDependency?: AxisDependency; }; viewPortOffsets?: Offsets; extraOffsets?: Offsets; group?: string; identifier?: string; syncX?: boolean; syncY?: boolean; } export interface PieRadarChartBase extends ChartBase { minOffset?: number; rotationEnabled?: boolean; rotationAngle?: number; } export interface LineValue { x?: number; y: number; marker?: string; } export interface CommonDatasetConfig { color?: Color; colors?: Color[]; highlightEnabled?: boolean; drawValues?: boolean; valueTextSize?: number; valueTextColor?: Color; visible?: boolean; valueFormatter?: ValueFormatter; axisDependency?: AxisDependency; } export interface BarLineScatterCandleBubbleConfig { highlightColor?: Color; } export interface LineScatterCandleRadarConfig { drawVerticalHighlightIndicator?: boolean; drawHorizontalHighlightIndicator?: boolean; highlightLineWidth?: number; drawHighlightIndicators?: boolean; } export interface LineRadarConfig { fillGradient?: { colors?: Color[]; positions?: number[]; angle?: number; orientation?: 'TOP_BOTTOM' | 'TR_BL' | 'RIGHT_LEFT' | 'BR_TL' | 'BOTTOM_TOP' | 'BL_TR' | 'LEFT_RIGHT' | 'TL_BR'; }; fillColor?: Color; fillAlpha?: number; drawFilled?: boolean; lineWidth?: number; } export interface LineDatasetConfig extends CommonDatasetConfig, BarLineScatterCandleBubbleConfig, LineScatterCandleRadarConfig, LineRadarConfig { circleRadius?: number; drawCircles?: boolean; mode?: 'LINEAR' | 'STEPPED' | 'CUBIC_BEZIER' | 'HORIZONTAL_BEZIER'; drawCubicIntensity?: number; circleColor?: Color; circleColors?: Color[]; circleHoleColor?: Color; drawCircleHole?: boolean; dashedLine?: { lineLength: number; spaceLength: number; phase?: number; }; } export interface Dataset { label?: string; } export interface LineDataset extends Dataset { values?: Array<number | LineValue>; config?: LineDatasetConfig; } export interface LineData { dataSets?: LineDataset[]; } export type ChartSelectEvent = NativeSyntheticEvent<{ x: number; y: number } | null>; export type ChartChangeEvent = NativeSyntheticEvent<{ action: string; scaleX?: number; scaleY?: number; centerX?: number; centerY?: number; left?: number; bottom?: number; right?: number; top?: number; }>; export interface LineChartProps extends BarLineChartBase { data: LineData; } export class LineChart extends Component<LineChartProps> {} export interface BarValue { x?: number; y?: number | number[]; marker?: string | string[]; } export interface BarDatasetConfig extends CommonDatasetConfig, BarLineScatterCandleBubbleConfig { barShadowColor?: Color; highlightAlpha?: number; stackLabels?: string[]; } export interface BarDataset extends Dataset { values?: Array<BarValue | number | number[]>; config?: BarDatasetConfig; } export interface BarData { dataSets?: BarDataset[]; config?: { barWidth?: number; group?: { fromX: number; groupSpace: number; barSpace: number; }; }; } export interface BarChartProps extends BarLineChartBase { drawValueAboveBar?: boolean; drawBarShadow?: boolean; highlightFullBarEnabled?: boolean; data: BarData; } export class BarChart extends Component<BarChartProps> {} export interface BubbleValue { x?: number; y: number; size: number; marker?: string; } export interface BubbleDatasetConfig extends CommonDatasetConfig, BarLineScatterCandleBubbleConfig { highlightCircleWidth?: number; } export interface BubbleDataset extends Dataset { values?: BubbleValue[]; label: string; config?: BubbleDatasetConfig; } export interface BubbleData { dataSets?: BubbleDataset[]; } export interface BubbleChartProps extends BarLineChartBase { data?: BubbleData; } export class BubbleChart extends Component<BubbleChartProps> {} export interface CandleStickValue { x?: number; shadowH: number; shadowL: number; open: number; close: number; marker?: string; } export type CandleStickPaintStyle = 'FILL' | 'STROKE' | 'FILL_AND_STROKE'; export interface CandleStickDatasetConfig extends CommonDatasetConfig, BarLineScatterCandleBubbleConfig, LineScatterCandleRadarConfig { barSpace?: number; shadowWidth?: number; shadowColor?: Color; shadowColorSameAsCandle?: boolean; neutralColor?: Color; decreasingColor?: Color; decreasingPaintStyle?: CandleStickPaintStyle; increasingColor?: Color; increasingPaintStyle?: CandleStickPaintStyle; } export interface CandleStickDataset extends Dataset { values?: CandleStickValue[]; label: string; config?: CandleStickDatasetConfig; } export interface CandleStickData { dataSets?: CandleStickDataset[]; } export interface CandleStickChartProps extends BarLineChartBase { data?: CandleStickData; } export class CandleStickChart extends Component<CandleStickChartProps> {} export type PieValuePosition = 'INSIDE_SLICE' | 'OUTSIDE_SLICE'; export interface PieDatasetConfig extends CommonDatasetConfig { sliceSpace?: number; selectionShift?: number; xValuePosition?: PieValuePosition; yValuePosition?: PieValuePosition; valueLinePart1Length?: number; valueLinePart2Length?: number; valueLineColor?: Color; valueLineWidth?: number; valueLinePart1OffsetPercentage?: number; valueLineVariableLength?: boolean; } export interface PieValue { value: number; label?: string; } export interface PieDataset extends Dataset { values?: Array<PieValue | number>; label: string; config?: PieDatasetConfig; } export interface PieData { dataSets?: PieDataset[]; } export interface PieChartProps extends PieRadarChartBase { drawEntryLabels?: boolean; usePercentValues?: boolean; centerText?: string; styledCenterText?: { text?: string; color?: Color; size?: number; }; centerTextRadiusPercent?: number; holeRadius?: number; holeColor?: Color; transparentCircleRadius?: number; transparentCircleColor?: Color; entryLabelColor?: Color; entryLabelTextSize?: number; maxAngle?: number; data?: PieData; } export class PieChart extends Component<PieChartProps> {} export interface RadarDatasetConfig extends CommonDatasetConfig, LineScatterCandleRadarConfig, LineRadarConfig {} export interface RadarDataset extends Dataset { values?: Array<{ value: number } | number>; label: string; config?: RadarDatasetConfig; } export interface RadarData { dataSets?: RadarDataset[]; labels?: string[]; } export interface RadarChartProps extends PieRadarChartBase { yAxis?: yAxis; drawWeb?: boolean; skipWebLineCount?: number; webLineWidth?: number; webLineWidthInner?: number; webAlpha?: number; webColor?: Color; webColorInner?: Color; data?: RadarData; } export class RadarChart extends Component<RadarChartProps> {} export interface ScatterDatasetConfig extends CommonDatasetConfig, BarLineScatterCandleBubbleConfig, LineScatterCandleRadarConfig { scatterShapeSize?: number; scatterShape?: "SQUARE" | "CIRCLE" | "TRIANGLE" | "CROSS" | "X"; scatterShapeHoleColor?: Color; scatterShapeHoleRadius?: number; } export interface ScatterDataset extends Dataset { values?: Array<LineValue | number>; label: string; config?: ScatterDatasetConfig; } export interface ScatterData { dataSets: ScatterDataset[]; } export interface ScatterChartProps extends BarLineChartBase { data?: ScatterData; } export class ScatterChart extends Component<ScatterChartProps> {} export interface CombinedData { lineData?: LineData; barData?: BarData; scatterData?: ScatterData; candleData?: CandleStickData; bubbleData?: BubbleData; } export interface CombinedChartProps extends BarLineChartBase { drawOrder?: Array<("BAR" | "BUBBLE" | "LINE" | "CANDLE" | "SCATTER")>; drawValueAboveBar?: boolean; highlightFullBarEnabled?: boolean; drawBarShadow?: boolean; data?: CombinedData; } export class CombinedChart extends Component<CombinedChartProps> {} export class HorizontalBarChart extends Component<BarChartProps> {}
the_stack
import * as AWS from 'aws-sdk'; import { GetCallerIdentityResponse } from 'aws-sdk/clients/sts'; AWS.config.logger = console; import { CloudFormationCustomResourceEvent, CloudFormationCustomResourceDeleteEvent, CloudFormationCustomResourceCreateEvent, CloudFormationCustomResourceUpdateEvent, } from 'aws-lambda'; import { errorHandler } from '@aws-accelerator/custom-resource-runtime-cfn-response'; import { throttlingBackOff } from '@aws-accelerator/custom-resource-cfn-utils'; export interface HandlerProperties { assumeRoleName: string; vpcAccountId: string; vpcName: string; vpcId: string; vpcRegion: string; hostedZoneAccountId: string; hostedZoneIds: string[]; } export class STS { private readonly client: AWS.STS; private readonly cache: { [roleArn: string]: AWS.Credentials } = {}; constructor(credentials?: AWS.Credentials) { this.client = new AWS.STS({ credentials, }); } async getCallerIdentity(): Promise<GetCallerIdentityResponse> { return throttlingBackOff(() => this.client.getCallerIdentity().promise()); } async getCredentialsForRoleArn(assumeRoleArn: string, durationSeconds: number = 3600): Promise<AWS.Credentials> { if (this.cache[assumeRoleArn]) { const cachedCredentials = this.cache[assumeRoleArn]; const currentDate = new Date(); if (cachedCredentials.expireTime && cachedCredentials.expireTime.getTime() < currentDate.getTime()) { return cachedCredentials; } } const response = await throttlingBackOff(() => this.client .assumeRole({ RoleArn: assumeRoleArn, RoleSessionName: 'temporary', // TODO Generate a random name DurationSeconds: durationSeconds, }) .promise(), ); const stsCredentials = response.Credentials!; const credentials = new AWS.Credentials({ accessKeyId: stsCredentials.AccessKeyId, secretAccessKey: stsCredentials.SecretAccessKey, sessionToken: stsCredentials.SessionToken, }); this.cache[assumeRoleArn] = credentials; return credentials; } async getCredentialsForAccountAndRole( accountId: string, assumeRole: string, durationSeconds?: number, ): Promise<AWS.Credentials> { return this.getCredentialsForRoleArn(`arn:aws:iam::${accountId}:role/${assumeRole}`, durationSeconds); } } const sts = new STS(); export const handler = errorHandler(onEvent); async function onEvent(event: CloudFormationCustomResourceEvent) { console.log(`Associating HostedZones to VPC..`); console.log(JSON.stringify(event, null, 2)); // eslint-disable-next-line default-case switch (event.RequestType) { case 'Create': return onCreate(event); case 'Update': return onUpdate(event); case 'Delete': return onDelete(event); } } async function onCreate(event: CloudFormationCustomResourceCreateEvent) { const properties = (event.ResourceProperties as unknown) as HandlerProperties; const { assumeRoleName, hostedZoneAccountId, hostedZoneIds, vpcAccountId, vpcId, vpcName, vpcRegion } = properties; const vpcAccountCredentials = await sts.getCredentialsForAccountAndRole(vpcAccountId, assumeRoleName); const vpcRoute53 = new AWS.Route53({ credentials: vpcAccountCredentials, }); let hostedZoneAccountCredentials: AWS.Credentials; let hostedZoneRoute53: AWS.Route53; if (vpcAccountId !== hostedZoneAccountId) { hostedZoneAccountCredentials = await sts.getCredentialsForAccountAndRole(hostedZoneAccountId, assumeRoleName); hostedZoneRoute53 = new AWS.Route53({ credentials: hostedZoneAccountCredentials, }); } for (const hostedZoneId of hostedZoneIds) { const hostedZoneProps = { HostedZoneId: hostedZoneId, VPC: { VPCId: vpcId, VPCRegion: vpcRegion, }, }; // authorize association of VPC with Hosted zones when VPC and Hosted Zones are defined in two different accounts if (vpcAccountId !== hostedZoneAccountId) { await throttlingBackOff(() => hostedZoneRoute53.createVPCAssociationAuthorization(hostedZoneProps).promise()); } // associate VPC with Hosted zones try { console.log(`Associating hosted zone ${hostedZoneId} with VPC ${vpcId} ${vpcName}...`); await throttlingBackOff(() => vpcRoute53.associateVPCWithHostedZone(hostedZoneProps).promise()); } catch (e) { if (e.code === 'ConflictingDomainExists') { console.info('Domain already added; ignore this error and continue'); } else { console.error(`Error while associating the hosted zone "${hostedZoneId}" to VPC "${vpcName}"`); console.error(e); throw new Error(e); } } // delete association of VPC with Hosted zones when VPC and Hosted Zones are defined in two different accounts if (vpcAccountId !== hostedZoneAccountId) { await throttlingBackOff(() => hostedZoneRoute53.deleteVPCAssociationAuthorization(hostedZoneProps).promise()); } } return { physicalResourceId: `AssociateHostedZones-${vpcName}-${vpcRegion}-${vpcAccountId}-${hostedZoneAccountId}`, }; } async function onUpdate(event: CloudFormationCustomResourceUpdateEvent) { const properties = (event.ResourceProperties as unknown) as HandlerProperties; const { assumeRoleName, hostedZoneAccountId, hostedZoneIds, vpcAccountId, vpcId, vpcName, vpcRegion } = properties; const vpcAccountCredentials = await sts.getCredentialsForAccountAndRole(vpcAccountId, assumeRoleName); const vpcRoute53 = new AWS.Route53({ credentials: vpcAccountCredentials, }); let hostedZoneAccountCredentials: AWS.Credentials; let hostedZoneRoute53: AWS.Route53; if (vpcAccountId !== hostedZoneAccountId) { hostedZoneAccountCredentials = await sts.getCredentialsForAccountAndRole(hostedZoneAccountId, assumeRoleName); hostedZoneRoute53 = new AWS.Route53({ credentials: hostedZoneAccountCredentials, }); } const oldProperties = (event.OldResourceProperties as unknown) as HandlerProperties; const currentAssociations = hostedZoneIds.filter(hz => !oldProperties.hostedZoneIds.includes(hz)); const removeAssociations = oldProperties.hostedZoneIds.filter(hz => !hostedZoneIds.includes(hz)); for (const hostedZoneId of currentAssociations) { const hostedZoneProps = { HostedZoneId: hostedZoneId, VPC: { VPCId: vpcId, VPCRegion: vpcRegion, }, }; // authorize association of VPC with Hosted zones when VPC and Hosted Zones are defined in two different accounts if (vpcAccountId !== hostedZoneAccountId) { await throttlingBackOff(() => hostedZoneRoute53.createVPCAssociationAuthorization(hostedZoneProps).promise()); } // associate VPC with Hosted zones try { console.log(`Associating hosted zone ${hostedZoneId} with VPC ${vpcId} ${vpcName}...`); await throttlingBackOff(() => vpcRoute53.associateVPCWithHostedZone(hostedZoneProps).promise()); } catch (e) { if (e.code === 'ConflictingDomainExists') { console.info('Domain already added; ignore this error and continue'); } else { // TODO Handle errors console.error(`Ignoring error while associating the hosted zone ${hostedZoneId} to VPC "${vpcName}"`); console.error(e); } } // delete association of VPC with Hosted zones when VPC and Hosted Zones are defined in two different accounts if (vpcAccountId !== hostedZoneAccountId) { await throttlingBackOff(() => hostedZoneRoute53.deleteVPCAssociationAuthorization(hostedZoneProps).promise()); } } for (const hostedZoneId of removeAssociations) { const hostedZoneProps = { HostedZoneId: hostedZoneId, VPC: { VPCId: vpcId, VPCRegion: vpcRegion, }, }; // authorize association of VPC with Hosted zones when VPC and Hosted Zones are defined in two different accounts if (vpcAccountId !== hostedZoneAccountId) { try { await throttlingBackOff(() => hostedZoneRoute53.createVPCAssociationAuthorization(hostedZoneProps).promise()); } catch (e) { if (e.code === 'NoSuchHostedZone') { console.info(`No Domain exists with ID "${hostedZoneId}"; ignore this error and continue`); continue; } else { throw new Error(e); } } } // associate VPC with Hosted zones try { console.log(`Disassociating hosted zone ${hostedZoneId} with VPC ${vpcId} ${vpcName}...`); await throttlingBackOff(() => vpcRoute53.disassociateVPCFromHostedZone(hostedZoneProps).promise()); } catch (e) { if (e.code === 'VPCAssociationNotFound') { console.warn(`The specified VPC "${vpcId}" and hosted zone "${hostedZoneId}" are not currently associated.`); } else if (e.code === 'NoSuchHostedZone') { console.warn(`The specified hosted zone "${hostedZoneId}" doesn't exist.`); continue; } else { console.error(`Error while associating the hosted zone "${hostedZoneId}" to VPC "${vpcName}"`); console.error(e); throw new Error(e); } } // delete association of VPC with Hosted zones when VPC and Hosted Zones are defined in two different accounts if (vpcAccountId !== hostedZoneAccountId) { try { await throttlingBackOff(() => hostedZoneRoute53.deleteVPCAssociationAuthorization(hostedZoneProps).promise()); } catch (e) { if (e.code === 'VPCAssociationNotFound') { console.warn(`The specified VPC "${vpcId}" and hosted zone "${hostedZoneId}" are not currently associated.`); } else if (e.code === 'NoSuchHostedZone') { console.warn(`The specified hosted zone "${hostedZoneId}" doesn't exist.`); } else { console.error(`Error while associating the hosted zone "${hostedZoneId}" to VPC "${vpcName}"`); console.error(e); throw new Error(e); } } } } return { physicalResourceId: `AssociateHostedZones-${vpcName}-${vpcRegion}-${vpcAccountId}-${hostedZoneAccountId}`, }; } async function onDelete(event: CloudFormationCustomResourceDeleteEvent) { console.log(`Deleting Log Group Metric filter...`); console.log(JSON.stringify(event, null, 2)); const properties = (event.ResourceProperties as unknown) as HandlerProperties; const { assumeRoleName, hostedZoneAccountId, hostedZoneIds, vpcAccountId, vpcId, vpcName, vpcRegion } = properties; if ( event.PhysicalResourceId !== `AssociateHostedZones-${vpcName}-${vpcRegion}-${vpcAccountId}-${hostedZoneAccountId}` ) { return; } const vpcAccountCredentials = await sts.getCredentialsForAccountAndRole(vpcAccountId, assumeRoleName); const vpcRoute53 = new AWS.Route53({ credentials: vpcAccountCredentials, }); let hostedZoneAccountCredentials: AWS.Credentials; let hostedZoneRoute53: AWS.Route53; if (vpcAccountId !== hostedZoneAccountId) { hostedZoneAccountCredentials = await sts.getCredentialsForAccountAndRole(hostedZoneAccountId, assumeRoleName); hostedZoneRoute53 = new AWS.Route53({ credentials: hostedZoneAccountCredentials, }); } for (const hostedZoneId of hostedZoneIds) { const hostedZoneProps = { HostedZoneId: hostedZoneId, VPC: { VPCId: vpcId, VPCRegion: vpcRegion, }, }; // authorize association of VPC with Hosted zones when VPC and Hosted Zones are defined in two different accounts if (vpcAccountId !== hostedZoneAccountId) { try { await throttlingBackOff(() => hostedZoneRoute53.createVPCAssociationAuthorization(hostedZoneProps).promise()); } catch (e) { console.error(`Ignoring error while deleting Association and stack ${hostedZoneId} to VPC "${vpcName}"`); console.error(e); continue; } } // associate VPC with Hosted zones try { console.log(`Disassociating hosted zone ${hostedZoneId} with VPC ${vpcId} ${vpcName}...`); await throttlingBackOff(() => vpcRoute53.disassociateVPCFromHostedZone(hostedZoneProps).promise()); } catch (e) { console.error(`Ignoring error while deleting Association and stack ${hostedZoneId} to VPC "${vpcName}"`); console.error(e); if (e.code === 'NoSuchHostedZone') { console.warn(`The specified hosted zone "${hostedZoneId}" doesn't exist.`); continue; } } // delete association of VPC with Hosted zones when VPC and Hosted Zones are defined in two different accounts if (vpcAccountId !== hostedZoneAccountId) { try { await throttlingBackOff(() => hostedZoneRoute53.deleteVPCAssociationAuthorization(hostedZoneProps).promise()); } catch (e) { console.error(`Ignoring error while deleting Association and stack ${hostedZoneId} to VPC "${vpcName}"`); console.error(e); } } } }
the_stack
function utf8ToUtf16 (utf8_bytes: number[]) { let unicode_codes: number[] = []; let unicode_code = 0; let num_followed = 0; for (let i = 0; i < utf8_bytes.length; ++i) { let utf8_byte = utf8_bytes[i]; if (utf8_byte >= 0x100) { // Malformed utf8 byte ignored. } else if ((utf8_byte & 0xC0) == 0x80) { if (num_followed > 0) { unicode_code = (unicode_code << 6) | (utf8_byte & 0x3f); num_followed -= 1; } else { // Malformed UTF-8 sequence ignored. } } else { if (num_followed == 0) { unicode_codes.push(unicode_code); } else { // Malformed UTF-8 sequence ignored. } if (utf8_byte < 0x80){ // 1-byte unicode_code = utf8_byte; num_followed = 0; } else if ((utf8_byte & 0xE0) == 0xC0) { // 2-byte unicode_code = utf8_byte & 0x1f; num_followed = 1; } else if ((utf8_byte & 0xF0) == 0xE0) { // 3-byte unicode_code = utf8_byte & 0x0f; num_followed = 2; } else if ((utf8_byte & 0xF8) == 0xF0) { // 4-byte unicode_code = utf8_byte & 0x07; num_followed = 3; } else { // Malformed UTF-8 sequence ignored. } } } if (num_followed == 0) { unicode_codes.push(unicode_code); } else { // Malformed UTF-8 sequence ignored. } unicode_codes.shift(); // Trim the first element. let utf16_codes = []; for (var i = 0; i < unicode_codes.length; ++i) { unicode_code = unicode_codes[i]; if (unicode_code < (1 << 16)) { utf16_codes.push(unicode_code); } else { var first = ((unicode_code - (1 << 16)) / (1 << 10)) + 0xD800; var second = (unicode_code % (1 << 10)) + 0xDC00; utf16_codes.push(first) utf16_codes.push(second) } } return utf16_codes; } export function utf8_to_ascii( str: string ) { // return unescape(encodeURIComponent(str)) const char2bytes = (unicode_code: number) => { let utf8_bytes: number[] = []; if (unicode_code < 0x80) { // 1-byte utf8_bytes.push(unicode_code); } else if (unicode_code < (1 << 11)) { // 2-byte utf8_bytes.push((unicode_code >>> 6) | 0xC0); utf8_bytes.push((unicode_code & 0x3F) | 0x80); } else if (unicode_code < (1 << 16)) { // 3-byte utf8_bytes.push((unicode_code >>> 12) | 0xE0); utf8_bytes.push(((unicode_code >> 6) & 0x3f) | 0x80); utf8_bytes.push((unicode_code & 0x3F) | 0x80); } else if (unicode_code < (1 << 21)) { // 4-byte utf8_bytes.push((unicode_code >>> 18) | 0xF0); utf8_bytes.push(((unicode_code >> 12) & 0x3F) | 0x80); utf8_bytes.push(((unicode_code >> 6) & 0x3F) | 0x80); utf8_bytes.push((unicode_code & 0x3F) | 0x80); } return utf8_bytes; } let o: number[] = [] for (let i = 0; i < str.length; i++) { o = o.concat(char2bytes(str.charCodeAt(i))) } return o.map(i => String.fromCharCode(i)).join('') } export function ascii_to_utf8( str: string ) { let bytes = str.split('').map(i => i.charCodeAt(0)) return utf8ToUtf16(bytes).map(i => String.fromCharCode(i)).join('') } export function requestFullScreen () { let de: any = document.documentElement; if (de.requestFullscreen) { de.requestFullscreen(); } else if (de.mozRequestFullScreen) { de.mozRequestFullScreen(); } else if (de.webkitRequestFullScreen) { de.webkitRequestFullScreen(); } } export function exitFullscreen () { let de: any = document; if (de.exitFullscreen) { de.exitFullscreen(); } else if (de.mozCancelFullScreen) { de.mozCancelFullScreen(); } else if (de.webkitCancelFullScreen) { de.webkitCancelFullScreen(); } } export class LocalStorage { constructor (private domain: string) { } getItem (key: string, def?: string) { return window.localStorage.getItem(`${this.domain}-${key}`) || def } setItem (key: string, data: string) { window.localStorage.setItem(`${this.domain}-${key}`, data) } } export class Timer { private id: number onTimer: () => void constructor (private delay: number) { } reset () { if (this.id) { clearTimeout(this.id) } this.id = window.setTimeout(this.onTimer, this.delay) } } export function getURL (src: string) { if (src.substr(0, 5) !== 'blob:') { src = chrome.runtime.getURL(src) } return src } export function addScript (src: string) { var script = document.createElement('script') // blob: script.src = getURL(src) document.head.appendChild(script) } export function addCss (src: string, rel: string = 'stylesheet', type: string = 'text/css') { var link = document.createElement('link') link.rel = rel link.type = type link.href = getURL(src) document.head.appendChild(link) } export function createBlobURL (content: string, type: string) { var blob = new Blob([content], { type }) return URL.createObjectURL(blob) } export const p32 = (i: number) => [i, i / 256, i / 65536, i / 16777216].map(i => String.fromCharCode(Math.floor(i) % 256)).join('') export const u32 = (s: string) => s.split('').map(i => i.charCodeAt(0)).reduce((a, b) => b * 256 + a) // --------------------- let messageMap: any = {} export function onMessage (type: string, cb: (data: any) => any) { messageMap[type] = cb } export function postMessage (type: string, data: any) { window.postMessage({ type: type, data: data }, "*") } type msgCallBack = (result: any) => void let msgCallbacks: msgCallBack[] = [] let lastCbId = 0 export function sendMessage<T> (type: string, data: any) { return new Promise<T>((res, rej) => { let curId = ++lastCbId let timeoutId = window.setTimeout(() => { delete msgCallbacks[curId] rej(new Error('sendMessage timeout')) }, 5000) msgCallbacks[curId] = (result) => { delete msgCallbacks[curId] window.clearTimeout(timeoutId) res(result) } window.postMessage({ type: type, data: data, cbId: curId++ }, '*') }) } window.addEventListener('message', async event => { const data = event.data if (data.cb) { let cb = msgCallbacks[data.cbId] if (cb && (typeof cb === 'function')) { cb(data.cbResult) } } else if (data.type) { let result: any = undefined if (typeof messageMap[data.type] === 'function') { result = messageMap[data.type](data.data) if (result instanceof Promise) { result = await result } if (data.cbId) { window.postMessage({ cb: true, cbId: data.cbId, cbResult: result }, '*') } } } }, false) export async function retry<T> (promise: () => Promise<T>, times: number) { let err = [] for (let i = 0; i < times; i++) { try { return await promise() } catch (e) { err.push(e) } } throw err } export function getSync () { return new Promise<any>((res, rej) => { if (chrome && chrome.storage && chrome.storage.sync) { chrome.storage.sync.get(items => { res(items) }) } else { rej(new Error('不支持的存储方式')) } }) } export function setSync (item: any) { return new Promise<void>((res, rej) => { if (chrome && chrome.storage && chrome.storage.sync) { chrome.storage.sync.set(item, res) } else { rej(new Error('不支持的存储方式')) } }) } interface Setting { blacklist?: string[] } export async function getSetting (): Promise<Setting> { let setting: Setting try { setting = await getSync() } catch (e) { } if (!setting) { setting = {} } if (!setting.blacklist) { setting.blacklist = [] } return setting } export async function setSetting (setting: Setting) { await setSync(setting) } const defaultBgListener = async (request: any): Promise<void> => null let bgListener = defaultBgListener export function setBgListener (listener: typeof defaultBgListener) { if (bgListener === defaultBgListener) { if ((typeof chrome !== 'undefined') && chrome.runtime && chrome.runtime.onMessage) { chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => { sendResponse(await bgListener(request)) }) } } else { console.warn('多次设置BgListener') } bgListener = listener } export class DelayNotify<T> { private notified = false private value: T private tmid: number = null private res: (value: T) => void = null constructor (private defaultValue: T) { } notify (value: T) { if (this.notified) { return } this.notified = true this.value = value if (this.res) { this.res(this.value) } } wait (timeout = 1000 * 10) { if (this.notified) { return Promise.resolve(this.value) } return new Promise<T>((resolve, reject) => { if (timeout > 0) { window.setTimeout(() => { resolve(this.defaultValue) }, timeout) } this.res = (value: T) => { return resolve(value) } }) } reset () { this.notified = false } } export class CountByTime { private list: number[] = [] /** * * @param remember in ms */ constructor (private remember: number) { } add () { const now = this.time() this.list.push(now) this.list = this.list.filter(i => now - i < this.remember) } count (before: number = this.remember) { if (before > this.remember) { throw new Error('before should < remember') } const now = this.time() return this.list.filter(i => now - i < before).length } private time () { return +new Date() } } /** * [from, to) * @param from * @param to */ export function randInt (from: number, to: number) { return Math.floor(Math.random() * (to - from) + from) } export function delay (time: number): Promise<void> { return new Promise<void>(res => setTimeout(res, time)) }
the_stack
import * as crypto from 'crypto'; import { Metric, MetricOptions, MetricProps } from '@aws-cdk/aws-cloudwatch'; import * as iam from '@aws-cdk/aws-iam'; import * as s3 from '@aws-cdk/aws-s3'; import * as cdk from '@aws-cdk/core'; import { Construct } from 'constructs'; import { Code } from './code'; import { Runtime } from './runtime'; import { Schedule } from './schedule'; import { CloudWatchSyntheticsMetrics } from './synthetics-canned-metrics.generated'; import { CfnCanary } from './synthetics.generated'; /** * Specify a test that the canary should run */ export class Test { /** * Specify a custom test with your own code * * @returns `Test` associated with the specified Code object * @param options The configuration options */ public static custom(options: CustomTestOptions): Test { Test.validateHandler(options.handler); return new Test(options.code, options.handler); } /** * Verifies that the given handler ends in '.handler'. Returns the handler if successful and * throws an error if not. * * @param handler - the handler given by the user */ private static validateHandler(handler: string) { if (!handler.endsWith('.handler')) { throw new Error(`Canary Handler must end in '.handler' (${handler})`); } if (handler.length > 21) { throw new Error(`Canary Handler must be less than 21 characters (${handler})`); } } /** * Construct a Test property * * @param code The code that the canary should run * @param handler The handler of the canary */ private constructor(public readonly code: Code, public readonly handler: string) { } } /** * Properties for specifying a test */ export interface CustomTestOptions { /** * The code of the canary script */ readonly code: Code, /** * The handler for the code. Must end with `.handler`. */ readonly handler: string, } /** * Options for specifying the s3 location that stores the data of each canary run. The artifacts bucket location **cannot** * be updated once the canary is created. */ export interface ArtifactsBucketLocation { /** * The s3 location that stores the data of each run. */ readonly bucket: s3.IBucket; /** * The S3 bucket prefix. Specify this if you want a more specific path within the artifacts bucket. * * @default - no prefix */ readonly prefix?: string; } /** * Properties for a canary */ export interface CanaryProps { /** * The s3 location that stores the data of the canary runs. * * @default - A new s3 bucket will be created without a prefix. */ readonly artifactsBucketLocation?: ArtifactsBucketLocation; /** * Canary execution role. * * This is the role that will be assumed by the canary upon execution. * It controls the permissions that the canary will have. The role must * be assumable by the AWS Lambda service principal. * * If not supplied, a role will be created with all the required permissions. * If you provide a Role, you must add the required permissions. * * @see required permissions: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-executionrolearn * * @default - A unique role will be generated for this canary. * You can add permissions to roles by calling 'addToRolePolicy'. */ readonly role?: iam.IRole; /** * How long the canary will be in a 'RUNNING' state. For example, if you set `timeToLive` to be 1 hour and `schedule` to be `rate(10 minutes)`, * your canary will run at 10 minute intervals for an hour, for a total of 6 times. * * @default - no limit */ readonly timeToLive?: cdk.Duration; /** * Specify the schedule for how often the canary runs. For example, if you set `schedule` to `rate(10 minutes)`, then the canary will run every 10 minutes. * You can set the schedule with `Schedule.rate(Duration)` (recommended) or you can specify an expression using `Schedule.expression()`. * @default 'rate(5 minutes)' */ readonly schedule?: Schedule; /** * Whether or not the canary should start after creation. * * @default true */ readonly startAfterCreation?: boolean; /** * How many days should successful runs be retained. * * @default Duration.days(31) */ readonly successRetentionPeriod?: cdk.Duration; /** * How many days should failed runs be retained. * * @default Duration.days(31) */ readonly failureRetentionPeriod?: cdk.Duration; /** * The name of the canary. Be sure to give it a descriptive name that distinguishes it from * other canaries in your account. * * Do not include secrets or proprietary information in your canary name. The canary name * makes up part of the canary ARN, which is included in outbound calls over the internet. * @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/servicelens_canaries_security.html * * @default - A unique name will be generated from the construct ID */ readonly canaryName?: string; /** * Specify the runtime version to use for the canary. * * @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html */ readonly runtime: Runtime; /** * The type of test that you want your canary to run. Use `Test.custom()` to specify the test to run. */ readonly test: Test; /** * Key-value pairs that the Synthetics caches and makes available for your canary scripts. Use environment variables * to apply configuration changes, such as test and production environment configurations, without changing your * Canary script source code. * * @default - No environment variables. */ readonly environmentVariables?: { [key: string]: string }; } /** * Define a new Canary */ export class Canary extends cdk.Resource { /** * Execution role associated with this Canary. */ public readonly role: iam.IRole; /** * The canary ID * @attribute */ public readonly canaryId: string; /** * The state of the canary. For example, 'RUNNING', 'STOPPED', 'NOT STARTED', or 'ERROR'. * @attribute */ public readonly canaryState: string; /** * The canary Name * @attribute */ public readonly canaryName: string; /** * Bucket where data from each canary run is stored. */ public readonly artifactsBucket: s3.IBucket; public constructor(scope: Construct, id: string, props: CanaryProps) { if (props.canaryName && !cdk.Token.isUnresolved(props.canaryName)) { validateName(props.canaryName); } super(scope, id, { physicalName: props.canaryName || cdk.Lazy.string({ produce: () => this.generateUniqueName(), }), }); this.artifactsBucket = props.artifactsBucketLocation?.bucket ?? new s3.Bucket(this, 'ArtifactsBucket', { encryption: s3.BucketEncryption.KMS_MANAGED, }); this.role = props.role ?? this.createDefaultRole(props.artifactsBucketLocation?.prefix); const resource: CfnCanary = new CfnCanary(this, 'Resource', { artifactS3Location: this.artifactsBucket.s3UrlForObject(props.artifactsBucketLocation?.prefix), executionRoleArn: this.role.roleArn, startCanaryAfterCreation: props.startAfterCreation ?? true, runtimeVersion: props.runtime.name, name: this.physicalName, schedule: this.createSchedule(props), failureRetentionPeriod: props.failureRetentionPeriod?.toDays(), successRetentionPeriod: props.successRetentionPeriod?.toDays(), code: this.createCode(props), runConfig: this.createRunConfig(props), }); this.canaryId = resource.attrId; this.canaryState = resource.attrState; this.canaryName = this.getResourceNameAttribute(resource.ref); } /** * Measure the Duration of a single canary run, in seconds. * * @param options - configuration options for the metric * * @default avg over 5 minutes */ public metricDuration(options?: MetricOptions): Metric { return this.cannedMetric(CloudWatchSyntheticsMetrics.durationAverage, options); } /** * Measure the percentage of successful canary runs. * * @param options - configuration options for the metric * * @default avg over 5 minutes */ public metricSuccessPercent(options?: MetricOptions): Metric { return this.cannedMetric(CloudWatchSyntheticsMetrics.successPercentAverage, options); } /** * Measure the number of failed canary runs over a given time period. * * Default: sum over 5 minutes * * @param options - configuration options for the metric */ public metricFailed(options?: MetricOptions): Metric { return this.cannedMetric(CloudWatchSyntheticsMetrics.failedSum, options); } /** * Returns a default role for the canary */ private createDefaultRole(prefix?: string): iam.IRole { const { partition } = cdk.Stack.of(this); // Created role will need these policies to run the Canary. // https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-synthetics-canary.html#cfn-synthetics-canary-executionrolearn const policy = new iam.PolicyDocument({ statements: [ new iam.PolicyStatement({ resources: ['*'], actions: ['s3:ListAllMyBuckets'], }), new iam.PolicyStatement({ resources: [this.artifactsBucket.arnForObjects(`${prefix ? prefix+'/*' : '*'}`)], actions: ['s3:PutObject', 's3:GetBucketLocation'], }), new iam.PolicyStatement({ resources: ['*'], actions: ['cloudwatch:PutMetricData'], conditions: { StringEquals: { 'cloudwatch:namespace': 'CloudWatchSynthetics' } }, }), new iam.PolicyStatement({ resources: [`arn:${partition}:logs:::*`], actions: ['logs:CreateLogStream', 'logs:CreateLogGroup', 'logs:PutLogEvents'], }), ], }); return new iam.Role(this, 'ServiceRole', { assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'), inlinePolicies: { canaryPolicy: policy, }, }); } /** * Returns the code object taken in by the canary resource. */ private createCode(props: CanaryProps): CfnCanary.CodeProperty { const codeConfig = { handler: props.test.handler, ...props.test.code.bind(this, props.test.handler, props.runtime.family), }; return { handler: codeConfig.handler, script: codeConfig.inlineCode, s3Bucket: codeConfig.s3Location?.bucketName, s3Key: codeConfig.s3Location?.objectKey, s3ObjectVersion: codeConfig.s3Location?.objectVersion, }; } /** * Returns a canary schedule object */ private createSchedule(props: CanaryProps): CfnCanary.ScheduleProperty { return { durationInSeconds: String(`${props.timeToLive?.toSeconds() ?? 0}`), expression: props.schedule?.expressionString ?? 'rate(5 minutes)', }; } private createRunConfig(props: CanaryProps): CfnCanary.RunConfigProperty | undefined { if (!props.environmentVariables) { return undefined; } return { environmentVariables: props.environmentVariables, }; } /** * Creates a unique name for the canary. The generated name is the physical ID of the canary. */ private generateUniqueName(): string { const name = cdk.Names.uniqueId(this).toLowerCase().replace(' ', '-'); if (name.length <= 21) { return name; } else { return name.substring(0, 15) + nameHash(name); } } private cannedMetric( fn: (dims: { CanaryName: string }) => MetricProps, props?: MetricOptions): Metric { return new Metric({ ...fn({ CanaryName: this.canaryName }), ...props, }).attachTo(this); } } /** * Take a hash of the given name. * * @param name the name to be hashed */ function nameHash(name: string): string { const md5 = crypto.createHash('sha256').update(name).digest('hex'); return md5.slice(0, 6); } const nameRegex: RegExp = /^[0-9a-z_\-]+$/; /** * Verifies that the name fits the regex expression: ^[0-9a-z_\-]+$. * * @param name - the given name of the canary */ function validateName(name: string) { if (name.length > 21) { throw new Error(`Canary name is too large, must be between 1 and 21 characters, but is ${name.length} (got "${name}")`); } if (!nameRegex.test(name)) { throw new Error(`Canary name must be lowercase, numbers, hyphens, or underscores (got "${name}")`); } }
the_stack
import { KeySet } from '../ojkeyset'; import { DataProvider } from '../ojdataprovider'; import { dvtBaseComponent, dvtBaseComponentEventMap, dvtBaseComponentSettableProperties } from '../ojdvt-base'; import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..'; export interface ojSunburst<K, D> extends dvtBaseComponent<ojSunburstSettableProperties<K, D>> { animationDuration: number; animationOnDataChange: 'auto' | 'none'; animationOnDisplay: 'auto' | 'none'; animationUpdateColor: string; as: string; colorLabel: string; data: DataProvider<K, D> | null; displayLevels: number; drilling: 'on' | 'off'; expanded: KeySet<K>; hiddenCategories: string[]; highlightMatch: 'any' | 'all'; highlightedCategories: string[]; hoverBehavior: 'dim' | 'none'; hoverBehaviorDelay: number; nodeDefaults: { borderColor: string; borderWidth: number; hoverColor: string; labelDisplay: 'horizontal' | 'rotated' | 'off' | 'auto'; labelHalign: 'inner' | 'outer' | 'center'; labelMinLength: number; labelStyle: object; selectedInnerColor: string; selectedOuterColor: string; showDisclosure: 'on' | 'off'; }; rootNode: any; rootNodeContent: { renderer: ((context: ojSunburst.RootNodeContext<K, D>) => ({ insert: Element | string; })); }; rotation: 'off' | 'on'; selection: any[]; selectionMode: 'none' | 'single' | 'multiple'; sizeLabel: string; sorting: 'on' | 'off'; startAngle: number; tooltip: { renderer: ((context: ojSunburst.TooltipContext<K, D>) => ({ insert: Element | string; } | { preventDefault: boolean; })); }; touchResponse: 'touchStart' | 'auto'; translations: { componentName?: string; labelAndValue?: string; labelClearSelection?: string; labelColor?: string; labelCountWithTotal?: string; labelDataVisualization?: string; labelInvalidData?: string; labelNoData?: string; labelSize?: string; stateCollapsed?: string; stateDrillable?: string; stateExpanded?: string; stateHidden?: string; stateIsolated?: string; stateMaximized?: string; stateMinimized?: string; stateSelected?: string; stateUnselected?: string; stateVisible?: string; tooltipCollapse?: string; tooltipExpand?: string; }; onAnimationDurationChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["animationDuration"]>) => any) | null; onAnimationOnDataChangeChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["animationOnDataChange"]>) => any) | null; onAnimationOnDisplayChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["animationOnDisplay"]>) => any) | null; onAnimationUpdateColorChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["animationUpdateColor"]>) => any) | null; onAsChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["as"]>) => any) | null; onColorLabelChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["colorLabel"]>) => any) | null; onDataChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["data"]>) => any) | null; onDisplayLevelsChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["displayLevels"]>) => any) | null; onDrillingChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["drilling"]>) => any) | null; onExpandedChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["expanded"]>) => any) | null; onHiddenCategoriesChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["hiddenCategories"]>) => any) | null; onHighlightMatchChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["highlightMatch"]>) => any) | null; onHighlightedCategoriesChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["highlightedCategories"]>) => any) | null; onHoverBehaviorChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["hoverBehavior"]>) => any) | null; onHoverBehaviorDelayChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["hoverBehaviorDelay"]>) => any) | null; onNodeDefaultsChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["nodeDefaults"]>) => any) | null; onRootNodeChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["rootNode"]>) => any) | null; onRootNodeContentChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["rootNodeContent"]>) => any) | null; onRotationChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["rotation"]>) => any) | null; onSelectionChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["selection"]>) => any) | null; onSelectionModeChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["selectionMode"]>) => any) | null; onSizeLabelChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["sizeLabel"]>) => any) | null; onSortingChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["sorting"]>) => any) | null; onStartAngleChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["startAngle"]>) => any) | null; onTooltipChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["tooltip"]>) => any) | null; onTouchResponseChanged: ((event: JetElementCustomEvent<ojSunburst<K, D>["touchResponse"]>) => any) | null; onOjBeforeCollapse: ((event: ojSunburst.ojBeforeCollapse) => any) | null; onOjBeforeDrill: ((event: ojSunburst.ojBeforeDrill) => any) | null; onOjBeforeExpand: ((event: ojSunburst.ojBeforeExpand) => any) | null; onOjCollapse: ((event: ojSunburst.ojCollapse) => any) | null; onOjDrill: ((event: ojSunburst.ojDrill) => any) | null; onOjExpand: ((event: ojSunburst.ojExpand) => any) | null; onOjRotateInput: ((event: ojSunburst.ojRotateInput) => any) | null; addEventListener<T extends keyof ojSunburstEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojSunburstEventMap<K, D>[T]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; getProperty<T extends keyof ojSunburstSettableProperties<K, D>>(property: T): ojSunburst<K, D>[T]; getProperty(property: string): any; setProperty<T extends keyof ojSunburstSettableProperties<K, D>>(property: T, value: ojSunburstSettableProperties<K, D>[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojSunburstSettableProperties<K, D>>): void; setProperties(properties: ojSunburstSettablePropertiesLenient<K, D>): void; getContextByNode(node: Element): ojSunburst.NodeContext | null; getNode(subIdPath: any[]): ojSunburst.DataContext | null; } export namespace ojSunburst { interface ojBeforeCollapse extends CustomEvent<{ id: any; data: object; itemData: object; [propName: string]: any; }> { } interface ojBeforeDrill extends CustomEvent<{ id: any; data: object; itemData: object; [propName: string]: any; }> { } interface ojBeforeExpand extends CustomEvent<{ id: any; data: object; itemData: object; [propName: string]: any; }> { } interface ojCollapse extends CustomEvent<{ id: any; data: object; itemData: object; [propName: string]: any; }> { } interface ojDrill extends CustomEvent<{ id: any; data: object; itemData: object; [propName: string]: any; }> { } interface ojExpand extends CustomEvent<{ id: any; data: object; itemData: object; [propName: string]: any; }> { } interface ojRotateInput extends CustomEvent<{ value: number; [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type DataContext = { color: string; label: string; selected: boolean; size: number; tooltip: string; }; // tslint:disable-next-line interface-over-type-literal type NodeContext = { subId: string; indexPath: number[]; }; // tslint:disable-next-line interface-over-type-literal type RootNodeContext<K, D> = { outerBounds: { x: number; y: number; width: number; height: number; }; innerBounds: { x: number; y: number; width: number; height: number; }; id: K; data: object; itemData: D; componentElement: Element; }; // tslint:disable-next-line interface-over-type-literal type TooltipContext<K, D> = { parentElement: Element; id: K; label: string; value: number; radius: number; color: string; data: object; itemData: D; componentElement: Element; }; } export interface ojSunburstEventMap<K, D> extends dvtBaseComponentEventMap<ojSunburstSettableProperties<K, D>> { 'ojBeforeCollapse': ojSunburst.ojBeforeCollapse; 'ojBeforeDrill': ojSunburst.ojBeforeDrill; 'ojBeforeExpand': ojSunburst.ojBeforeExpand; 'ojCollapse': ojSunburst.ojCollapse; 'ojDrill': ojSunburst.ojDrill; 'ojExpand': ojSunburst.ojExpand; 'ojRotateInput': ojSunburst.ojRotateInput; 'animationDurationChanged': JetElementCustomEvent<ojSunburst<K, D>["animationDuration"]>; 'animationOnDataChangeChanged': JetElementCustomEvent<ojSunburst<K, D>["animationOnDataChange"]>; 'animationOnDisplayChanged': JetElementCustomEvent<ojSunburst<K, D>["animationOnDisplay"]>; 'animationUpdateColorChanged': JetElementCustomEvent<ojSunburst<K, D>["animationUpdateColor"]>; 'asChanged': JetElementCustomEvent<ojSunburst<K, D>["as"]>; 'colorLabelChanged': JetElementCustomEvent<ojSunburst<K, D>["colorLabel"]>; 'dataChanged': JetElementCustomEvent<ojSunburst<K, D>["data"]>; 'displayLevelsChanged': JetElementCustomEvent<ojSunburst<K, D>["displayLevels"]>; 'drillingChanged': JetElementCustomEvent<ojSunburst<K, D>["drilling"]>; 'expandedChanged': JetElementCustomEvent<ojSunburst<K, D>["expanded"]>; 'hiddenCategoriesChanged': JetElementCustomEvent<ojSunburst<K, D>["hiddenCategories"]>; 'highlightMatchChanged': JetElementCustomEvent<ojSunburst<K, D>["highlightMatch"]>; 'highlightedCategoriesChanged': JetElementCustomEvent<ojSunburst<K, D>["highlightedCategories"]>; 'hoverBehaviorChanged': JetElementCustomEvent<ojSunburst<K, D>["hoverBehavior"]>; 'hoverBehaviorDelayChanged': JetElementCustomEvent<ojSunburst<K, D>["hoverBehaviorDelay"]>; 'nodeDefaultsChanged': JetElementCustomEvent<ojSunburst<K, D>["nodeDefaults"]>; 'rootNodeChanged': JetElementCustomEvent<ojSunburst<K, D>["rootNode"]>; 'rootNodeContentChanged': JetElementCustomEvent<ojSunburst<K, D>["rootNodeContent"]>; 'rotationChanged': JetElementCustomEvent<ojSunburst<K, D>["rotation"]>; 'selectionChanged': JetElementCustomEvent<ojSunburst<K, D>["selection"]>; 'selectionModeChanged': JetElementCustomEvent<ojSunburst<K, D>["selectionMode"]>; 'sizeLabelChanged': JetElementCustomEvent<ojSunburst<K, D>["sizeLabel"]>; 'sortingChanged': JetElementCustomEvent<ojSunburst<K, D>["sorting"]>; 'startAngleChanged': JetElementCustomEvent<ojSunburst<K, D>["startAngle"]>; 'tooltipChanged': JetElementCustomEvent<ojSunburst<K, D>["tooltip"]>; 'touchResponseChanged': JetElementCustomEvent<ojSunburst<K, D>["touchResponse"]>; } export interface ojSunburstSettableProperties<K, D> extends dvtBaseComponentSettableProperties { animationDuration: number; animationOnDataChange: 'auto' | 'none'; animationOnDisplay: 'auto' | 'none'; animationUpdateColor: string; as: string; colorLabel: string; data: DataProvider<K, D> | null; displayLevels: number; drilling: 'on' | 'off'; expanded: KeySet<K>; hiddenCategories: string[]; highlightMatch: 'any' | 'all'; highlightedCategories: string[]; hoverBehavior: 'dim' | 'none'; hoverBehaviorDelay: number; nodeDefaults: { borderColor: string; borderWidth: number; hoverColor: string; labelDisplay: 'horizontal' | 'rotated' | 'off' | 'auto'; labelHalign: 'inner' | 'outer' | 'center'; labelMinLength: number; labelStyle: object; selectedInnerColor: string; selectedOuterColor: string; showDisclosure: 'on' | 'off'; }; rootNode: any; rootNodeContent: { renderer: ((context: ojSunburst.RootNodeContext<K, D>) => ({ insert: Element | string; })); }; rotation: 'off' | 'on'; selection: any[]; selectionMode: 'none' | 'single' | 'multiple'; sizeLabel: string; sorting: 'on' | 'off'; startAngle: number; tooltip: { renderer: ((context: ojSunburst.TooltipContext<K, D>) => ({ insert: Element | string; } | { preventDefault: boolean; })); }; touchResponse: 'touchStart' | 'auto'; translations: { componentName?: string; labelAndValue?: string; labelClearSelection?: string; labelColor?: string; labelCountWithTotal?: string; labelDataVisualization?: string; labelInvalidData?: string; labelNoData?: string; labelSize?: string; stateCollapsed?: string; stateDrillable?: string; stateExpanded?: string; stateHidden?: string; stateIsolated?: string; stateMaximized?: string; stateMinimized?: string; stateSelected?: string; stateUnselected?: string; stateVisible?: string; tooltipCollapse?: string; tooltipExpand?: string; }; } export interface ojSunburstSettablePropertiesLenient<K, D> extends Partial<ojSunburstSettableProperties<K, D>> { [key: string]: any; } export interface ojSunburstNode extends JetElement<ojSunburstNodeSettableProperties> { borderColor?: string; borderWidth?: number; categories?: string[]; color?: string; drilling?: 'on' | 'off' | 'inherit'; label?: string; labelDisplay?: 'horizontal' | 'rotated' | 'off' | 'auto'; labelHalign?: 'inner' | 'outer' | 'center'; labelStyle?: object; pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none'; radius?: number; selectable?: 'off' | 'auto'; shortDesc?: string; showDisclosure?: 'on' | 'off' | 'inherit'; svgClassName?: string; svgStyle?: object; value: number; onBorderColorChanged: ((event: JetElementCustomEvent<ojSunburstNode["borderColor"]>) => any) | null; onBorderWidthChanged: ((event: JetElementCustomEvent<ojSunburstNode["borderWidth"]>) => any) | null; onCategoriesChanged: ((event: JetElementCustomEvent<ojSunburstNode["categories"]>) => any) | null; onColorChanged: ((event: JetElementCustomEvent<ojSunburstNode["color"]>) => any) | null; onDrillingChanged: ((event: JetElementCustomEvent<ojSunburstNode["drilling"]>) => any) | null; onLabelChanged: ((event: JetElementCustomEvent<ojSunburstNode["label"]>) => any) | null; onLabelDisplayChanged: ((event: JetElementCustomEvent<ojSunburstNode["labelDisplay"]>) => any) | null; onLabelHalignChanged: ((event: JetElementCustomEvent<ojSunburstNode["labelHalign"]>) => any) | null; onLabelStyleChanged: ((event: JetElementCustomEvent<ojSunburstNode["labelStyle"]>) => any) | null; onPatternChanged: ((event: JetElementCustomEvent<ojSunburstNode["pattern"]>) => any) | null; onRadiusChanged: ((event: JetElementCustomEvent<ojSunburstNode["radius"]>) => any) | null; onSelectableChanged: ((event: JetElementCustomEvent<ojSunburstNode["selectable"]>) => any) | null; onShortDescChanged: ((event: JetElementCustomEvent<ojSunburstNode["shortDesc"]>) => any) | null; onShowDisclosureChanged: ((event: JetElementCustomEvent<ojSunburstNode["showDisclosure"]>) => any) | null; onSvgClassNameChanged: ((event: JetElementCustomEvent<ojSunburstNode["svgClassName"]>) => any) | null; onSvgStyleChanged: ((event: JetElementCustomEvent<ojSunburstNode["svgStyle"]>) => any) | null; onValueChanged: ((event: JetElementCustomEvent<ojSunburstNode["value"]>) => any) | null; addEventListener<T extends keyof ojSunburstNodeEventMap>(type: T, listener: (this: HTMLElement, ev: ojSunburstNodeEventMap[T]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; getProperty<T extends keyof ojSunburstNodeSettableProperties>(property: T): ojSunburstNode[T]; getProperty(property: string): any; setProperty<T extends keyof ojSunburstNodeSettableProperties>(property: T, value: ojSunburstNodeSettableProperties[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojSunburstNodeSettableProperties>): void; setProperties(properties: ojSunburstNodeSettablePropertiesLenient): void; } export interface ojSunburstNodeEventMap extends HTMLElementEventMap { 'borderColorChanged': JetElementCustomEvent<ojSunburstNode["borderColor"]>; 'borderWidthChanged': JetElementCustomEvent<ojSunburstNode["borderWidth"]>; 'categoriesChanged': JetElementCustomEvent<ojSunburstNode["categories"]>; 'colorChanged': JetElementCustomEvent<ojSunburstNode["color"]>; 'drillingChanged': JetElementCustomEvent<ojSunburstNode["drilling"]>; 'labelChanged': JetElementCustomEvent<ojSunburstNode["label"]>; 'labelDisplayChanged': JetElementCustomEvent<ojSunburstNode["labelDisplay"]>; 'labelHalignChanged': JetElementCustomEvent<ojSunburstNode["labelHalign"]>; 'labelStyleChanged': JetElementCustomEvent<ojSunburstNode["labelStyle"]>; 'patternChanged': JetElementCustomEvent<ojSunburstNode["pattern"]>; 'radiusChanged': JetElementCustomEvent<ojSunburstNode["radius"]>; 'selectableChanged': JetElementCustomEvent<ojSunburstNode["selectable"]>; 'shortDescChanged': JetElementCustomEvent<ojSunburstNode["shortDesc"]>; 'showDisclosureChanged': JetElementCustomEvent<ojSunburstNode["showDisclosure"]>; 'svgClassNameChanged': JetElementCustomEvent<ojSunburstNode["svgClassName"]>; 'svgStyleChanged': JetElementCustomEvent<ojSunburstNode["svgStyle"]>; 'valueChanged': JetElementCustomEvent<ojSunburstNode["value"]>; } export interface ojSunburstNodeSettableProperties extends JetSettableProperties { borderColor?: string; borderWidth?: number; categories?: string[]; color?: string; drilling?: 'on' | 'off' | 'inherit'; label?: string; labelDisplay?: 'horizontal' | 'rotated' | 'off' | 'auto'; labelHalign?: 'inner' | 'outer' | 'center'; labelStyle?: object; pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none'; radius?: number; selectable?: 'off' | 'auto'; shortDesc?: string; showDisclosure?: 'on' | 'off' | 'inherit'; svgClassName?: string; svgStyle?: object; value: number; } export interface ojSunburstNodeSettablePropertiesLenient extends Partial<ojSunburstNodeSettableProperties> { [key: string]: any; }
the_stack
import { Registration, Writable, DI } from '@aurelia/kernel'; import { Aurelia, customElement, ICustomElementController, IPlatform, IViewModel, LifecycleFlags as LF, IHydratedController as HC, IHydratedParentController as HPC, } from '@aurelia/runtime-html'; import { assert, TestContext } from '@aurelia/testing'; function createFixture() { const ctx = TestContext.create(); const cfg = new NotifierConfig([], 100); const { container } = ctx; container.register(Registration.instance(INotifierConfig, cfg)); const mgr = container.get(INotifierManager); const p = container.get(IPlatform); const host = ctx.createElement('div'); const au = new Aurelia(container); return { mgr, p, au, host }; } describe('controller.hook-timings.integration', function () { const allSyncSpecs: IDelayedInvokerSpec = { binding: (mgr, p) => DelayedInvoker.binding(mgr, p), bound: (mgr, p) => DelayedInvoker.bound(mgr, p), attaching: (mgr, p) => DelayedInvoker.attaching(mgr, p), attached: (mgr, p) => DelayedInvoker.attached(mgr, p), detaching: (mgr, p) => DelayedInvoker.detaching(mgr, p), unbinding: (mgr, p) => DelayedInvoker.unbinding(mgr, p), dispose: (mgr, p) => DelayedInvoker.dispose(mgr, p), toString() { return 'allSync'; }, }; function getAllAsyncSpecs(ticks: number): IDelayedInvokerSpec { return { binding: (mgr, p) => DelayedInvoker.binding(mgr, p, ticks), bound: (mgr, p) => DelayedInvoker.bound(mgr, p, ticks), attaching: (mgr, p) => DelayedInvoker.attaching(mgr, p, ticks), attached: (mgr, p) => DelayedInvoker.attached(mgr, p, ticks), detaching: (mgr, p) => DelayedInvoker.detaching(mgr, p, ticks), unbinding: (mgr, p) => DelayedInvoker.unbinding(mgr, p, ticks), dispose: (mgr, p) => DelayedInvoker.dispose(mgr, p), toString() { return 'allAsync'; }, }; } describe('basic single child component', function () { function $(prefix: 'start' | 'stop') { switch (prefix) { case 'start': return function (component: 'app' | 'a-1') { return function (hook?: HookName) { switch (hook) { case void 0: return [ `start.${component}.binding.enter`, `start.${component}.binding.leave`, `start.${component}.bound.enter`, `start.${component}.bound.leave`, `start.${component}.attaching.enter`, `start.${component}.attaching.leave`, `start.${component}.attached.enter`, `start.${component}.attached.leave`, ]; default: return [ `${prefix}.${component}.${hook}.enter`, `${prefix}.${component}.${hook}.leave`, ]; } }; }; case 'stop': return function (component: 'app' | 'a-1') { return function (hook: HookName) { return [ `${prefix}.${component}.${hook}.enter`, `${prefix}.${component}.${hook}.leave`, ]; }; }; } } const stop_allSync = [ ...$('stop')('a-1')('detaching'), ...$('stop')('app')('detaching'), ...$('stop')('a-1')('unbinding'), ...$('stop')('app')('unbinding'), ...$('stop')('app')('dispose'), ...$('stop')('a-1')('dispose'), ]; const start_allSync = [ ...$('start')('app')('binding'), ...$('start')('app')('bound'), ...$('start')('app')('attaching'), ...$('start')('a-1')(), ...$('start')('app')('attached'), ]; const allSync = [ ...start_allSync, ...stop_allSync, ]; interface ISpec { app: IDelayedInvokerSpec; a1: IDelayedInvokerSpec; expected: string[]; } const syncLikeSpecs: ISpec[] = [ { app: allSyncSpecs, a1: allSyncSpecs, expected: allSync, }, { app: allSyncSpecs, a1: { ...allSyncSpecs, binding: (mgr, p) => DelayedInvoker.binding(mgr, p, 1), toString() { return 'async_binding'; }, }, expected: [ ...$('start')('app')('binding'), ...$('start')('app')('bound'), ...$('start')('app')('attaching'), `start.a-1.binding.enter`, `start.a-1.binding.tick(1)`, `start.a-1.binding.leave`, ...$('start')('a-1')('bound'), ...$('start')('a-1')('attaching'), ...$('start')('a-1')('attached'), ...$('start')('app')('attached'), ...stop_allSync, ], }, { app: { ...allSyncSpecs, binding: (mgr, p) => DelayedInvoker.binding(mgr, p, 1), toString() { return 'async_binding'; }, }, a1: allSyncSpecs, expected: [ `start.app.binding.enter`, `start.app.binding.tick(1)`, `start.app.binding.leave`, ...$('start')('app')('bound'), ...$('start')('app')('attaching'), ...$('start')('a-1')('binding'), ...$('start')('a-1')('bound'), ...$('start')('a-1')('attaching'), ...$('start')('a-1')('attached'), ...$('start')('app')('attached'), ...stop_allSync, ], }, { app: { ...allSyncSpecs, binding: (mgr, p) => DelayedInvoker.binding(mgr, p, 1), toString() { return 'async_binding'; }, }, a1: { ...allSyncSpecs, binding: (mgr, p) => DelayedInvoker.binding(mgr, p, 1), toString() { return 'async_binding'; }, }, expected: [ `start.app.binding.enter`, `start.app.binding.tick(1)`, `start.app.binding.leave`, ...$('start')('app')('bound'), ...$('start')('app')('attaching'), `start.a-1.binding.enter`, `start.a-1.binding.tick(1)`, `start.a-1.binding.leave`, ...$('start')('a-1')('bound'), ...$('start')('a-1')('attaching'), ...$('start')('a-1')('attached'), ...$('start')('app')('attached'), ...stop_allSync, ], }, { app: allSyncSpecs, a1: { ...allSyncSpecs, bound: (mgr, p) => DelayedInvoker.bound(mgr, p, 1), toString() { return 'async_bound'; }, }, expected: [ ...$('start')('app')('binding'), ...$('start')('app')('bound'), ...$('start')('app')('attaching'), ...$('start')('a-1')('binding'), `start.a-1.bound.enter`, `start.a-1.bound.tick(1)`, `start.a-1.bound.leave`, ...$('start')('a-1')('attaching'), ...$('start')('a-1')('attached'), ...$('start')('app')('attached'), ...stop_allSync, ], }, { app: { ...allSyncSpecs, bound: (mgr, p) => DelayedInvoker.bound(mgr, p, 1), toString() { return 'async_bound'; }, }, a1: allSyncSpecs, expected: [ ...$('start')('app')('binding'), `start.app.bound.enter`, `start.app.bound.tick(1)`, `start.app.bound.leave`, ...$('start')('app')('attaching'), ...$('start')('a-1')('binding'), ...$('start')('a-1')('bound'), ...$('start')('a-1')('attaching'), ...$('start')('a-1')('attached'), ...$('start')('app')('attached'), ...stop_allSync, ], }, { app: { ...allSyncSpecs, bound: (mgr, p) => DelayedInvoker.bound(mgr, p, 1), toString() { return 'async_bound'; }, }, a1: { ...allSyncSpecs, bound: (mgr, p) => DelayedInvoker.bound(mgr, p, 1), toString() { return 'async_bound'; }, }, expected: [ ...$('start')('app')('binding'), `start.app.bound.enter`, `start.app.bound.tick(1)`, `start.app.bound.leave`, ...$('start')('app')('attaching'), ...$('start')('a-1')('binding'), `start.a-1.bound.enter`, `start.a-1.bound.tick(1)`, `start.a-1.bound.leave`, ...$('start')('a-1')('attaching'), ...$('start')('a-1')('attached'), ...$('start')('app')('attached'), ...stop_allSync, ], }, { app: allSyncSpecs, a1: { ...allSyncSpecs, attaching: (mgr, p) => DelayedInvoker.attaching(mgr, p, 1), toString() { return 'async_attaching'; }, }, expected: [ ...$('start')('app')('binding'), ...$('start')('app')('bound'), ...$('start')('app')('attaching'), ...$('start')('a-1')('binding'), ...$('start')('a-1')('bound'), `start.a-1.attaching.enter`, `start.a-1.attaching.tick(1)`, `start.a-1.attaching.leave`, ...$('start')('a-1')('attached'), ...$('start')('app')('attached'), ...stop_allSync, ], }, { app: { ...allSyncSpecs, attaching: (mgr, p) => DelayedInvoker.attaching(mgr, p, 1), toString() { return 'async_attaching'; }, }, a1: allSyncSpecs, expected: [ ...$('start')('app')('binding'), ...$('start')('app')('bound'), `start.app.attaching.enter`, ...$('start')('a-1')('binding'), ...$('start')('a-1')('bound'), ...$('start')('a-1')('attaching'), ...$('start')('a-1')('attached'), `start.app.attaching.tick(1)`, `start.app.attaching.leave`, ...$('start')('app')('attached'), ...stop_allSync, ], }, { app: { ...allSyncSpecs, attaching: (mgr, p) => DelayedInvoker.attaching(mgr, p, 1), toString() { return 'async_attaching'; }, }, a1: { ...allSyncSpecs, attaching: (mgr, p) => DelayedInvoker.attaching(mgr, p, 1), toString() { return 'async_attaching'; }, }, expected: [ ...$('start')('app')('binding'), ...$('start')('app')('bound'), `start.app.attaching.enter`, ...$('start')('a-1')('binding'), ...$('start')('a-1')('bound'), `start.a-1.attaching.enter`, `start.app.attaching.tick(1)`, `start.app.attaching.leave`, `start.a-1.attaching.tick(1)`, `start.a-1.attaching.leave`, ...$('start')('a-1')('attached'), ...$('start')('app')('attached'), ...stop_allSync, ], }, { app: allSyncSpecs, a1: { ...allSyncSpecs, attached: (mgr, p) => DelayedInvoker.attached(mgr, p, 1), toString() { return 'async_attached'; }, }, expected: [ ...$('start')('app')('binding'), ...$('start')('app')('bound'), ...$('start')('app')('attaching'), ...$('start')('a-1')('binding'), ...$('start')('a-1')('bound'), ...$('start')('a-1')('attaching'), `start.a-1.attached.enter`, `start.a-1.attached.tick(1)`, `start.a-1.attached.leave`, ...$('start')('app')('attached'), ...stop_allSync, ], }, { app: { ...allSyncSpecs, attached: (mgr, p) => DelayedInvoker.attached(mgr, p, 1), toString() { return 'async_attached'; }, }, a1: allSyncSpecs, expected: [ ...$('start')('app')('binding'), ...$('start')('app')('bound'), ...$('start')('app')('attaching'), ...$('start')('a-1')('binding'), ...$('start')('a-1')('bound'), ...$('start')('a-1')('attaching'), ...$('start')('a-1')('attached'), `start.app.attached.enter`, `start.app.attached.tick(1)`, `start.app.attached.leave`, ...stop_allSync, ], }, { app: { ...allSyncSpecs, attached: (mgr, p) => DelayedInvoker.attached(mgr, p, 1), toString() { return 'async_attached'; }, }, a1: { ...allSyncSpecs, attached: (mgr, p) => DelayedInvoker.attached(mgr, p, 1), toString() { return 'async_attached'; }, }, expected: [ ...$('start')('app')('binding'), ...$('start')('app')('bound'), ...$('start')('app')('attaching'), ...$('start')('a-1')('binding'), ...$('start')('a-1')('bound'), ...$('start')('a-1')('attaching'), `start.a-1.attached.enter`, `start.a-1.attached.tick(1)`, `start.a-1.attached.leave`, `start.app.attached.enter`, `start.app.attached.tick(1)`, `start.app.attached.leave`, ...stop_allSync, ], }, { app: { ...allSyncSpecs, detaching: (mgr, p) => DelayedInvoker.detaching(mgr, p, 1), toString() { return 'async_detaching'; }, }, a1: allSyncSpecs, expected: [ ...start_allSync, ...$('stop')('a-1')('detaching'), `stop.app.detaching.enter`, `stop.app.detaching.tick(1)`, `stop.app.detaching.leave`, ...$('stop')('a-1')('unbinding'), ...$('stop')('app')('unbinding'), ...$('stop')('app')('dispose'), ...$('stop')('a-1')('dispose'), ], }, { app: allSyncSpecs, a1: { ...allSyncSpecs, detaching: (mgr, p) => DelayedInvoker.detaching(mgr, p, 1), toString() { return 'async_detaching'; }, }, expected: [ ...start_allSync, `stop.a-1.detaching.enter`, ...$('stop')('app')('detaching'), `stop.a-1.detaching.tick(1)`, `stop.a-1.detaching.leave`, ...$('stop')('a-1')('unbinding'), ...$('stop')('app')('unbinding'), ...$('stop')('app')('dispose'), ...$('stop')('a-1')('dispose'), ], }, { app: { ...allSyncSpecs, detaching: (mgr, p) => DelayedInvoker.detaching(mgr, p, 1), toString() { return 'async_detaching'; }, }, a1: { ...allSyncSpecs, detaching: (mgr, p) => DelayedInvoker.detaching(mgr, p, 1), toString() { return 'async_detaching'; }, }, expected: [ ...start_allSync, `stop.a-1.detaching.enter`, `stop.app.detaching.enter`, `stop.a-1.detaching.tick(1)`, `stop.a-1.detaching.leave`, `stop.app.detaching.tick(1)`, `stop.app.detaching.leave`, ...$('stop')('a-1')('unbinding'), ...$('stop')('app')('unbinding'), ...$('stop')('app')('dispose'), ...$('stop')('a-1')('dispose'), ], }, { app: { ...allSyncSpecs, unbinding: (mgr, p) => DelayedInvoker.unbinding(mgr, p, 1), toString() { return 'async_unbinding'; }, }, a1: allSyncSpecs, expected: [ ...start_allSync, ...$('stop')('a-1')('detaching'), ...$('stop')('app')('detaching'), ...$('stop')('a-1')('unbinding'), `stop.app.unbinding.enter`, `stop.app.unbinding.tick(1)`, `stop.app.unbinding.leave`, ...$('stop')('app')('dispose'), ...$('stop')('a-1')('dispose'), ], }, { app: allSyncSpecs, a1: { ...allSyncSpecs, unbinding: (mgr, p) => DelayedInvoker.unbinding(mgr, p, 1), toString() { return 'async_unbinding'; }, }, expected: [ ...start_allSync, ...$('stop')('a-1')('detaching'), ...$('stop')('app')('detaching'), `stop.a-1.unbinding.enter`, ...$('stop')('app')('unbinding'), `stop.a-1.unbinding.tick(1)`, `stop.a-1.unbinding.leave`, ...$('stop')('app')('dispose'), ...$('stop')('a-1')('dispose'), ], }, { app: { ...allSyncSpecs, unbinding: (mgr, p) => DelayedInvoker.unbinding(mgr, p, 1), toString() { return 'async_unbinding'; }, }, a1: { ...allSyncSpecs, unbinding: (mgr, p) => DelayedInvoker.unbinding(mgr, p, 1), toString() { return 'async_unbinding'; }, }, expected: [ ...start_allSync, ...$('stop')('a-1')('detaching'), ...$('stop')('app')('detaching'), `stop.a-1.unbinding.enter`, `stop.app.unbinding.enter`, `stop.a-1.unbinding.tick(1)`, `stop.a-1.unbinding.leave`, `stop.app.unbinding.tick(1)`, `stop.app.unbinding.leave`, ...$('stop')('app')('dispose'), ...$('stop')('a-1')('dispose'), ], }, { app: { ...allSyncSpecs, detaching: (mgr, p) => DelayedInvoker.detaching(mgr, p, 1), unbinding: (mgr, p) => DelayedInvoker.unbinding(mgr, p, 1), toString() { return 'async_detaching+unbinding'; }, }, a1: allSyncSpecs, expected: [ ...start_allSync, ...$('stop')('a-1')('detaching'), `stop.app.detaching.enter`, `stop.app.detaching.tick(1)`, `stop.app.detaching.leave`, ...$('stop')('a-1')('unbinding'), `stop.app.unbinding.enter`, `stop.app.unbinding.tick(1)`, `stop.app.unbinding.leave`, ...$('stop')('app')('dispose'), ...$('stop')('a-1')('dispose'), ], }, { app: allSyncSpecs, a1: { ...allSyncSpecs, detaching: (mgr, p) => DelayedInvoker.detaching(mgr, p, 1), unbinding: (mgr, p) => DelayedInvoker.unbinding(mgr, p, 1), toString() { return 'async_detaching+unbinding'; }, }, expected: [ ...start_allSync, `stop.a-1.detaching.enter`, ...$('stop')('app')('detaching'), `stop.a-1.detaching.tick(1)`, `stop.a-1.detaching.leave`, `stop.a-1.unbinding.enter`, ...$('stop')('app')('unbinding'), `stop.a-1.unbinding.tick(1)`, `stop.a-1.unbinding.leave`, ...$('stop')('app')('dispose'), ...$('stop')('a-1')('dispose'), ], }, { app: { ...allSyncSpecs, detaching: (mgr, p) => DelayedInvoker.detaching(mgr, p, 1), unbinding: (mgr, p) => DelayedInvoker.unbinding(mgr, p, 1), toString() { return 'async_detaching+unbinding'; }, }, a1: { ...allSyncSpecs, detaching: (mgr, p) => DelayedInvoker.detaching(mgr, p, 1), toString() { return 'async_detaching'; }, }, expected: [ ...start_allSync, `stop.a-1.detaching.enter`, `stop.app.detaching.enter`, `stop.a-1.detaching.tick(1)`, `stop.a-1.detaching.leave`, `stop.app.detaching.tick(1)`, `stop.app.detaching.leave`, ...$('stop')('a-1')('unbinding'), `stop.app.unbinding.enter`, `stop.app.unbinding.tick(1)`, `stop.app.unbinding.leave`, ...$('stop')('app')('dispose'), ...$('stop')('a-1')('dispose'), ], }, { app: { ...allSyncSpecs, detaching: (mgr, p) => DelayedInvoker.detaching(mgr, p, 1), unbinding: (mgr, p) => DelayedInvoker.unbinding(mgr, p, 1), toString() { return 'async_detaching+unbinding'; }, }, a1: { ...allSyncSpecs, unbinding: (mgr, p) => DelayedInvoker.unbinding(mgr, p, 1), toString() { return 'async_unbinding'; }, }, expected: [ ...start_allSync, ...$('stop')('a-1')('detaching'), `stop.app.detaching.enter`, `stop.app.detaching.tick(1)`, `stop.app.detaching.leave`, `stop.a-1.unbinding.enter`, `stop.app.unbinding.enter`, `stop.a-1.unbinding.tick(1)`, `stop.a-1.unbinding.leave`, `stop.app.unbinding.tick(1)`, `stop.app.unbinding.leave`, ...$('stop')('app')('dispose'), ...$('stop')('a-1')('dispose'), ], }, { app: { ...allSyncSpecs, detaching: (mgr, p) => DelayedInvoker.detaching(mgr, p, 1), toString() { return 'async_detaching'; }, }, a1: { ...allSyncSpecs, detaching: (mgr, p) => DelayedInvoker.detaching(mgr, p, 1), unbinding: (mgr, p) => DelayedInvoker.unbinding(mgr, p, 1), toString() { return 'async_detaching+unbinding'; }, }, expected: [ ...start_allSync, `stop.a-1.detaching.enter`, `stop.app.detaching.enter`, `stop.a-1.detaching.tick(1)`, `stop.a-1.detaching.leave`, `stop.app.detaching.tick(1)`, `stop.app.detaching.leave`, `stop.a-1.unbinding.enter`, ...$('stop')('app')('unbinding'), `stop.a-1.unbinding.tick(1)`, `stop.a-1.unbinding.leave`, ...$('stop')('app')('dispose'), ...$('stop')('a-1')('dispose'), ], }, { app: { ...allSyncSpecs, unbinding: (mgr, p) => DelayedInvoker.unbinding(mgr, p, 1), toString() { return 'async_unbinding'; }, }, a1: { ...allSyncSpecs, detaching: (mgr, p) => DelayedInvoker.detaching(mgr, p, 1), unbinding: (mgr, p) => DelayedInvoker.unbinding(mgr, p, 1), toString() { return 'async_detaching+unbinding'; }, }, expected: [ ...start_allSync, `stop.a-1.detaching.enter`, ...$('stop')('app')('detaching'), `stop.a-1.detaching.tick(1)`, `stop.a-1.detaching.leave`, `stop.a-1.unbinding.enter`, `stop.app.unbinding.enter`, `stop.a-1.unbinding.tick(1)`, `stop.a-1.unbinding.leave`, `stop.app.unbinding.tick(1)`, `stop.app.unbinding.leave`, ...$('stop')('app')('dispose'), ...$('stop')('a-1')('dispose'), ], }, { app: { ...allSyncSpecs, detaching: (mgr, p) => DelayedInvoker.detaching(mgr, p, 1), unbinding: (mgr, p) => DelayedInvoker.unbinding(mgr, p, 1), toString() { return 'async_detaching+unbinding'; }, }, a1: { ...allSyncSpecs, detaching: (mgr, p) => DelayedInvoker.detaching(mgr, p, 1), unbinding: (mgr, p) => DelayedInvoker.unbinding(mgr, p, 1), toString() { return 'async_detaching+unbinding'; }, }, expected: [ ...start_allSync, `stop.a-1.detaching.enter`, `stop.app.detaching.enter`, `stop.a-1.detaching.tick(1)`, `stop.a-1.detaching.leave`, `stop.app.detaching.tick(1)`, `stop.app.detaching.leave`, `stop.a-1.unbinding.enter`, `stop.app.unbinding.enter`, `stop.a-1.unbinding.tick(1)`, `stop.a-1.unbinding.leave`, `stop.app.unbinding.tick(1)`, `stop.app.unbinding.leave`, ...$('stop')('app')('dispose'), ...$('stop')('a-1')('dispose'), ], }, ]; for (const { app, a1, expected } of syncLikeSpecs) { it(`app ${app}, a-1 ${a1}`, async function () { const { mgr, p, au, host } = createFixture(); @customElement({ name: 'a-1', template: null }) class A1 extends TestVM { public constructor() { super(mgr, p, a1); } } @customElement({ name: 'app', template: '<a-1></a-1>', dependencies: [A1] }) class App extends TestVM { public constructor() { super(mgr, p, app); } } au.app({ host, component: App }); mgr.setPrefix('start'); await au.start(); mgr.setPrefix('stop'); await au.stop(true); verifyInvocationsEqual(mgr.fullNotifyHistory, expected); }); it(`app ${app}, a-1 if.bind ${a1}`, async function () { const { mgr, p, au, host } = createFixture(); @customElement({ name: 'a-1', template: null }) class A1 extends TestVM { public constructor() { super(mgr, p, a1); } } @customElement({ name: 'app', template: '<a-1 if.bind="true"></a-1>', dependencies: [A1] }) class App extends TestVM { public constructor() { super(mgr, p, app); } } au.app({ host, component: App }); mgr.setPrefix('start'); await au.start(); mgr.setPrefix('stop'); await au.stop(true); verifyInvocationsEqual(mgr.fullNotifyHistory, expected); }); it(`app ${app}, a-1 else ${a1}`, async function () { const { mgr, p, au, host } = createFixture(); @customElement({ name: 'a-1', template: null }) class A1 extends TestVM { public constructor() { super(mgr, p, a1); } } @customElement({ name: 'app', template: '<a-1 if.bind="false"></a-1><a-1 else></a-1>', dependencies: [A1] }) class App extends TestVM { public constructor() { super(mgr, p, app); } } au.app({ host, component: App }); mgr.setPrefix('start'); await au.start(); mgr.setPrefix('stop'); await au.stop(true); verifyInvocationsEqual(mgr.fullNotifyHistory, expected); }); it(`app ${app}, a-1 with ${a1}`, async function () { const { mgr, p, au, host } = createFixture(); @customElement({ name: 'a-1', template: null }) class A1 extends TestVM { public constructor() { super(mgr, p, a1); } } @customElement({ name: 'app', template: '<a-1 with.bind="{}"></a-1>', dependencies: [A1] }) class App extends TestVM { public constructor() { super(mgr, p, app); } } au.app({ host, component: App }); mgr.setPrefix('start'); await au.start(); mgr.setPrefix('stop'); await au.stop(true); verifyInvocationsEqual(mgr.fullNotifyHistory, expected); }); it(`app ${app}, a-1 repeat.for ${a1}`, async function () { const { mgr, p, au, host } = createFixture(); @customElement({ name: 'a-1', template: null }) class A1 extends TestVM { public constructor() { super(mgr, p, a1); } } @customElement({ name: 'app', template: '<a-1 repeat.for="i of 1"></a-1>', dependencies: [A1] }) class App extends TestVM { public constructor() { super(mgr, p, app); } } au.app({ host, component: App }); mgr.setPrefix('start'); await au.start(); mgr.setPrefix('stop'); await au.stop(true); verifyInvocationsEqual(mgr.fullNotifyHistory, expected); }); it(`app ${app}, a-1 switch.bind case.bind ${a1}`, async function () { const { mgr, p, au, host } = createFixture(); @customElement({ name: 'a-1', template: null }) class A1 extends TestVM { public constructor() { super(mgr, p, a1); } } @customElement({ name: 'app', template: '<a-1 switch.bind="1" case.bind="1"></a-1>', dependencies: [A1] }) class App extends TestVM { public constructor() { super(mgr, p, app); } } au.app({ host, component: App }); mgr.setPrefix('start'); await au.start(); mgr.setPrefix('stop'); await au.stop(true); verifyInvocationsEqual(mgr.fullNotifyHistory, expected); }); it(`app ${app}, a-1 switch.bind default-case ${a1}`, async function () { const { mgr, p, au, host } = createFixture(); @customElement({ name: 'a-1', template: null }) class A1 extends TestVM { public constructor() { super(mgr, p, a1); } } @customElement({ name: 'app', template: '<a-1 switch.bind="1" default-case></a-1>', dependencies: [A1] }) class App extends TestVM { public constructor() { super(mgr, p, app); } } au.app({ host, component: App }); mgr.setPrefix('start'); await au.start(); mgr.setPrefix('stop'); await au.stop(true); verifyInvocationsEqual(mgr.fullNotifyHistory, expected); }); it(`app ${app}, a-1 flags ${a1}`, async function () { const { mgr, p, au, host } = createFixture(); @customElement({ name: 'a-1', template: null }) class A1 extends TestVM { public constructor() { super(mgr, p, a1); } } @customElement({ name: 'app', template: '<a-1 flags></a-1>', dependencies: [A1] }) class App extends TestVM { public constructor() { super(mgr, p, app); } } au.app({ host, component: App }); mgr.setPrefix('start'); await au.start(); mgr.setPrefix('stop'); await au.stop(true); verifyInvocationsEqual(mgr.fullNotifyHistory, expected); }); it(`app ${app}, a-1 portal ${a1}`, async function () { const { mgr, p, au, host } = createFixture(); @customElement({ name: 'a-1', template: null }) class A1 extends TestVM { public constructor() { super(mgr, p, a1); } } @customElement({ name: 'app', template: '<a-1 portal></a-1>', dependencies: [A1] }) class App extends TestVM { public constructor() { super(mgr, p, app); } } au.app({ host, component: App }); mgr.setPrefix('start'); await au.start(); mgr.setPrefix('stop'); await au.stop(true); verifyInvocationsEqual(mgr.fullNotifyHistory, expected); }); } }); // Note: these tests don't necessarily test scenarios that aren't covered elsewhere - their purpose is to provide an easy to understand // set of smoke tests for how the controllers deal with async hooks in various arrangements. // Therefore, the assertions are intentionally verbose and hand-coded to make them as easy as possible to understand, // even if this comes at a cost of making them harder to maintain/modify (which is not really supposed to happen anyway). describe('parallelism', function () { it(`parent 'attaching' can overlap with grandchild 'attached'`, async function () { const { mgr, p, au, host } = createFixture(); const appSpec: IDelayedInvokerSpec = { ...allSyncSpecs, attaching: () => DelayedInvoker.attaching(mgr, p, 1), }; const parentSpec: IDelayedInvokerSpec = { ...allSyncSpecs, }; const childSpec: IDelayedInvokerSpec = { ...allSyncSpecs, }; @customElement({ name: 'c-1', template: null })class C1 extends TestVM { public constructor() { super(mgr, p, childSpec); } } @customElement({ name: 'p-1', template: '<c-1></c-1>', dependencies: [C1] })class P1 extends TestVM { public constructor() { super(mgr, p, parentSpec); } } @customElement({ name: 'app', template: '<p-1></p-1>', dependencies: [P1] })class App extends TestVM { public constructor() { super(mgr, p, appSpec); } } au.app({ host, component: App }); mgr.setPrefix('start'); await au.start(); mgr.setPrefix('stop'); await au.stop(true); verifyInvocationsEqual(mgr.fullNotifyHistory, [ 'start.app.binding.enter', 'start.app.binding.leave', 'start.app.bound.enter', 'start.app.bound.leave', 'start.app.attaching.enter', 'start.p-1.binding.enter', 'start.p-1.binding.leave', 'start.p-1.bound.enter', 'start.p-1.bound.leave', 'start.p-1.attaching.enter', 'start.p-1.attaching.leave', 'start.c-1.binding.enter', 'start.c-1.binding.leave', 'start.c-1.bound.enter', 'start.c-1.bound.leave', 'start.c-1.attaching.enter', 'start.c-1.attaching.leave', 'start.c-1.attached.enter', 'start.c-1.attached.leave', 'start.p-1.attached.enter', 'start.p-1.attached.leave', // app.'attaching' still ongoing after c-1.'attached' finished 'start.app.attaching.tick(1)', 'start.app.attaching.leave', 'start.app.attached.enter', 'start.app.attached.leave', // nothing of interest here: all of these are synchronous and do not demonstrate parallelism (not part of this test) 'stop.c-1.detaching.enter', 'stop.c-1.detaching.leave', 'stop.p-1.detaching.enter', 'stop.p-1.detaching.leave', 'stop.app.detaching.enter', 'stop.app.detaching.leave', 'stop.c-1.unbinding.enter', 'stop.c-1.unbinding.leave', 'stop.p-1.unbinding.enter', 'stop.p-1.unbinding.leave', 'stop.app.unbinding.enter', 'stop.app.unbinding.leave', 'stop.app.dispose.enter', 'stop.app.dispose.leave', 'stop.p-1.dispose.enter', 'stop.p-1.dispose.leave', 'stop.c-1.dispose.enter', 'stop.c-1.dispose.leave', ]); }); it(`'attaching' is awaited before 'attached' starts, and child 'attached' is awaited before parent 'attached' starts`, async function () { const { mgr, p, au, host } = createFixture(); const appSpec: IDelayedInvokerSpec = { ...allSyncSpecs, }; const childSpec: IDelayedInvokerSpec = { ...allSyncSpecs, attaching: () => DelayedInvoker.attaching(mgr, p, 1), attached: () => DelayedInvoker.attached(mgr, p, 1), }; @customElement({ name: 'c-1', template: null })class C1 extends TestVM { public constructor() { super(mgr, p, childSpec); } } @customElement({ name: 'app', template: '<c-1></c-1>', dependencies: [C1] })class App extends TestVM { public constructor() { super(mgr, p, appSpec); } } au.app({ host, component: App }); mgr.setPrefix('start'); await au.start(); mgr.setPrefix('stop'); await au.stop(true); verifyInvocationsEqual(mgr.fullNotifyHistory, [ 'start.app.binding.enter', 'start.app.binding.leave', 'start.app.bound.enter', 'start.app.bound.leave', 'start.app.attaching.enter', 'start.app.attaching.leave', 'start.c-1.binding.enter', 'start.c-1.binding.leave', 'start.c-1.bound.enter', 'start.c-1.bound.leave', 'start.c-1.attaching.enter', 'start.c-1.attaching.tick(1)', 'start.c-1.attaching.leave', 'start.c-1.attached.enter', 'start.c-1.attached.tick(1)', 'start.c-1.attached.leave', 'start.app.attached.enter', 'start.app.attached.leave', // nothing of interest here: all of these are synchronous and do not demonstrate parallelism (not part of this test) 'stop.c-1.detaching.enter', 'stop.c-1.detaching.leave', 'stop.app.detaching.enter', 'stop.app.detaching.leave', 'stop.c-1.unbinding.enter', 'stop.c-1.unbinding.leave', 'stop.app.unbinding.enter', 'stop.app.unbinding.leave', 'stop.app.dispose.enter', 'stop.app.dispose.leave', 'stop.c-1.dispose.enter', 'stop.c-1.dispose.leave', ]); }); it(`parent and child 'attaching' can overlap`, async function () { const { mgr, p, au, host } = createFixture(); const hookSpec: IDelayedInvokerSpec = { ...allSyncSpecs, attaching: () => DelayedInvoker.attaching(mgr, p, 2), }; @customElement({ name: 'c-1', template: null })class C1 extends TestVM { public constructor() { super(mgr, p, hookSpec); } } @customElement({ name: 'app', template: '<c-1></c-1>', dependencies: [C1] })class App extends TestVM { public constructor() { super(mgr, p, hookSpec); } } au.app({ host, component: App }); mgr.setPrefix('start'); await au.start(); mgr.setPrefix('stop'); await au.stop(true); verifyInvocationsEqual(mgr.fullNotifyHistory, [ 'start.app.binding.enter', 'start.app.binding.leave', 'start.app.bound.enter', 'start.app.bound.leave', 'start.app.attaching.enter', 'start.c-1.binding.enter', 'start.c-1.binding.leave', 'start.c-1.bound.enter', 'start.c-1.bound.leave', 'start.c-1.attaching.enter', 'start.app.attaching.tick(1)', 'start.c-1.attaching.tick(1)', 'start.app.attaching.tick(2)', 'start.app.attaching.leave', 'start.c-1.attaching.tick(2)', 'start.c-1.attaching.leave', 'start.c-1.attached.enter', 'start.c-1.attached.leave', 'start.app.attached.enter', 'start.app.attached.leave', // nothing of interest here: all of these are synchronous and do not demonstrate parallelism (not part of this test) 'stop.c-1.detaching.enter', 'stop.c-1.detaching.leave', 'stop.app.detaching.enter', 'stop.app.detaching.leave', 'stop.c-1.unbinding.enter', 'stop.c-1.unbinding.leave', 'stop.app.unbinding.enter', 'stop.app.unbinding.leave', 'stop.app.dispose.enter', 'stop.app.dispose.leave', 'stop.c-1.dispose.enter', 'stop.c-1.dispose.leave', ]); }); it(`'binding' and 'bound' are sequential relative to each other and across parent-child hierarchies`, async function () { const { mgr, p, au, host } = createFixture(); const hookSpec: IDelayedInvokerSpec = { ...allSyncSpecs, binding: () => DelayedInvoker.binding(mgr, p, 1), bound: () => DelayedInvoker.bound(mgr, p, 1), }; @customElement({ name: 'c-1', template: null })class C1 extends TestVM { public constructor() { super(mgr, p, hookSpec); } } @customElement({ name: 'app', template: '<c-1></c-1>', dependencies: [C1] })class App extends TestVM { public constructor() { super(mgr, p, hookSpec); } } au.app({ host, component: App }); mgr.setPrefix('start'); await au.start(); mgr.setPrefix('stop'); await au.stop(true); verifyInvocationsEqual(mgr.fullNotifyHistory, [ 'start.app.binding.enter', 'start.app.binding.tick(1)', 'start.app.binding.leave', 'start.app.bound.enter', 'start.app.bound.tick(1)', 'start.app.bound.leave', 'start.app.attaching.enter', 'start.app.attaching.leave', 'start.c-1.binding.enter', 'start.c-1.binding.tick(1)', 'start.c-1.binding.leave', 'start.c-1.bound.enter', 'start.c-1.bound.tick(1)', 'start.c-1.bound.leave', 'start.c-1.attaching.enter', 'start.c-1.attaching.leave', 'start.c-1.attached.enter', 'start.c-1.attached.leave', 'start.app.attached.enter', 'start.app.attached.leave', // nothing of interest here: all of these are synchronous and do not demonstrate parallelism (not part of this test) 'stop.c-1.detaching.enter', 'stop.c-1.detaching.leave', 'stop.app.detaching.enter', 'stop.app.detaching.leave', 'stop.c-1.unbinding.enter', 'stop.c-1.unbinding.leave', 'stop.app.unbinding.enter', 'stop.app.unbinding.leave', 'stop.app.dispose.enter', 'stop.app.dispose.leave', 'stop.c-1.dispose.enter', 'stop.c-1.dispose.leave', ]); }); it(`'detaching' and 'unbinding' are individually awaited bottom-up in parallel`, async function () { const { mgr, p, au, host } = createFixture(); const hookSpec: IDelayedInvokerSpec = { ...allSyncSpecs, detaching: () => DelayedInvoker.detaching(mgr, p, 2), unbinding: () => DelayedInvoker.unbinding(mgr, p, 2), }; @customElement({ name: 'c-1', template: null })class C1 extends TestVM { public constructor() { super(mgr, p, hookSpec); } } @customElement({ name: 'p-1', template: '<c-1></c-1>', dependencies: [C1] })class P1 extends TestVM { public constructor() { super(mgr, p, hookSpec); } } @customElement({ name: 'app', template: '<p-1></p-1>', dependencies: [P1] })class App extends TestVM { public constructor() { super(mgr, p, hookSpec); } } au.app({ host, component: App }); mgr.setPrefix('start'); await au.start(); mgr.setPrefix('stop'); await au.stop(true); verifyInvocationsEqual(mgr.fullNotifyHistory, [ 'start.app.binding.enter', 'start.app.binding.leave', 'start.app.bound.enter', 'start.app.bound.leave', 'start.app.attaching.enter', 'start.app.attaching.leave', 'start.p-1.binding.enter', 'start.p-1.binding.leave', 'start.p-1.bound.enter', 'start.p-1.bound.leave', 'start.p-1.attaching.enter', 'start.p-1.attaching.leave', 'start.c-1.binding.enter', 'start.c-1.binding.leave', 'start.c-1.bound.enter', 'start.c-1.bound.leave', 'start.c-1.attaching.enter', 'start.c-1.attaching.leave', 'start.c-1.attached.enter', 'start.c-1.attached.leave', 'start.p-1.attached.enter', 'start.p-1.attached.leave', 'start.app.attached.enter', 'start.app.attached.leave', // all 3 'detaching' started bottom-up in parallel, and awaited before 'unbinding' is started 'stop.c-1.detaching.enter', 'stop.p-1.detaching.enter', 'stop.app.detaching.enter', 'stop.c-1.detaching.tick(1)', 'stop.p-1.detaching.tick(1)', 'stop.app.detaching.tick(1)', 'stop.c-1.detaching.tick(2)', 'stop.c-1.detaching.leave', 'stop.p-1.detaching.tick(2)', 'stop.p-1.detaching.leave', 'stop.app.detaching.tick(2)', 'stop.app.detaching.leave', // all 3 'unbinding' started bottom-up in parallel, and awaited before 'dispose' is started 'stop.c-1.unbinding.enter', 'stop.p-1.unbinding.enter', 'stop.app.unbinding.enter', 'stop.c-1.unbinding.tick(1)', 'stop.p-1.unbinding.tick(1)', 'stop.app.unbinding.tick(1)', 'stop.c-1.unbinding.tick(2)', 'stop.c-1.unbinding.leave', 'stop.p-1.unbinding.tick(2)', 'stop.p-1.unbinding.leave', 'stop.app.unbinding.tick(2)', 'stop.app.unbinding.leave', // 'dispose' runs top-down (and is always synchronous) 'stop.app.dispose.enter', 'stop.app.dispose.leave', 'stop.p-1.dispose.enter', 'stop.p-1.dispose.leave', 'stop.c-1.dispose.enter', 'stop.c-1.dispose.leave', ]); }); it(`all hooks are arranged as expected in a complex tree when all are async with the same timings`, async function () { const { mgr, p, au, host } = createFixture(); const hookSpec: IDelayedInvokerSpec = { ...getAllAsyncSpecs(1), }; @customElement({ name: 'c-1', template: null })class C1 extends TestVM { public constructor() { super(mgr, p, hookSpec); } } @customElement({ name: 'c-2', template: null })class C2 extends TestVM { public constructor() { super(mgr, p, hookSpec); } } @customElement({ name: 'p-1', template: '<c-1></c-1>', dependencies: [C1] })class P1 extends TestVM { public constructor() { super(mgr, p, hookSpec); } } @customElement({ name: 'p-2', template: '<c-2></c-2>', dependencies: [C2] })class P2 extends TestVM { public constructor() { super(mgr, p, hookSpec); } } @customElement({ name: 'app', template: '<p-1></p-1><p-2></p-2>', dependencies: [P1, P2] })class App extends TestVM { public constructor() { super(mgr, p, hookSpec); } } au.app({ host, component: App }); mgr.setPrefix('start'); await au.start(); mgr.setPrefix('stop'); await au.stop(true); verifyInvocationsEqual(mgr.fullNotifyHistory, [ 'start.app.binding.enter', 'start.app.binding.tick(1)', 'start.app.binding.leave', 'start.app.bound.enter', 'start.app.bound.tick(1)', 'start.app.bound.leave', 'start.app.attaching.enter', // parent 'attaching' starts in parallel with child activation 'start.p-1.binding.enter', 'start.p-2.binding.enter', 'start.app.attaching.tick(1)', 'start.app.attaching.leave', 'start.p-1.binding.tick(1)', 'start.p-1.binding.leave', 'start.p-2.binding.tick(1)', 'start.p-2.binding.leave', 'start.p-1.bound.enter', 'start.p-2.bound.enter', 'start.p-1.bound.tick(1)', 'start.p-1.bound.leave', 'start.p-2.bound.tick(1)', 'start.p-2.bound.leave', 'start.p-1.attaching.enter', // parent 'attaching' starts in parallel with child activation 'start.c-1.binding.enter', 'start.p-2.attaching.enter', // parent 'attaching' starts in parallel with child activation 'start.c-2.binding.enter', 'start.p-1.attaching.tick(1)', 'start.p-1.attaching.leave', 'start.c-1.binding.tick(1)', 'start.c-1.binding.leave', 'start.p-2.attaching.tick(1)', 'start.p-2.attaching.leave', 'start.c-2.binding.tick(1)', 'start.c-2.binding.leave', 'start.c-1.bound.enter', 'start.c-2.bound.enter', 'start.c-1.bound.tick(1)', 'start.c-1.bound.leave', 'start.c-2.bound.tick(1)', 'start.c-2.bound.leave', 'start.c-1.attaching.enter', 'start.c-2.attaching.enter', 'start.c-1.attaching.tick(1)', 'start.c-1.attaching.leave', 'start.c-2.attaching.tick(1)', 'start.c-2.attaching.leave', // 'attached' runs bottom-up and children are awaited before parents 'start.c-1.attached.enter', 'start.c-2.attached.enter', 'start.c-1.attached.tick(1)', 'start.c-1.attached.leave', 'start.c-2.attached.tick(1)', 'start.c-2.attached.leave', 'start.p-1.attached.enter', 'start.p-2.attached.enter', 'start.p-1.attached.tick(1)', 'start.p-1.attached.leave', 'start.p-2.attached.tick(1)', 'start.p-2.attached.leave', 'start.app.attached.enter', 'start.app.attached.tick(1)', 'start.app.attached.leave', // all 'detaching' hooks are started bottom-up in parallel, and all awaited before any 'unbinding' hooks are started 'stop.c-1.detaching.enter', 'stop.p-1.detaching.enter', 'stop.c-2.detaching.enter', 'stop.p-2.detaching.enter', 'stop.app.detaching.enter', 'stop.c-1.detaching.tick(1)', 'stop.c-1.detaching.leave', 'stop.p-1.detaching.tick(1)', 'stop.p-1.detaching.leave', 'stop.c-2.detaching.tick(1)', 'stop.c-2.detaching.leave', 'stop.p-2.detaching.tick(1)', 'stop.p-2.detaching.leave', 'stop.app.detaching.tick(1)', 'stop.app.detaching.leave', // all 'unbinding' hooks are started bottom-up in parallel, and all awaited before any 'dispose' hooks are started 'stop.c-1.unbinding.enter', 'stop.p-1.unbinding.enter', 'stop.c-2.unbinding.enter', 'stop.p-2.unbinding.enter', 'stop.app.unbinding.enter', 'stop.c-1.unbinding.tick(1)', 'stop.c-1.unbinding.leave', 'stop.p-1.unbinding.tick(1)', 'stop.p-1.unbinding.leave', 'stop.c-2.unbinding.tick(1)', 'stop.c-2.unbinding.leave', 'stop.p-2.unbinding.tick(1)', 'stop.p-2.unbinding.leave', 'stop.app.unbinding.tick(1)', 'stop.app.unbinding.leave', // all 'dispose' hooks are run top-down 'stop.app.dispose.enter', 'stop.app.dispose.leave', 'stop.p-1.dispose.enter', 'stop.p-1.dispose.leave', 'stop.c-1.dispose.enter', 'stop.c-1.dispose.leave', 'stop.p-2.dispose.enter', 'stop.p-2.dispose.leave', 'stop.c-2.dispose.enter', 'stop.c-2.dispose.leave', ]); }); it(`activation hooks are arranged as expected in a complex tree when all are async but 'attaching' taking much longer than the rest`, async function () { const { mgr, p, au, host } = createFixture(); const hookSpec: IDelayedInvokerSpec = { ...allSyncSpecs, binding: () => DelayedInvoker.binding(mgr, p, 1), bound: () => DelayedInvoker.bound(mgr, p, 1), attaching: () => DelayedInvoker.attaching(mgr, p, 10), attached: () => DelayedInvoker.attached(mgr, p, 1), }; @customElement({ name: 'c-1', template: null })class C1 extends TestVM { public constructor() { super(mgr, p, hookSpec); } } @customElement({ name: 'c-2', template: null })class C2 extends TestVM { public constructor() { super(mgr, p, hookSpec); } } @customElement({ name: 'p-1', template: '<c-1></c-1>', dependencies: [C1] })class P1 extends TestVM { public constructor() { super(mgr, p, hookSpec); } } @customElement({ name: 'p-2', template: '<c-2></c-2>', dependencies: [C2] })class P2 extends TestVM { public constructor() { super(mgr, p, hookSpec); } } @customElement({ name: 'app', template: '<p-1></p-1><p-2></p-2>', dependencies: [P1, P2] })class App extends TestVM { public constructor() { super(mgr, p, hookSpec); } } au.app({ host, component: App }); mgr.setPrefix('start'); await au.start(); mgr.setPrefix('stop'); await au.stop(true); verifyInvocationsEqual(mgr.fullNotifyHistory, [ // app.'binding' is awaited before starting app.'bound' 'start.app.binding.enter', 'start.app.binding.tick(1)', 'start.app.binding.leave', // app.'bound' is awaited before starting app.'attaching' 'start.app.bound.enter', 'start.app.bound.tick(1)', 'start.app.bound.leave', // app.'attaching' is awaited in parallel with p-1 & p-2 activation before starting app.'attached' 'start.app.attaching.enter', 'start.p-1.binding.enter', 'start.p-2.binding.enter', 'start.app.attaching.tick(1)', 'start.p-1.binding.tick(1)', 'start.p-1.binding.leave', 'start.p-2.binding.tick(1)', 'start.p-2.binding.leave', 'start.app.attaching.tick(2)', 'start.p-1.bound.enter', 'start.p-2.bound.enter', 'start.app.attaching.tick(3)', 'start.p-1.bound.tick(1)', 'start.p-1.bound.leave', 'start.p-2.bound.tick(1)', 'start.p-2.bound.leave', 'start.app.attaching.tick(4)', // p-1.'attaching' is awaited in parallel with its children (c-1) activation before starting p-1.'attached' 'start.p-1.attaching.enter', 'start.c-1.binding.enter', // p-2.'attaching' is awaited in parallel with its children (c-2) activation before starting p-2.'attached' 'start.p-2.attaching.enter', 'start.c-2.binding.enter', 'start.app.attaching.tick(5)', 'start.p-1.attaching.tick(1)', 'start.c-1.binding.tick(1)', 'start.c-1.binding.leave', 'start.p-2.attaching.tick(1)', 'start.c-2.binding.tick(1)', 'start.c-2.binding.leave', 'start.app.attaching.tick(6)', 'start.p-1.attaching.tick(2)', 'start.c-1.bound.enter', 'start.p-2.attaching.tick(2)', 'start.c-2.bound.enter', 'start.app.attaching.tick(7)', 'start.p-1.attaching.tick(3)', 'start.c-1.bound.tick(1)', 'start.c-1.bound.leave', 'start.p-2.attaching.tick(3)', 'start.c-2.bound.tick(1)', 'start.c-2.bound.leave', 'start.app.attaching.tick(8)', 'start.p-1.attaching.tick(4)', // c-1.'attaching' is awaited before starting c-1.'attached' 'start.c-1.attaching.enter', 'start.p-2.attaching.tick(4)', // c-2.'attaching' is awaited before starting c-2.'attached' 'start.c-2.attaching.enter', 'start.app.attaching.tick(9)', 'start.p-1.attaching.tick(5)', 'start.c-1.attaching.tick(1)', 'start.p-2.attaching.tick(5)', 'start.c-2.attaching.tick(1)', 'start.app.attaching.tick(10)', // app.'attaching' is now done, but p-1/c-1 & p-2/c-2 activation is still ongoing so not starting app.'attached' yet 'start.app.attaching.leave', 'start.p-1.attaching.tick(6)', 'start.c-1.attaching.tick(2)', 'start.p-2.attaching.tick(6)', 'start.c-2.attaching.tick(2)', 'start.p-1.attaching.tick(7)', 'start.c-1.attaching.tick(3)', 'start.p-2.attaching.tick(7)', 'start.c-2.attaching.tick(3)', 'start.p-1.attaching.tick(8)', 'start.c-1.attaching.tick(4)', 'start.p-2.attaching.tick(8)', 'start.c-2.attaching.tick(4)', 'start.p-1.attaching.tick(9)', 'start.c-1.attaching.tick(5)', 'start.p-2.attaching.tick(9)', 'start.c-2.attaching.tick(5)', 'start.p-1.attaching.tick(10)', // p-1.'attaching' is now done, but c-1 activation is still ongoing so not starting p-1.'attached' yet 'start.p-1.attaching.leave', 'start.c-1.attaching.tick(6)', 'start.p-2.attaching.tick(10)', // p-2.'attaching' is now done, but c-2 activation is still ongoing so not starting p-2.'attached' yet 'start.p-2.attaching.leave', 'start.c-2.attaching.tick(6)', 'start.c-1.attaching.tick(7)', 'start.c-2.attaching.tick(7)', 'start.c-1.attaching.tick(8)', 'start.c-2.attaching.tick(8)', 'start.c-1.attaching.tick(9)', 'start.c-2.attaching.tick(9)', // c-1.'attaching' and c-2.'attaching' are now done 'start.c-1.attaching.tick(10)', 'start.c-1.attaching.leave', 'start.c-2.attaching.tick(10)', 'start.c-2.attaching.leave', // c-1 and c-2 'attaching' finished, starting c-1 and c-2 'attached' 'start.c-1.attached.enter', 'start.c-2.attached.enter', 'start.c-1.attached.tick(1)', 'start.c-1.attached.leave', 'start.c-2.attached.tick(1)', 'start.c-2.attached.leave', // c-1 and c-2 'attached' (last part of activation) finished, starting p-1 and p-2 'attached' 'start.p-1.attached.enter', 'start.p-2.attached.enter', 'start.p-1.attached.tick(1)', 'start.p-1.attached.leave', 'start.p-2.attached.tick(1)', 'start.p-2.attached.leave', // p-1 and p-2 'attached' (last part of activation) finished, starting app 'attached' 'start.app.attached.enter', 'start.app.attached.tick(1)', 'start.app.attached.leave', // nothing of interest here: all of these are synchronous and do not demonstrate parallelism (not part of this test) 'stop.c-1.detaching.enter', 'stop.c-1.detaching.leave', 'stop.p-1.detaching.enter', 'stop.p-1.detaching.leave', 'stop.c-2.detaching.enter', 'stop.c-2.detaching.leave', 'stop.p-2.detaching.enter', 'stop.p-2.detaching.leave', 'stop.app.detaching.enter', 'stop.app.detaching.leave', 'stop.c-1.unbinding.enter', 'stop.c-1.unbinding.leave', 'stop.p-1.unbinding.enter', 'stop.p-1.unbinding.leave', 'stop.c-2.unbinding.enter', 'stop.c-2.unbinding.leave', 'stop.p-2.unbinding.enter', 'stop.p-2.unbinding.leave', 'stop.app.unbinding.enter', 'stop.app.unbinding.leave', 'stop.app.dispose.enter', 'stop.app.dispose.leave', 'stop.p-1.dispose.enter', 'stop.p-1.dispose.leave', 'stop.c-1.dispose.enter', 'stop.c-1.dispose.leave', 'stop.p-2.dispose.enter', 'stop.p-2.dispose.leave', 'stop.c-2.dispose.enter', 'stop.c-2.dispose.leave', ]); }); it(`separate activate + deactivate can be aligned on attaching/detaching`, async function () { const { mgr, p, au, host } = createFixture(); const componentSpec: IDelayedInvokerSpec = { ...allSyncSpecs, attaching: () => DelayedInvoker.attaching(mgr, p, 3), detaching: () => DelayedInvoker.detaching(mgr, p, 3), }; const appSpec: IDelayedInvokerSpec = { ...allSyncSpecs, }; @customElement({ name: 'c-1', template: null })class C1 extends TestVM { public constructor() { super(mgr, p, componentSpec); } } @customElement({ name: 'c-2', template: null })class C2 extends TestVM { public constructor() { super(mgr, p, componentSpec); } } @customElement({ name: 'p-1', template: '<c-1></c-1>', dependencies: [C1] })class P1 extends TestVM { public constructor() { super(mgr, p, componentSpec); } } @customElement({ name: 'p-2', template: '<c-2></c-2>', dependencies: [C2] })class P2 extends TestVM { public constructor() { super(mgr, p, componentSpec); } } @customElement({ name: 'app', template: '<p-1 if.bind="n===1"></p-1><p-2 if.bind="n===2"></p-2>', dependencies: [P1, P2] }) class App extends TestVM { public n: number = 1; public constructor() { super(mgr, p, appSpec); } } au.app({ host, component: App }); const app = au.root.controller.viewModel as App; mgr.setPrefix('start'); await au.start(); mgr.setPrefix('swap'); app.n = 2; await au.root.work.wait(); mgr.setPrefix('stop'); await au.stop(true); verifyInvocationsEqual(mgr.fullNotifyHistory, [ 'start.app.binding.enter', 'start.app.binding.leave', 'start.app.bound.enter', 'start.app.bound.leave', 'start.app.attaching.enter', 'start.app.attaching.leave', 'start.p-1.binding.enter', 'start.p-1.binding.leave', 'start.p-1.bound.enter', 'start.p-1.bound.leave', 'start.p-1.attaching.enter', 'start.c-1.binding.enter', 'start.c-1.binding.leave', 'start.c-1.bound.enter', 'start.c-1.bound.leave', 'start.c-1.attaching.enter', 'start.p-1.attaching.tick(1)', 'start.c-1.attaching.tick(1)', 'start.p-1.attaching.tick(2)', 'start.c-1.attaching.tick(2)', 'start.p-1.attaching.tick(3)', 'start.p-1.attaching.leave', 'start.c-1.attaching.tick(3)', 'start.c-1.attaching.leave', 'start.c-1.attached.enter', 'start.c-1.attached.leave', 'start.p-1.attached.enter', 'start.p-1.attached.leave', 'start.app.attached.enter', 'start.app.attached.leave', 'swap.c-1.detaching.enter', 'swap.p-1.detaching.enter', 'swap.p-2.binding.enter', 'swap.p-2.binding.leave', 'swap.p-2.bound.enter', 'swap.p-2.bound.leave', 'swap.p-2.attaching.enter', 'swap.c-2.binding.enter', 'swap.c-2.binding.leave', 'swap.c-2.bound.enter', 'swap.c-2.bound.leave', 'swap.c-2.attaching.enter', // start of the part that's relevant to this test 'swap.c-1.detaching.tick(1)', 'swap.p-1.detaching.tick(1)', 'swap.p-2.attaching.tick(1)', 'swap.c-2.attaching.tick(1)', 'swap.c-1.detaching.tick(2)', 'swap.p-1.detaching.tick(2)', 'swap.p-2.attaching.tick(2)', 'swap.c-2.attaching.tick(2)', 'swap.c-1.detaching.tick(3)', 'swap.c-1.detaching.leave', 'swap.p-1.detaching.tick(3)', 'swap.p-1.detaching.leave', 'swap.p-2.attaching.tick(3)', 'swap.p-2.attaching.leave', 'swap.c-2.attaching.tick(3)', 'swap.c-2.attaching.leave', // end of the part that's relevant to this test 'swap.c-1.unbinding.enter', 'swap.c-1.unbinding.leave', 'swap.p-1.unbinding.enter', 'swap.p-1.unbinding.leave', 'swap.c-2.attached.enter', 'swap.c-2.attached.leave', 'swap.p-2.attached.enter', 'swap.p-2.attached.leave', 'stop.c-2.detaching.enter', 'stop.p-2.detaching.enter', 'stop.app.detaching.enter', 'stop.app.detaching.leave', 'stop.c-2.detaching.tick(1)', 'stop.p-2.detaching.tick(1)', 'stop.c-2.detaching.tick(2)', 'stop.p-2.detaching.tick(2)', 'stop.c-2.detaching.tick(3)', 'stop.c-2.detaching.leave', 'stop.p-2.detaching.tick(3)', 'stop.p-2.detaching.leave', 'stop.c-2.unbinding.enter', 'stop.c-2.unbinding.leave', 'stop.p-2.unbinding.enter', 'stop.p-2.unbinding.leave', 'stop.app.unbinding.enter', 'stop.app.unbinding.leave', 'stop.app.dispose.enter', 'stop.app.dispose.leave', 'stop.p-1.dispose.enter', 'stop.p-1.dispose.leave', 'stop.c-1.dispose.enter', 'stop.c-1.dispose.leave', 'stop.p-2.dispose.enter', 'stop.p-2.dispose.leave', 'stop.c-2.dispose.enter', 'stop.c-2.dispose.leave', ]); }); }); }); async function waitTicks(n: number): Promise<void> { for (let i = 0; i < n; ++i) { await Promise.resolve(); } } const hookNames = ['binding', 'bound', 'attaching', 'attached', 'detaching', 'unbinding'] as const; type HookName = typeof hookNames[number] | 'dispose'; interface IDelayedInvokerSpec { binding(mgr: INotifierManager, p: IPlatform): DelayedInvoker<'binding'>; bound(mgr: INotifierManager, p: IPlatform): DelayedInvoker<'bound'>; attaching(mgr: INotifierManager, p: IPlatform): DelayedInvoker<'attaching'>; attached(mgr: INotifierManager, p: IPlatform): DelayedInvoker<'attached'>; detaching(mgr: INotifierManager, p: IPlatform): DelayedInvoker<'detaching'>; unbinding(mgr: INotifierManager, p: IPlatform): DelayedInvoker<'unbinding'>; dispose(mgr: INotifierManager, p: IPlatform): DelayedInvoker<'dispose'>; toString(): string; } abstract class TestVM implements IViewModel { public readonly $controller!: ICustomElementController<this>; public get name(): string { return this.$controller.definition.name; } public readonly bindingDI: DelayedInvoker<'binding'>; public readonly boundDI: DelayedInvoker<'bound'>; public readonly attachingDI: DelayedInvoker<'attaching'>; public readonly attachedDI: DelayedInvoker<'attached'>; public readonly detachingDI: DelayedInvoker<'detaching'>; public readonly unbindingDI: DelayedInvoker<'unbinding'>; public readonly disposeDI: DelayedInvoker<'dispose'>; public constructor(mgr: INotifierManager, p: IPlatform, { binding, bound, attaching, attached, detaching, unbinding, dispose }: IDelayedInvokerSpec) { this.bindingDI = binding(mgr, p); this.boundDI = bound(mgr, p); this.attachingDI = attaching(mgr, p); this.attachedDI = attached(mgr, p); this.detachingDI = detaching(mgr, p); this.unbindingDI = unbinding(mgr, p); this.disposeDI = dispose(mgr, p); } public binding(i: HC, p: HPC, f: LF): void | Promise<void> { return this.bindingDI.invoke(this, () => { this.$binding(i, p, f); }); } public bound(i: HC, p: HPC, f: LF): void | Promise<void> { return this.boundDI.invoke(this, () => { this.$bound(i, p, f); }); } public attaching(i: HC, p: HPC, f: LF): void | Promise<void> { return this.attachingDI.invoke(this, () => { this.$attaching(i, p, f); }); } public attached(i: HC, f: LF): void | Promise<void> { return this.attachedDI.invoke(this, () => { this.$attached(i, f); }); } public detaching(i: HC, p: HPC, f: LF): void | Promise<void> { return this.detachingDI.invoke(this, () => { this.$detaching(i, p, f); }); } public unbinding(i: HC, p: HPC, f: LF): void | Promise<void> { return this.unbindingDI.invoke(this, () => { this.$unbinding(i, p, f); }); } public dispose(): void { void this.disposeDI.invoke(this, () => { this.$dispose(); }); } protected $binding(_i: HC, _p: HPC, _f: LF): void { /* do nothing */ } protected $bound(_i: HC, _p: HPC, _f: LF): void { /* do nothing */ } protected $attaching(_i: HC, _p: HPC, _f: LF): void { /* do nothing */ } protected $attached(_i: HC, _f: LF): void { /* do nothing */ } protected $detaching(_i: HC, _p: HPC, _f: LF): void { /* do nothing */ } protected $unbinding(_i: HC, _p: HPC, _f: LF): void { /* do nothing */ } protected $dispose(this: Partial<Writable<this>>): void { this.bindingDI = void 0; this.boundDI = void 0; this.attachingDI = void 0; this.attachedDI = void 0; this.detachingDI = void 0; this.unbindingDI = void 0; this.disposeDI = void 0; } } class Notifier { public readonly p: IPlatform; public readonly entryHistory: string[] = []; public readonly fullHistory: string[] = []; public constructor( public readonly mgr: NotifierManager, public readonly name: HookName, ) { this.p = mgr.p; } public enter(vm: TestVM): void { this.entryHistory.push(vm.name); this.fullHistory.push(`${vm.name}.enter`); this.mgr.enter(vm, this); } public leave(vm: TestVM): void { this.fullHistory.push(`${vm.name}.leave`); this.mgr.leave(vm, this); } public tick(vm: TestVM, i: number): void { this.fullHistory.push(`${vm.name}.tick(${i})`); this.mgr.tick(vm, this, i); } public dispose(this: Partial<Writable<this>>): void { this.entryHistory = void 0; this.fullHistory = void 0; this.p = void 0; this.mgr = void 0; } } const INotifierConfig = DI.createInterface<INotifierConfig>('INotifierConfig'); interface INotifierConfig extends NotifierConfig {} class NotifierConfig { public constructor( public readonly resolveLabels: string[], public readonly resolveTimeoutMs: number, ) {} } const INotifierManager = DI.createInterface<INotifierManager>('INotifierManager', x => x.singleton(NotifierManager)); interface INotifierManager extends NotifierManager {} class NotifierManager { public readonly entryNotifyHistory: string[] = []; public readonly fullNotifyHistory: string[] = []; public prefix: string = ''; public constructor( @IPlatform public readonly p: IPlatform, ) {} public readonly binding: Notifier = new Notifier(this, 'binding'); public readonly bound: Notifier = new Notifier(this, 'bound'); public readonly attaching: Notifier = new Notifier(this, 'attaching'); public readonly attached: Notifier = new Notifier(this, 'attached'); public readonly detaching: Notifier = new Notifier(this, 'detaching'); public readonly unbinding: Notifier = new Notifier(this, 'unbinding'); public readonly dispose: Notifier = new Notifier(this, 'dispose'); public enter(vm: TestVM, tracker: Notifier): void { const label = `${this.prefix}.${vm.name}.${tracker.name}`; this.entryNotifyHistory.push(label); this.fullNotifyHistory.push(`${label}.enter`); } public leave(vm: TestVM, tracker: Notifier): void { const label = `${this.prefix}.${vm.name}.${tracker.name}`; this.fullNotifyHistory.push(`${label}.leave`); } public tick(vm: TestVM, tracker: Notifier, i: number): void { const label = `${this.prefix}.${vm.name}.${tracker.name}`; this.fullNotifyHistory.push(`${label}.tick(${i})`); } public setPrefix(prefix: string): void { this.prefix = prefix; } public $dispose(this: Partial<Writable<this>>): void { this.binding.dispose(); this.bound.dispose(); this.attaching.dispose(); this.attached.dispose(); this.detaching.dispose(); this.unbinding.dispose(); this.dispose.dispose(); this.entryNotifyHistory = void 0; this.fullNotifyHistory = void 0; this.p = void 0; this.binding = void 0; this.bound = void 0; this.attaching = void 0; this.attached = void 0; this.detaching = void 0; this.unbinding = void 0; this.$dispose = void 0; } } class DelayedInvoker<T extends HookName> { public constructor( public readonly mgr: INotifierManager, public readonly p: IPlatform, public readonly name: T, public readonly ticks: number | null, ) {} public static binding(mgr: INotifierManager, p: IPlatform, ticks: number | null = null): DelayedInvoker<'binding'> { return new DelayedInvoker(mgr, p, 'binding', ticks); } public static bound(mgr: INotifierManager, p: IPlatform, ticks: number | null = null): DelayedInvoker<'bound'> { return new DelayedInvoker(mgr, p, 'bound', ticks); } public static attaching(mgr: INotifierManager, p: IPlatform, ticks: number | null = null): DelayedInvoker<'attaching'> { return new DelayedInvoker(mgr, p, 'attaching', ticks); } public static attached(mgr: INotifierManager, p: IPlatform, ticks: number | null = null): DelayedInvoker<'attached'> { return new DelayedInvoker(mgr, p, 'attached', ticks); } public static detaching(mgr: INotifierManager, p: IPlatform, ticks: number | null = null): DelayedInvoker<'detaching'> { return new DelayedInvoker(mgr, p, 'detaching', ticks); } public static unbinding(mgr: INotifierManager, p: IPlatform, ticks: number | null = null): DelayedInvoker<'unbinding'> { return new DelayedInvoker(mgr, p, 'unbinding', ticks); } public static dispose(mgr: INotifierManager, p: IPlatform, ticks: number | null = null): DelayedInvoker<'dispose'> { return new DelayedInvoker(mgr, p, 'dispose', ticks); } public invoke(vm: TestVM, cb: () => void): void | Promise<void> { if (this.ticks === null) { this.mgr[this.name].enter(vm); cb(); this.mgr[this.name].leave(vm); } else { let i = -1; let resolve: () => void; const p = new Promise<void>(r => { resolve = r; }); const next = (): void => { if (++i === 0) { this.mgr[this.name].enter(vm); } else { this.mgr[this.name].tick(vm, i); } if (i < this.ticks) { void Promise.resolve().then(next); } else { cb(); this.mgr[this.name].leave(vm); resolve(); } }; next(); return p; } } public toString(): string { let str = this.name as string; if (this.ticks !== null) { str = `${str}.${this.ticks}t`; } return str; } } function verifyInvocationsEqual(actual: string[], expected: string[]): void { const groupNames = new Set<string>(); actual.forEach(x => groupNames.add(x.slice(0, x.indexOf('.')))); expected.forEach(x => groupNames.add(x.slice(0, x.indexOf('.')))); const expectedGroups: Record<string, string[]> = {}; const actualGroups: Record<string, string[]> = {}; for (const groupName of groupNames) { expectedGroups[groupName] = expected.filter(x => x.startsWith(`${groupName}.`)); actualGroups[groupName] = actual.filter(x => x.startsWith(`${groupName}.`)); } const errors: string[] = []; for (const prefix in expectedGroups) { expected = expectedGroups[prefix]; actual = actualGroups[prefix]; const len = Math.max(actual.length, expected.length); for (let i = 0; i < len; ++i) { const $actual = actual[i]; const $expected = expected[i]; if ($actual === $expected) { errors.push(` OK : ${$actual}`); } else { errors.push(`NOT OK : ${$actual} (expected: ${$expected})`); } } } if (errors.some(e => e.startsWith('N'))) { throw new Error(`Failed assertion: invocation mismatch\n - ${errors.join('\n - ')})`); } else { // fallback just to make sure there's no bugs in this function causing false positives assert.deepStrictEqual(actual, expected); } }
the_stack
const enum AzureIotEvent { Connected = 1, Disconnected = 2, Error = 3, GotTwinResponse = 100, } namespace azureiot { export const SECRETS_KEY = "azureiot" export let logPriority = ConsolePriority.Debug; type SMap<T> = { [s: string]: T; } export type Json = any; let _mqttClient: mqtt.Client; let _messageBusId: number; let _receiveHandler: (msg: Json, sysProps: SMap<string>) => void; let _methodHandlers: SMap<(msg: Json) => Json>; let twinRespHandlers: SMap<(status: number, body: any) => void> function log(msg: string) { console.add(logPriority, "azureiot: " + msg); } export function mqttClient(skipCreate?: boolean): mqtt.Client { if (!_mqttClient && !skipCreate) { log("creating mqtt client") _mqttClient = createMQTTClient(); } return _mqttClient; } function generateSasToken(resourceUri: string, signingKey: string, expiresEpoch: number) { const key = Buffer.fromBase64(signingKey) resourceUri = net.urlencode(resourceUri) const toSign = resourceUri + "\n" + expiresEpoch const sig = net.urlencode(crypto.sha256Hmac(key, Buffer.fromUTF8(toSign)).toBase64()) const token = `sr=${resourceUri}&se=${expiresEpoch}&sig=${sig}` return token } export function hubName() { return connectionStringPart("HostName") } export function hubDeviceId() { return connectionStringPart("DeviceId") } function messageBusId() { if (!_messageBusId) _messageBusId = control.allocateEventSource(); return _messageBusId } function createMQTTClient() { messageBusId() const iotHubHostName = hubName() const deviceId = hubDeviceId() if (!iotHubHostName || !deviceId) throw "invalid connection string" const connStringParts = parseConnectionString(); let sasToken = connStringParts["SharedAccessSignature"]; if (!sasToken) // token valid until year 2255; in future we may try something more short-lived sasToken = generateSasToken(`${iotHubHostName}/devices/${deviceId}`, connStringParts["SharedAccessKey"], 9000000000) const opts: mqtt.IConnectionOptions = { host: iotHubHostName, /* port: 8883, overriden based on platform */ username: `${iotHubHostName}/${deviceId}/?api-version=2018-06-30`, password: "SharedAccessSignature " + sasToken, clientId: deviceId } const c = new mqtt.Client(opts); const evid = messageBusId() c.on('connected', () => { log("connected") control.raiseEvent(evid, AzureIotEvent.Connected) }); c.on('disconnected', () => { log("disconnected") control.raiseEvent(evid, AzureIotEvent.Disconnected) }); c.on('error', (msg) => { log("error: " + msg) control.raiseEvent(evid, AzureIotEvent.Error) }); c.on('receive', (packet: mqtt.IMessage) => { log("unhandled msg: " + packet.topic + " / " + packet.content.toString()) }); c.connect(); return c; } function splitPair(kv: string): string[] { const i = kv.indexOf('='); if (i < 0) return [kv, ""]; else return [kv.slice(0, i), kv.slice(i + 1)]; } function parsePropertyBag(msg: string, separator?: string): SMap<string> { const r: SMap<string> = {}; if (msg && typeof msg === "string") msg.split(separator || "&") .map(kv => splitPair(kv)) .filter(parts => !!parts[1].length) .forEach(parts => r[net.urldecode(parts[0])] = net.urldecode(parts[1])); return r; } function parseConnectionString() { try { const connString = settings.programSecrets.readSecret(SECRETS_KEY); const connStringParts = parsePropertyBag(connString, ";"); return connStringParts } catch { console.debug(`clearing invalid azure iot connection string`) settings.programSecrets.setSecret(SECRETS_KEY, "") return {} } } function connectionStringPart(name: string) { const connStringParts = parseConnectionString() const value = connStringParts[name]; return value || "" } function encodeQuery(props: SMap<string>): string { const keys = Object.keys(props) if (keys.length == 0) return "" return "?" + keys .map(k => `${net.urlencode(k)}=${net.urlencode(props[k])}`) .join('&'); } export function setConnectionString(connectionString: string) { disconnect() settings.programSecrets.setSecret(SECRETS_KEY, connectionString) parseConnectionString() } /** * Disconnects the hub if any */ export function disconnect() { const c = mqttClient(true) if (c) { try { c.disconnect() } catch { // just ignore errors disconnecting } } } /** * Connects to the IoT hub */ export function connect() { const c = mqttClient(); if (!c.connected) { c.connect() // start connect if not started yet // busy wait for connection const start = control.millis() const timeout = 30000 while (!c.connected && control.millis() - start < timeout) { pause(1000) } if (!c.connected) throw "connection failed" } } /** * Registers code when the MQTT client gets connected or disconnected * @param event * @param handler */ export function onEvent(event: AzureIotEvent, handler: () => void) { const evid = messageBusId() control.onEvent(evid, event, handler); try { const c = mqttClient(true); if (c && c.connected) // raise connected event by default control.raiseEvent(evid, AzureIotEvent.Connected); } catch { } } /** * Indicates if the MQTT client is connected */ //% export function isConnected(): boolean { try { const c = mqttClient(true); return !!c && !!c.connected; } catch { return false } } /** * Send a message via mqtt * @param msg */ //% export function publishMessageJSON(msg: Json, sysProps?: SMap<string>) { const c = mqttClient(); let topic = `devices/${c.opt.clientId}/messages/events/`; if (sysProps) topic += encodeQuery(sysProps); const m = JSON.stringify(msg) msg = null // qos, retained are not supported c.publish(topic, m); } /** * Send a message via mqtt * @param msg */ //% export function publishMessageBuffer(msg: Buffer, sysProps?: SMap<string>) { const c = mqttClient(); let topic = `devices/${c.opt.clientId}/messages/events/`; if (sysProps) topic += encodeQuery(sysProps); // qos, retained are not supported c.publish(topic, msg); } /** * Send a message via mqtt * @param msg */ //% export function publishMessageHex(msg: Buffer, len?: number, sysProps?: SMap<string>) { const c = mqttClient(); let topic = `devices/${c.opt.clientId}/messages/events/`; if (sysProps) topic += encodeQuery(sysProps); if (len == null) len = msg.length if (len > msg.length) { log(`len too long: ${len}/${msg.length}`) len = msg.length } // qos, retained are not supported if (c.startPublish(topic, len * 2)) { const chunk = 128 for (let ptr = 0; ptr < len; ptr += chunk) c.continuePublish(Buffer.fromUTF8(msg.slice(ptr, Math.min(chunk, len - ptr)).toHex())) c.finishPublish() } } /** * Registers code to run when a message is received * @param handler */ //% export function onMessageReceived(handler: (body: Json, sysProps: SMap<string>) => void) { const c = mqttClient(); if (!_receiveHandler) { c.subscribe(`devices/${c.opt.clientId}/messages/devicebound/#`, handleDeviceBound); /* c.subscribe('$iothub/twin/PATCH/properties/desired/#') */ } _receiveHandler = handler; } function parseTopicArgs(topic: string) { const qidx = topic.indexOf("?") if (qidx >= 0) return parsePropertyBag(topic.slice(qidx + 1)) return {} } function handleDeviceBound(packet: mqtt.IMessage) { if (!_receiveHandler) return; // nobody's listening // TODO this needs some testing const sysProps = parseTopicArgs(packet.topic) _receiveHandler(JSON.parse(packet.content.toString()), sysProps); } function handleMethod(msg: mqtt.IMessage) { const props = parseTopicArgs(msg.topic) const qidx = msg.topic.indexOf("/?") const methodName = msg.topic.slice(21, qidx) log("method: '" + methodName + "'; " + JSON.stringify(props)) let status = 200 let resp: any = {} if (!_methodHandlers[methodName]) { log("method not found: '" + methodName + "'") status = 404 } else { const h = _methodHandlers[methodName] const resp2 = h(JSON.parse(msg.content.toString())) if (resp2) resp = resp2 if (resp["_status"] != null) { status = resp["_status"] resp["_status"] = undefined } log("method: '" + methodName + "' status=" + status) } const c = mqttClient(); c.publish('$iothub/methods/res/' + status + "/?$rid=" + props["$rid"], JSON.stringify(resp)) } // $iothub/twin/res/{status}/?$rid={request id} function twinResponse(msg: mqtt.IMessage) { const args = parseTopicArgs(msg.topic) const h = twinRespHandlers[args["$rid"]] const status = parseInt(msg.topic.slice(17)) // log(`twin resp: ${status} ${msg.content.toHex()} ${msg.content.toString()}`) if (h) { delete twinRespHandlers[args["$rid"]] h(status, JSON.parse(msg.content.toString() || "{}")) } } export class ValueAwaiter { private evid: number private value: any constructor() { this.evid = control.allocateNotifyEvent() } setValue(v: any) { this.value = v control.raiseEvent(DAL.DEVICE_ID_NOTIFY, this.evid) this.evid = -1 } wait() { if (this.evid < 0) return this.value control.waitForEvent(DAL.DEVICE_ID_NOTIFY, this.evid) return this.value } } function twinReq(path: string, msg?: string): Json { const c = mqttClient(); if (!twinRespHandlers) { twinRespHandlers = {} c.subscribe("$iothub/twin/res/#", twinResponse) } const rid = Math.randomRange(100000000, 900000000) + "" const va = new ValueAwaiter() twinRespHandlers[rid] = (status, body) => { if (status == 204 || status == 200) { va.setValue(body) } else { log(`twin error -> ${status} ${JSON.stringify(body)}`) va.setValue(null) } } c.publish(`$iothub/twin/${path}/?$rid=${rid}`, msg) return va.wait() } export function getTwin(): Json { return twinReq("GET") } export function patchTwin(patch: Json) { const p = JSON.stringify(patch) if (p == "{}") log("skipping empty twin patch") else { log(`twin patch: ${JSON.stringify(patch)}`) twinReq("PATCH/properties/reported", p) } } export function computePatch(curr: Json, target: Json) { const patch: Json = {} for (const k of Object.keys(curr)) { const vt = target[k] if (k[0] == "$") continue if (vt === undefined) { patch[k] = null } else { const vc = curr[k] if (typeof vt == "object") if (typeof vc == "object") { const p0 = computePatch(vc, vt) if (Object.keys(p0).length > 0) patch[k] = p0 } else { patch[k] = vt } else if (vc != vt) patch[k] = vt } } for (const k of Object.keys(target)) { if (curr[k] === undefined && k[0] != "$") patch[k] = target[k] } return patch } export function applyPatch(trg: Json, patch: Json) { for (const k of Object.keys(patch)) { const v = patch[k] if (v === null) { delete trg[k] } else if (typeof v == "object") { if (!trg[k]) trg[k] = {} applyPatch(trg[k], v) } else { trg[k] = v } } } export function onTwinUpdate(handler: (twin: Json, patch: Json) => void) { const c = mqttClient() let currTwin: Json = null let lastVersion: number c.subscribe("$iothub/twin/PATCH/properties/desired/#", msg => { if (!currTwin) return const sysProps = parseTopicArgs(msg.topic) const ver = parseInt(sysProps["$version"]) if (ver <= lastVersion) { log(`skipping twin update: ${ver}`) return } const update = JSON.parse(msg.content.toString()) applyPatch(currTwin["desired"], update) handler(currTwin, update) }) currTwin = getTwin() lastVersion = currTwin["desired"]["$version"] handler(currTwin, currTwin["desired"]) } export function onMethod(methodName: string, handler: (msg: Json) => Json) { const c = mqttClient(); if (!_methodHandlers) { if (!c.connected) throw "azure iot hub not connected" _methodHandlers = {} c.subscribe('$iothub/methods/POST/#', handleMethod) } _methodHandlers[methodName] = handler } }
the_stack
* @packageDocumentation * @module asset-manager */ import { Asset } from '../assets/asset'; import SceneAsset from '../assets/scene-asset'; import { legacyCC } from '../global-exports'; import { error, errorID } from '../platform/debug'; import Config, { IAddressableInfo, IAssetInfo, IConfigOption, ISceneInfo } from './config'; import releaseManager from './release-manager'; import RequestItem from './request-item'; import { assets, AssetType, bundles, CompleteCallbackWithData, CompleteCallbackNoData, IAssetOptions, ProgressCallback, RequestType } from './shared'; import { parseLoadResArgs, parseParameters } from './utilities'; /** * @en * A bundle contains an amount of assets(includes scene), you can load, preload, release asset which is in this bundle * * @zh * 一个包含一定数量资源(包括场景)的包,你可以加载,预加载,释放此包内的资源 * */ export default class Bundle { private _config: Config = new Config(); /** * for internal use * @private */ public get config (): Config { return this._config; } /** * @en * The name of this bundle * * @zh * 此 bundle 的名称 * */ public get name (): string { return this._config.name; } /** * @en * The dependency of this bundle * * @zh * 此 bundle 的依赖 * */ public get deps (): string[] { return this._config.deps!; } /** * @en * The root path of this bundle, such like 'http://example.com/bundle1' * * @zh * 此 bundle 的根路径, 例如 'http://example.com/bundle1' * */ public get base (): string { return this._config.base; } /** * @en * Get asset's info using path, only valid when asset is in bundle folder. * * @zh * 使用 path 获取资源的配置信息 * * @param path - The relative path of asset, such as 'images/a' * @param type - The constructor of asset, such as `cc.Texture2D` * @returns The asset info * * @example * var info = bundle.getInfoWithPath('image/a', cc.Texture2D); * */ public getInfoWithPath (path: string, type?: AssetType | null): IAddressableInfo | null { return this._config.getInfoWithPath(path, type); } /** * @en * Get all asset's info within specific folder * * @zh * 获取在某个指定文件夹下的所有资源信息 * * @param path - The relative path of folder, such as 'images' * @param type - The constructor should be used to filter paths * @param out - The output array * @returns Infos * * @example * var infos = []; * bundle.getDirWithPath('images', cc.Texture2D, infos); */ public getDirWithPath (path: string, type?: AssetType | null, out?: IAddressableInfo[]): IAddressableInfo[] { return this._config.getDirWithPath(path, type, out); } /** * @en * Get asset's info with uuid * * @zh * 通过 uuid 获取资源信息 * * @method getAssetInfo * @param uuid - The asset's uuid * @returns info * * @example * var info = bundle.getAssetInfo('fcmR3XADNLgJ1ByKhqcC5Z'); * */ public getAssetInfo (uuid: string): IAssetInfo | null { return this._config.getAssetInfo(uuid); } /** * @en * Get scene'info with name * * @zh * 通过场景名获取场景信息 * * @method getSceneInfo * @param name - The name of scene * @return info * * @example * var info = bundle.getSceneInfo('first.fire'); * */ public getSceneInfo (name: string): ISceneInfo | null { return this._config.getSceneInfo(name); } /** * @en * Initialize this bundle with options * * @zh * 初始化此 bundle * * @param options * */ public init (options: IConfigOption) { this._config.init(options); bundles.add(options.name, this); } /** * @en * Load the asset within this bundle by the path which is relative to bundle's path * * @zh * 通过相对路径加载分包中的资源。路径是相对分包文件夹路径的相对路径 * * @param paths - Paths of the target assets.The path is relative to the bundle's folder, extensions must be omitted. * @param type - Only asset of type will be loaded if this argument is supplied. * @param onProgress - Callback invoked when progression change. * @param onProgress.finish - The number of the items that are already completed. * @param onProgress.total - The total number of the items. * @param onProgress.item - The finished request item. * @param onComplete - Callback invoked when all assets loaded. * @param onComplete.error - The error info or null if loaded successfully. * @param onComplete.assets - The loaded assets. * * @example * // load the texture (${project}/assets/resources/textures/background.jpg) from resources * cc.resources.load('textures/background', cc.Texture2D, (err, texture) => console.log(err)); * * // load the audio (${project}/assets/resources/music/hit.mp3) from resources * cc.resources.load('music/hit', cc.AudioClip, (err, audio) => console.log(err)); * * // load the prefab (${project}/assets/bundle1/misc/character/cocos) from bundle1 folder * bundle1.load('misc/character/cocos', cc.Prefab, (err, prefab) => console.log(err)); * * // load the sprite frame (${project}/assets/some/xxx/bundle2/imgs/cocos.png) from bundle2 folder * bundle2.load('imgs/cocos', cc.SpriteFrame, null, (err, spriteFrame) => console.log(err)); * */ public load<T extends Asset> ( paths: string, type: AssetType<T> | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<T> | null): void; public load<T extends Asset> ( paths: string[], type: AssetType<T> | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<T[]> | null): void; public load<T extends Asset> (paths: string, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<T> | null): void; public load<T extends Asset> (paths: string[], onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<T[]> | null): void; public load<T extends Asset> (paths: string, onComplete?: CompleteCallbackWithData<T> | null): void; public load<T extends Asset> (paths: string[], onComplete?: CompleteCallbackWithData<T[]> | null): void; public load<T extends Asset> (paths: string, type: AssetType<T> | null, onComplete?: CompleteCallbackWithData<T> | null): void; public load<T extends Asset> (paths: string[], type: AssetType<T> | null, onComplete?: CompleteCallbackWithData<T[]> | null): void; public load<T extends Asset> ( paths: string|string[], type?: AssetType<T> | ProgressCallback | CompleteCallbackWithData<T|T[]> | null, onProgress?: ProgressCallback | CompleteCallbackWithData<T|T[]> | null, onComplete?: CompleteCallbackWithData<T|T[]> | null, ) { const { type: _type, onProgress: onProg, onComplete: onComp } = parseLoadResArgs(type, onProgress, onComplete); const options = { __requestType__: RequestType.PATH, type: _type, bundle: this.name, __outputAsArray__: Array.isArray(paths) }; legacyCC.assetManager.loadAny(paths, options, onProg, onComp); } /** * @en * Preload the asset within this bundle by the path which is relative to bundle's path. * After calling this method, you still need to finish loading by calling `Bundle.load`. * It will be totally fine to call `Bundle.load` at any time even if the preloading is not * yet finished * * @zh * 通过相对路径预加载分包中的资源。路径是相对分包文件夹路径的相对路径。调用完后,你仍然需要通过 `Bundle.load` 来完成加载。 * 就算预加载还没完成,你也可以直接调用 `Bundle.load`。 * * @param paths - Paths of the target asset.The path is relative to bundle folder, extensions must be omitted. * @param type - Only asset of type will be loaded if this argument is supplied. * @param onProgress - Callback invoked when progression change. * @param onProgress.finish - The number of the items that are already completed. * @param onProgress.total - The total number of the items. * @param onProgress.item - The finished request item. * @param onComplete - Callback invoked when the resource loaded. * @param onComplete.error - The error info or null if loaded successfully. * @param onComplete.items - The preloaded items. * * @example * // preload the texture (${project}/assets/resources/textures/background.jpg) from resources * cc.resources.preload('textures/background', cc.Texture2D); * * // preload the audio (${project}/assets/resources/music/hit.mp3) from resources * cc.resources.preload('music/hit', cc.AudioClip); * // wait for while * cc.resources.load('music/hit', cc.AudioClip, (err, audioClip) => {}); * * * // preload the prefab (${project}/assets/bundle1/misc/character/cocos) from bundle1 folder * bundle1.preload('misc/character/cocos', cc.Prefab); * * // load the sprite frame of (${project}/assets/bundle2/imgs/cocos.png) from bundle2 folder * bundle2.preload('imgs/cocos', cc.SpriteFrame); * // wait for while * bundle2.load('imgs/cocos', cc.SpriteFrame, (err, spriteFrame) => {}); * */ public preload (paths: string|string[], type: AssetType|null, onProgress: ProgressCallback|null, onComplete: CompleteCallbackWithData<RequestItem[]>|null): void; public preload (paths: string|string[], onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<RequestItem[]> | null): void; public preload (paths: string|string[], onComplete?: CompleteCallbackWithData<RequestItem[]> | null): void; public preload (paths: string|string[], type: AssetType | null, onComplete?: CompleteCallbackWithData<RequestItem[]> | null): void; public preload ( paths: string|string[], type?: AssetType | ProgressCallback | CompleteCallbackWithData<RequestItem[]> | null, onProgress?: ProgressCallback | CompleteCallbackWithData<RequestItem[]> | null, onComplete?: CompleteCallbackWithData<RequestItem[]> | null, ) { const { type: _type, onProgress: onProg, onComplete: onComp } = parseLoadResArgs(type, onProgress, onComplete); legacyCC.assetManager.preloadAny(paths, { __requestType__: RequestType.PATH, type: _type, bundle: this.name }, onProg, onComp); } /** * @en * Load all assets under a folder inside the bundle folder.<br> * <br> * Note: All asset paths in Creator use forward slashes, paths using backslashes will not work. * * @zh * 加载目标文件夹中的所有资源, 注意:路径中只能使用斜杠,反斜杠将停止工作 * * @param dir - path of the target folder.The path is relative to the bundle folder, extensions must be omitted. * @param type - Only asset of type will be loaded if this argument is supplied. * @param onProgress - Callback invoked when progression change. * @param onProgress.finish - The number of the items that are already completed. * @param onProgress.total - The total number of the items. * @param onProgress.item - The latest request item * @param onComplete - A callback which is called when all assets have been loaded, or an error occurs. * @param onComplete.error - If one of the asset failed, the complete callback is immediately called with the error. * If all assets are loaded successfully, error will be null. * @param onComplete.assets - An array of all loaded assets. * * @example * // load all audios (resources/audios/) * cc.resources.loadDir('audios', cc.AudioClip, (err, audios) => {}); * * // load all textures in "resources/imgs/" * cc.resources.loadDir('imgs', cc.Texture2D, null, function (err, textures) { * var texture1 = textures[0]; * var texture2 = textures[1]; * }); * * // load all prefabs (${project}/assets/bundle1/misc/characters/) from bundle1 folder * bundle1.loadDir('misc/characters', cc.Prefab, (err, prefabs) => console.log(err)); * * // load all sprite frame (${project}/assets/some/xxx/bundle2/skills/) from bundle2 folder * bundle2.loadDir('skills', cc.SpriteFrame, null, (err, spriteFrames) => console.log(err)); * */ public loadDir<T extends Asset> (dir: string, type: AssetType<T> | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<T[]> | null): void; public loadDir<T extends Asset> (dir: string, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<T[]> | null): void; public loadDir<T extends Asset> (dir: string, onComplete?: CompleteCallbackWithData<T[]> | null): void; public loadDir<T extends Asset> (dir: string, type: AssetType<T> | null, onComplete?: CompleteCallbackWithData<T[]> | null): void; public loadDir<T extends Asset> ( dir: string, type?: AssetType<T> | ProgressCallback | CompleteCallbackWithData<T[]> | null, onProgress?: ProgressCallback | CompleteCallbackWithData<T[]> | null, onComplete?: CompleteCallbackWithData<T[]> | null, ) { const { type: _type, onProgress: onProg, onComplete: onComp } = parseLoadResArgs(type, onProgress, onComplete); legacyCC.assetManager.loadAny(dir, { __requestType__: RequestType.DIR, type: _type, bundle: this.name, __outputAsArray__: true }, onProg, onComp); } /** * @en * Preload all assets under a folder inside the bundle folder.<br> After calling this method, you still need to * finish loading by calling `Bundle.loadDir`. * It will be totally fine to call `Bundle.loadDir` at any time even if the preloading is not yet finished * * @zh * 预加载目标文件夹中的所有资源。调用完后,你仍然需要通过 `Bundle.loadDir` 来完成加载。 * 就算预加载还没完成,你也可以直接调用 `Bundle.loadDir`。 * * @param dir - path of the target folder.The path is relative to the bundle folder, extensions must be omitted. * @param type - Only asset of type will be preloaded if this argument is supplied. * @param onProgress - Callback invoked when progression change. * @param onProgress.finish - The number of the items that are already completed. * @param onProgress.total - The total number of the items. * @param onProgress.item - The latest request item * @param onComplete - A callback which is called when all assets have been loaded, or an error occurs. * @param onComplete.error - If one of the asset failed, the complete callback is immediately called with the error. * If all assets are preloaded successfully, error will be null. * @param onComplete.items - An array of all preloaded items. * * @example * // preload all audios (resources/audios/) * cc.resources.preloadDir('audios', cc.AudioClip); * * // preload all textures in "resources/imgs/" * cc.resources.preloadDir('imgs', cc.Texture2D); * // wait for while * cc.resources.loadDir('imgs', cc.Texture2D, (err, textures) => {}); * * // preload all prefabs (${project}/assets/bundle1/misc/characters/) from bundle1 folder * bundle1.preloadDir('misc/characters', cc.Prefab); * * // preload all sprite frame (${project}/assets/some/xxx/bundle2/skills/) from bundle2 folder * bundle2.preloadDir('skills', cc.SpriteFrame); * // wait for while * bundle2.loadDir('skills', cc.SpriteFrame, (err, spriteFrames) => {}); */ public preloadDir (dir: string, type: AssetType | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<RequestItem[]> | null): void; public preloadDir (dir: string, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<RequestItem[]> | null): void; public preloadDir (dir: string, onComplete?: CompleteCallbackWithData<RequestItem[]> | null): void; public preloadDir (dir: string, type: AssetType | null, onComplete?: CompleteCallbackWithData<RequestItem[]> | null): void; public preloadDir ( dir: string, type?: AssetType | ProgressCallback | CompleteCallbackWithData<RequestItem[]>| null, onProgress?: ProgressCallback | CompleteCallbackWithData<RequestItem[]>| null, onComplete?: CompleteCallbackWithData<RequestItem[]>| null, ) { const { type: _type, onProgress: onProg, onComplete: onComp } = parseLoadResArgs(type, onProgress, onComplete); legacyCC.assetManager.preloadAny(dir, { __requestType__: RequestType.DIR, type: _type, bundle: this.name }, onProg, onComp); } /** * @en * Loads the scene within this bundle by its name. * * @zh * 通过场景名称加载分包中的场景。 * * @param sceneName - The name of the scene to load. * @param options - Some optional parameters * @param onProgress - Callback invoked when progression change. * @param onProgress.finish - The number of the items that are already completed. * @param onProgress.total - The total number of the items. * @param onProgress.item - The latest request item * @param onComplete - callback, will be called after scene launched. * @param onComplete.err - The occurred error, null indicetes success * @param onComplete.sceneAsset - The scene asset * * @example * bundle1.loadScene('first', (err, sceneAsset) => cc.director.runScene(sceneAsset)); * */ public loadScene (sceneName: string, options: IAssetOptions | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<SceneAsset> | null): void; public loadScene (sceneName: string, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData<SceneAsset> | null): void; public loadScene (sceneName: string, options: IAssetOptions | null, onComplete?: CompleteCallbackWithData<SceneAsset> | null): void; public loadScene (sceneName: string, onComplete?: CompleteCallbackWithData<SceneAsset> | null): void; public loadScene ( sceneName: string, options?: IAssetOptions | ProgressCallback | CompleteCallbackWithData<SceneAsset> | null, onProgress?: ProgressCallback | CompleteCallbackWithData<SceneAsset> | null, onComplete?: CompleteCallbackWithData<SceneAsset> | null, ) { const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters<CompleteCallbackWithData<SceneAsset>>(options, onProgress, onComplete); opts.preset = opts.preset || 'scene'; opts.bundle = this.name; legacyCC.assetManager.loadAny({ scene: sceneName }, opts, onProg, (err, sceneAsset) => { if (err) { error(err.message, err.stack); } else if (sceneAsset instanceof SceneAsset && sceneAsset.scene) { const scene = sceneAsset.scene; // @ts-expect-error set private property scene._id = sceneAsset._uuid; scene.name = sceneAsset.name; } else { err = new Error(`The asset ${sceneAsset._uuid} is not a scene`); } if (onComp) { onComp(err, sceneAsset); } }); } /** * @en * Preloads the scene within this bundle by its name. After calling this method, you still need to finish loading * by calling `Bundle.loadScene` or `cc.director.loadScene`.It will be totally fine to call `Bundle.loadDir` at any * time even if the preloading is not yet finished * * @zh * 通过场景名称预加载分包中的场景.调用完后,你仍然需要通过 `Bundle.loadScene` 或 `cc.director.loadScene` 来完成加载。 * 就算预加载还没完成,你也可以直接调用 `Bundle.loadScene` 或 `cc.director.loadScene`。 * * @param sceneName - The name of the scene to preload. * @param options - Some optional parameters * @param onProgress - callback, will be called when the load progression change. * @param onProgress.finish - The number of the items that are already completed * @param onProgress.total - The total number of the items * @param onProgress.item The latest request item * @param onComplete - callback, will be called after scene loaded. * @param onComplete.error - null or the error object. * * @example * bundle1.preloadScene('first'); * // wait for a while * bundle1.loadScene('first', (err, scene) => cc.director.runScene(scene)); * */ public preloadScene (sceneName: string, options: IAssetOptions | null, onProgress: ProgressCallback, onComplete: CompleteCallbackNoData | null): void; public preloadScene (sceneName: string, onProgress: ProgressCallback | null, onComplete: CompleteCallbackNoData | null): void; public preloadScene (sceneName: string, options: IAssetOptions | null, onComplete?: CompleteCallbackNoData | null): void; public preloadScene (sceneName: string, onComplete?: CompleteCallbackNoData | null): void; public preloadScene ( sceneName: string, options?: IAssetOptions | ProgressCallback | CompleteCallbackNoData | null, onProgress?: ProgressCallback | CompleteCallbackNoData | null, onComplete?: CompleteCallbackNoData | null, ) { const { options: opts, onProgress: onProg, onComplete: onComp } = parseParameters<CompleteCallbackNoData>(options, onProgress, onComplete); opts.bundle = this.name; legacyCC.assetManager.preloadAny({ scene: sceneName }, opts, onProg, (err) => { if (err) { errorID(1210, sceneName, err.message); } if (onComp) { onComp(err); } }); } /** * @en * Get cached asset within this bundle by path and type. <br> * After you load asset with {{#crossLink "Bundle/load:method"}}{{/crossLink}} or {{#crossLink "Bundle/loadDir:method"}}{{/crossLink}}, * you can acquire them by passing the path to this API. * * NOTE:The `path` and `type` parameters passed need to be the same as those passed to `Bundle.load`, * otherwise it may return some other resources with the same name! * * @zh * 通过路径与类型获取已缓存资源。在你使用 {{#crossLink "Bundle/load:method"}}{{/crossLink}} 或者 {{#crossLink "Bundle/loadDir:method"}}{{/crossLink}} 之后, * 你能通过传路径通过这个 API 获取到这些资源。 * * 注意:传入的 path 与 type 参数需要与 `Bundle.load` 加载资源时传入的参数一致,否则可能会获取到其他同名资源 * * @param path - The path of asset * @param type - Only asset of type will be returned if this argument is supplied. * @returns - the asset has been cached * * @example * bundle1.get('music/hit', cc.AudioClip); */ public get<T extends Asset> (path: string, type?: AssetType<T> | null): T | null { const info = this.getInfoWithPath(path, type); if (info) { return assets.get(info.uuid) as T || null; } return null; } /** * @en * Release the asset loaded by {{#crossLink "Bundle/load:method"}}{{/crossLink}} or {{#crossLink "Bundle/loadDir:method"}}{{/crossLink}} * and it's dependencies. Refer to {{#crossLink "AssetManager/releaseAsset:method"}}{{/crossLink}} for detailed informations. * * NOTE:The `path` and `type` parameters passed need to be the same as those passed to `Bundle.load`, * otherwise it may release some other resources with the same name! * * @zh * 释放通过 {{#crossLink "Bundle/load:method"}}{{/crossLink}} 或者 {{#crossLink "Bundle/loadDir:method"}}{{/crossLink}} 加载的资源。 * 详细信息请参考 {{#crossLink "AssetManager/releaseAsset:method"}}{{/crossLink}} * * 注意:传入的 path 与 type 参数需要与 `Bundle.load` 加载资源时传入的参数一致,否则可能会释放到其他同名资源 * * @param path - The path of asset * @param type - Only asset of type will be released if this argument is supplied. * * @example * // release a texture which is no longer need * bundle1.release('misc/character/cocos'); * */ public release (path: string, type?: AssetType | null) { const asset = this.get(path, type); if (asset) { releaseManager.tryRelease(asset, true); } } /** * @en * Release all unused assets within this bundle. Refer to {{#crossLink "AssetManager/releaseAll:method"}}{{/crossLink}} for detailed informations. * * @zh * 释放此包中的所有没有用到的资源。详细信息请参考 {{#crossLink "AssetManager/releaseAll:method"}}{{/crossLink}} * * @private * * @example * // release all unused asset within bundle1 * bundle1.releaseUnusedAssets(); * */ public releaseUnusedAssets () { assets.forEach((asset) => { const info = this.getAssetInfo(asset._uuid); if (info && !info.redirect) { releaseManager.tryRelease(asset); } }); } /** * @en * Release all assets within this bundle. Refer to {{#crossLink "AssetManager/releaseAll:method"}}{{/crossLink}} for detailed informations. * * @zh * 释放此包中的所有资源。详细信息请参考 {{#crossLink "AssetManager/releaseAll:method"}}{{/crossLink}} * * @example * // release all asset within bundle1 * bundle1.releaseAll(); */ public releaseAll () { assets.forEach((asset) => { const info = this.getAssetInfo(asset._uuid); if (info && !info.redirect) { releaseManager.tryRelease(asset, true); } }); } public _destroy () { this._config.destroy(); } } /** * @en * resources is a bundle and controls all asset under assets/resources * * @zh * resources 是一个 bundle,用于管理所有在 assets/resources 下的资源 */ export const resources: Bundle = new Bundle(); legacyCC.resources = resources;
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {WaiterConfiguration} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class CloudControl extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: CloudControl.Types.ClientConfiguration) config: Config & CloudControl.Types.ClientConfiguration; /** * Cancels the specified resource operation request. For more information, see Canceling resource operation requests in the Amazon Web Services Cloud Control API User Guide. Only resource operations requests with a status of PENDING or IN_PROGRESS can be cancelled. */ cancelResourceRequest(params: CloudControl.Types.CancelResourceRequestInput, callback?: (err: AWSError, data: CloudControl.Types.CancelResourceRequestOutput) => void): Request<CloudControl.Types.CancelResourceRequestOutput, AWSError>; /** * Cancels the specified resource operation request. For more information, see Canceling resource operation requests in the Amazon Web Services Cloud Control API User Guide. Only resource operations requests with a status of PENDING or IN_PROGRESS can be cancelled. */ cancelResourceRequest(callback?: (err: AWSError, data: CloudControl.Types.CancelResourceRequestOutput) => void): Request<CloudControl.Types.CancelResourceRequestOutput, AWSError>; /** * Creates the specified resource. For more information, see Creating a resource in the Amazon Web Services Cloud Control API User Guide. After you have initiated a resource creation request, you can monitor the progress of your request by calling GetResourceRequestStatus using the RequestToken of the ProgressEvent type returned by CreateResource. */ createResource(params: CloudControl.Types.CreateResourceInput, callback?: (err: AWSError, data: CloudControl.Types.CreateResourceOutput) => void): Request<CloudControl.Types.CreateResourceOutput, AWSError>; /** * Creates the specified resource. For more information, see Creating a resource in the Amazon Web Services Cloud Control API User Guide. After you have initiated a resource creation request, you can monitor the progress of your request by calling GetResourceRequestStatus using the RequestToken of the ProgressEvent type returned by CreateResource. */ createResource(callback?: (err: AWSError, data: CloudControl.Types.CreateResourceOutput) => void): Request<CloudControl.Types.CreateResourceOutput, AWSError>; /** * Deletes the specified resource. For details, see Deleting a resource in the Amazon Web Services Cloud Control API User Guide. After you have initiated a resource deletion request, you can monitor the progress of your request by calling GetResourceRequestStatus using the RequestToken of the ProgressEvent returned by DeleteResource. */ deleteResource(params: CloudControl.Types.DeleteResourceInput, callback?: (err: AWSError, data: CloudControl.Types.DeleteResourceOutput) => void): Request<CloudControl.Types.DeleteResourceOutput, AWSError>; /** * Deletes the specified resource. For details, see Deleting a resource in the Amazon Web Services Cloud Control API User Guide. After you have initiated a resource deletion request, you can monitor the progress of your request by calling GetResourceRequestStatus using the RequestToken of the ProgressEvent returned by DeleteResource. */ deleteResource(callback?: (err: AWSError, data: CloudControl.Types.DeleteResourceOutput) => void): Request<CloudControl.Types.DeleteResourceOutput, AWSError>; /** * Returns information about the current state of the specified resource. For details, see Reading a resource's current state. You can use this action to return information about an existing resource in your account and Amazon Web Services Region, whether or not those resources were provisioned using Cloud Control API. */ getResource(params: CloudControl.Types.GetResourceInput, callback?: (err: AWSError, data: CloudControl.Types.GetResourceOutput) => void): Request<CloudControl.Types.GetResourceOutput, AWSError>; /** * Returns information about the current state of the specified resource. For details, see Reading a resource's current state. You can use this action to return information about an existing resource in your account and Amazon Web Services Region, whether or not those resources were provisioned using Cloud Control API. */ getResource(callback?: (err: AWSError, data: CloudControl.Types.GetResourceOutput) => void): Request<CloudControl.Types.GetResourceOutput, AWSError>; /** * Returns the current status of a resource operation request. For more information, see Tracking the progress of resource operation requests in the Amazon Web Services Cloud Control API User Guide. */ getResourceRequestStatus(params: CloudControl.Types.GetResourceRequestStatusInput, callback?: (err: AWSError, data: CloudControl.Types.GetResourceRequestStatusOutput) => void): Request<CloudControl.Types.GetResourceRequestStatusOutput, AWSError>; /** * Returns the current status of a resource operation request. For more information, see Tracking the progress of resource operation requests in the Amazon Web Services Cloud Control API User Guide. */ getResourceRequestStatus(callback?: (err: AWSError, data: CloudControl.Types.GetResourceRequestStatusOutput) => void): Request<CloudControl.Types.GetResourceRequestStatusOutput, AWSError>; /** * Returns existing resource operation requests. This includes requests of all status types. For more information, see Listing active resource operation requests in the Amazon Web Services Cloud Control API User Guide. Resource operation requests expire after seven days. */ listResourceRequests(params: CloudControl.Types.ListResourceRequestsInput, callback?: (err: AWSError, data: CloudControl.Types.ListResourceRequestsOutput) => void): Request<CloudControl.Types.ListResourceRequestsOutput, AWSError>; /** * Returns existing resource operation requests. This includes requests of all status types. For more information, see Listing active resource operation requests in the Amazon Web Services Cloud Control API User Guide. Resource operation requests expire after seven days. */ listResourceRequests(callback?: (err: AWSError, data: CloudControl.Types.ListResourceRequestsOutput) => void): Request<CloudControl.Types.ListResourceRequestsOutput, AWSError>; /** * Returns information about the specified resources. For more information, see Discovering resources in the Amazon Web Services Cloud Control API User Guide. You can use this action to return information about existing resources in your account and Amazon Web Services Region, whether or not those resources were provisioned using Cloud Control API. */ listResources(params: CloudControl.Types.ListResourcesInput, callback?: (err: AWSError, data: CloudControl.Types.ListResourcesOutput) => void): Request<CloudControl.Types.ListResourcesOutput, AWSError>; /** * Returns information about the specified resources. For more information, see Discovering resources in the Amazon Web Services Cloud Control API User Guide. You can use this action to return information about existing resources in your account and Amazon Web Services Region, whether or not those resources were provisioned using Cloud Control API. */ listResources(callback?: (err: AWSError, data: CloudControl.Types.ListResourcesOutput) => void): Request<CloudControl.Types.ListResourcesOutput, AWSError>; /** * Updates the specified property values in the resource. You specify your resource property updates as a list of patch operations contained in a JSON patch document that adheres to the RFC 6902 - JavaScript Object Notation (JSON) Patch standard. For details on how Cloud Control API performs resource update operations, see Updating a resource in the Amazon Web Services Cloud Control API User Guide. After you have initiated a resource update request, you can monitor the progress of your request by calling GetResourceRequestStatus using the RequestToken of the ProgressEvent returned by UpdateResource. For more information about the properties of a specific resource, refer to the related topic for the resource in the Resource and property types reference in the Amazon Web Services CloudFormation Users Guide. */ updateResource(params: CloudControl.Types.UpdateResourceInput, callback?: (err: AWSError, data: CloudControl.Types.UpdateResourceOutput) => void): Request<CloudControl.Types.UpdateResourceOutput, AWSError>; /** * Updates the specified property values in the resource. You specify your resource property updates as a list of patch operations contained in a JSON patch document that adheres to the RFC 6902 - JavaScript Object Notation (JSON) Patch standard. For details on how Cloud Control API performs resource update operations, see Updating a resource in the Amazon Web Services Cloud Control API User Guide. After you have initiated a resource update request, you can monitor the progress of your request by calling GetResourceRequestStatus using the RequestToken of the ProgressEvent returned by UpdateResource. For more information about the properties of a specific resource, refer to the related topic for the resource in the Resource and property types reference in the Amazon Web Services CloudFormation Users Guide. */ updateResource(callback?: (err: AWSError, data: CloudControl.Types.UpdateResourceOutput) => void): Request<CloudControl.Types.UpdateResourceOutput, AWSError>; /** * Waits for the resourceRequestSuccess state by periodically calling the underlying CloudControl.getResourceRequestStatusoperation every 5 seconds (at most 720 times). Wait until resource operation request is successful */ waitFor(state: "resourceRequestSuccess", params: CloudControl.Types.GetResourceRequestStatusInput & {$waiter?: WaiterConfiguration}, callback?: (err: AWSError, data: CloudControl.Types.GetResourceRequestStatusOutput) => void): Request<CloudControl.Types.GetResourceRequestStatusOutput, AWSError>; /** * Waits for the resourceRequestSuccess state by periodically calling the underlying CloudControl.getResourceRequestStatusoperation every 5 seconds (at most 720 times). Wait until resource operation request is successful */ waitFor(state: "resourceRequestSuccess", callback?: (err: AWSError, data: CloudControl.Types.GetResourceRequestStatusOutput) => void): Request<CloudControl.Types.GetResourceRequestStatusOutput, AWSError>; } declare namespace CloudControl { export interface CancelResourceRequestInput { /** * The RequestToken of the ProgressEvent object returned by the resource operation request. */ RequestToken: RequestToken; } export interface CancelResourceRequestOutput { ProgressEvent?: ProgressEvent; } export type ClientToken = string; export interface CreateResourceInput { /** * The name of the resource type. */ TypeName: TypeName; /** * For private resource types, the type version to use in this resource operation. If you do not specify a resource version, CloudFormation uses the default version. */ TypeVersionId?: TypeVersionId; /** * The Amazon Resource Name (ARN) of the Identity and Access Management (IAM) for Cloud Control API to use when performing this resource operation. The role specified must have the permissions required for this operation. The necessary permissions for each event handler are defined in the handlers section of the resource type definition schema. If you do not specify a role, Cloud Control API uses a temporary session created using your Amazon Web Services user credentials. For more information, see Specifying credentials in the Amazon Web Services Cloud Control API User Guide. */ RoleArn?: RoleArn; /** * A unique identifier to ensure the idempotency of the resource request. As a best practice, specify this token to ensure idempotency, so that Amazon Web Services Cloud Control API can accurately distinguish between request retries and new resource requests. You might retry a resource request to ensure that it was successfully received. A client token is valid for 36 hours once used. After that, a resource request with the same client token is treated as a new request. If you do not specify a client token, one is generated for inclusion in the request. For more information, see Ensuring resource operation requests are unique in the Amazon Web Services Cloud Control API User Guide. */ ClientToken?: ClientToken; /** * Structured data format representing the desired state of the resource, consisting of that resource's properties and their desired values. Cloud Control API currently supports JSON as a structured data format. Specify the desired state as one of the following: A JSON blob A local path containing the desired state in JSON data format For more information, see Composing the desired state of the resource in the Amazon Web Services Cloud Control API User Guide. For more information about the properties of a specific resource, refer to the related topic for the resource in the Resource and property types reference in the Amazon Web Services CloudFormation Users Guide. */ DesiredState: Properties; } export interface CreateResourceOutput { /** * Represents the current status of the resource creation request. After you have initiated a resource creation request, you can monitor the progress of your request by calling GetResourceRequestStatus using the RequestToken of the ProgressEvent returned by CreateResource. */ ProgressEvent?: ProgressEvent; } export interface DeleteResourceInput { /** * The name of the resource type. */ TypeName: TypeName; /** * For private resource types, the type version to use in this resource operation. If you do not specify a resource version, CloudFormation uses the default version. */ TypeVersionId?: TypeVersionId; /** * The Amazon Resource Name (ARN) of the Identity and Access Management (IAM) for Cloud Control API to use when performing this resource operation. The role specified must have the permissions required for this operation. The necessary permissions for each event handler are defined in the handlers section of the resource type definition schema. If you do not specify a role, Cloud Control API uses a temporary session created using your Amazon Web Services user credentials. For more information, see Specifying credentials in the Amazon Web Services Cloud Control API User Guide. */ RoleArn?: RoleArn; /** * A unique identifier to ensure the idempotency of the resource request. As a best practice, specify this token to ensure idempotency, so that Amazon Web Services Cloud Control API can accurately distinguish between request retries and new resource requests. You might retry a resource request to ensure that it was successfully received. A client token is valid for 36 hours once used. After that, a resource request with the same client token is treated as a new request. If you do not specify a client token, one is generated for inclusion in the request. For more information, see Ensuring resource operation requests are unique in the Amazon Web Services Cloud Control API User Guide. */ ClientToken?: ClientToken; /** * The identifier for the resource. You can specify the primary identifier, or any secondary identifier defined for the resource type in its resource schema. You can only specify one identifier. Primary identifiers can be specified as a string or JSON; secondary identifiers must be specified as JSON. For compound primary identifiers (that is, one that consists of multiple resource properties strung together), to specify the primary identifier as a string, list the property values in the order they are specified in the primary identifier definition, separated by |. For more information, see Identifying resources in the Amazon Web Services Cloud Control API User Guide. */ Identifier: Identifier; } export interface DeleteResourceOutput { /** * Represents the current status of the resource deletion request. After you have initiated a resource deletion request, you can monitor the progress of your request by calling GetResourceRequestStatus using the RequestToken of the ProgressEvent returned by DeleteResource. */ ProgressEvent?: ProgressEvent; } export interface GetResourceInput { /** * The name of the resource type. */ TypeName: TypeName; /** * For private resource types, the type version to use in this resource operation. If you do not specify a resource version, CloudFormation uses the default version. */ TypeVersionId?: TypeVersionId; /** * The Amazon Resource Name (ARN) of the Identity and Access Management (IAM) for Cloud Control API to use when performing this resource operation. The role specified must have the permissions required for this operation. The necessary permissions for each event handler are defined in the handlers section of the resource type definition schema. If you do not specify a role, Cloud Control API uses a temporary session created using your Amazon Web Services user credentials. For more information, see Specifying credentials in the Amazon Web Services Cloud Control API User Guide. */ RoleArn?: RoleArn; /** * The identifier for the resource. You can specify the primary identifier, or any secondary identifier defined for the resource type in its resource schema. You can only specify one identifier. Primary identifiers can be specified as a string or JSON; secondary identifiers must be specified as JSON. For compound primary identifiers (that is, one that consists of multiple resource properties strung together), to specify the primary identifier as a string, list the property values in the order they are specified in the primary identifier definition, separated by |. For more information, see Identifying resources in the Amazon Web Services Cloud Control API User Guide. */ Identifier: Identifier; } export interface GetResourceOutput { /** * The name of the resource type. */ TypeName?: TypeName; ResourceDescription?: ResourceDescription; } export interface GetResourceRequestStatusInput { /** * A unique token used to track the progress of the resource operation request. Request tokens are included in the ProgressEvent type returned by a resource operation request. */ RequestToken: RequestToken; } export interface GetResourceRequestStatusOutput { /** * Represents the current status of the resource operation request. */ ProgressEvent?: ProgressEvent; } export type HandlerErrorCode = "NotUpdatable"|"InvalidRequest"|"AccessDenied"|"InvalidCredentials"|"AlreadyExists"|"NotFound"|"ResourceConflict"|"Throttling"|"ServiceLimitExceeded"|"NotStabilized"|"GeneralServiceException"|"ServiceInternalError"|"ServiceTimeout"|"NetworkFailure"|"InternalFailure"|string; export type HandlerNextToken = string; export type Identifier = string; export interface ListResourceRequestsInput { /** * The maximum number of results to be returned with a single call. If the number of available results exceeds this maximum, the response includes a NextToken value that you can assign to the NextToken request parameter to get the next set of results. The default is 20. */ MaxResults?: MaxResults; /** * If the previous paginated request didn't return all of the remaining results, the response object's NextToken parameter value is set to a token. To retrieve the next set of results, call this action again and assign that token to the request object's NextToken parameter. If there are no remaining results, the previous response object's NextToken parameter is set to null. */ NextToken?: NextToken; /** * The filter criteria to apply to the requests returned. */ ResourceRequestStatusFilter?: ResourceRequestStatusFilter; } export interface ListResourceRequestsOutput { /** * The requests that match the specified filter criteria. */ ResourceRequestStatusSummaries?: ResourceRequestStatusSummaries; /** * If the request doesn't return all of the remaining results, NextToken is set to a token. To retrieve the next set of results, call ListResources again and assign that token to the request object's NextToken parameter. If the request returns all results, NextToken is set to null. */ NextToken?: NextToken; } export interface ListResourcesInput { /** * The name of the resource type. */ TypeName: TypeName; /** * For private resource types, the type version to use in this resource operation. If you do not specify a resource version, CloudFormation uses the default version. */ TypeVersionId?: TypeVersionId; /** * The Amazon Resource Name (ARN) of the Identity and Access Management (IAM) for Cloud Control API to use when performing this resource operation. The role specified must have the permissions required for this operation. The necessary permissions for each event handler are defined in the handlers section of the resource type definition schema. If you do not specify a role, Cloud Control API uses a temporary session created using your Amazon Web Services user credentials. For more information, see Specifying credentials in the Amazon Web Services Cloud Control API User Guide. */ RoleArn?: RoleArn; /** * If the previous paginated request didn't return all of the remaining results, the response object's NextToken parameter value is set to a token. To retrieve the next set of results, call this action again and assign that token to the request object's NextToken parameter. If there are no remaining results, the previous response object's NextToken parameter is set to null. */ NextToken?: HandlerNextToken; /** * The maximum number of results to be returned with a single call. If the number of available results exceeds this maximum, the response includes a NextToken value that you can assign to the NextToken request parameter to get the next set of results. The default is 20. */ MaxResults?: MaxResults; /** * The resource model to use to select the resources to return. */ ResourceModel?: Properties; } export interface ListResourcesOutput { /** * The name of the resource type. */ TypeName?: TypeName; /** * Information about the specified resources, including primary identifier and resource model. */ ResourceDescriptions?: ResourceDescriptions; /** * If the request doesn't return all of the remaining results, NextToken is set to a token. To retrieve the next set of results, call ListResources again and assign that token to the request object's NextToken parameter. If the request returns all results, NextToken is set to null. */ NextToken?: HandlerNextToken; } export type MaxResults = number; export type NextToken = string; export type Operation = "CREATE"|"DELETE"|"UPDATE"|string; export type OperationStatus = "PENDING"|"IN_PROGRESS"|"SUCCESS"|"FAILED"|"CANCEL_IN_PROGRESS"|"CANCEL_COMPLETE"|string; export type OperationStatuses = OperationStatus[]; export type Operations = Operation[]; export type PatchDocument = string; export interface ProgressEvent { /** * The name of the resource type used in the operation. */ TypeName?: TypeName; /** * The primary identifier for the resource. In some cases, the resource identifier may be available before the resource operation has reached a status of SUCCESS. */ Identifier?: Identifier; /** * The unique token representing this resource operation request. Use the RequestToken with GetResourceRequestStatus to return the current status of a resource operation request. */ RequestToken?: RequestToken; /** * The resource operation type. */ Operation?: Operation; /** * The current status of the resource operation request. PENDING: The resource operation has not yet started. IN_PROGRESS: The resource operation is currently in progress. SUCCESS: The resource operation has successfully completed. FAILED: The resource operation has failed. Refer to the error code and status message for more information. CANCEL_IN_PROGRESS: The resource operation is in the process of being canceled. CANCEL_COMPLETE: The resource operation has been canceled. */ OperationStatus?: OperationStatus; /** * When the resource operation request was initiated. */ EventTime?: Timestamp; /** * A JSON string containing the resource model, consisting of each resource property and its current value. */ ResourceModel?: Properties; /** * Any message explaining the current status. */ StatusMessage?: StatusMessage; /** * For requests with a status of FAILED, the associated error code. For error code definitions, see Handler error codes in the CloudFormation Command Line Interface User Guide for Extension Development. */ ErrorCode?: HandlerErrorCode; /** * When to next request the status of this resource operation request. */ RetryAfter?: Timestamp; } export type Properties = string; export type RequestToken = string; export interface ResourceDescription { /** * The primary identifier for the resource. For more information, see Identifying resources in the Amazon Web Services Cloud Control API User Guide. */ Identifier?: Identifier; /** * A list of the resource properties and their current values. */ Properties?: Properties; } export type ResourceDescriptions = ResourceDescription[]; export interface ResourceRequestStatusFilter { /** * The operation types to include in the filter. */ Operations?: Operations; /** * The operation statuses to include in the filter. PENDING: The operation has been requested, but not yet initiated. IN_PROGRESS: The operation is currently in progress. SUCCESS: The operation has successfully completed. FAILED: The operation has failed. CANCEL_IN_PROGRESS: The operation is currently in the process of being canceled. CANCEL_COMPLETE: The operation has been canceled. */ OperationStatuses?: OperationStatuses; } export type ResourceRequestStatusSummaries = ProgressEvent[]; export type RoleArn = string; export type StatusMessage = string; export type Timestamp = Date; export type TypeName = string; export type TypeVersionId = string; export interface UpdateResourceInput { /** * The name of the resource type. */ TypeName: TypeName; /** * For private resource types, the type version to use in this resource operation. If you do not specify a resource version, CloudFormation uses the default version. */ TypeVersionId?: TypeVersionId; /** * The Amazon Resource Name (ARN) of the Identity and Access Management (IAM) for Cloud Control API to use when performing this resource operation. The role specified must have the permissions required for this operation. The necessary permissions for each event handler are defined in the handlers section of the resource type definition schema. If you do not specify a role, Cloud Control API uses a temporary session created using your Amazon Web Services user credentials. For more information, see Specifying credentials in the Amazon Web Services Cloud Control API User Guide. */ RoleArn?: RoleArn; /** * A unique identifier to ensure the idempotency of the resource request. As a best practice, specify this token to ensure idempotency, so that Amazon Web Services Cloud Control API can accurately distinguish between request retries and new resource requests. You might retry a resource request to ensure that it was successfully received. A client token is valid for 36 hours once used. After that, a resource request with the same client token is treated as a new request. If you do not specify a client token, one is generated for inclusion in the request. For more information, see Ensuring resource operation requests are unique in the Amazon Web Services Cloud Control API User Guide. */ ClientToken?: ClientToken; /** * The identifier for the resource. You can specify the primary identifier, or any secondary identifier defined for the resource type in its resource schema. You can only specify one identifier. Primary identifiers can be specified as a string or JSON; secondary identifiers must be specified as JSON. For compound primary identifiers (that is, one that consists of multiple resource properties strung together), to specify the primary identifier as a string, list the property values in the order they are specified in the primary identifier definition, separated by |. For more information, see Identifying resources in the Amazon Web Services Cloud Control API User Guide. */ Identifier: Identifier; /** * A JavaScript Object Notation (JSON) document listing the patch operations that represent the updates to apply to the current resource properties. For details, see Composing the patch document in the Amazon Web Services Cloud Control API User Guide. */ PatchDocument: PatchDocument; } export interface UpdateResourceOutput { /** * Represents the current status of the resource update request. Use the RequestToken of the ProgressEvent with GetResourceRequestStatus to return the current status of a resource operation request. */ ProgressEvent?: ProgressEvent; } /** * 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 = "2021-09-30"|"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 CloudControl client. */ export import Types = CloudControl; } export = CloudControl;
the_stack
import React, { Dispatch, useEffect, useMemo, useRef } from 'react' import { useDispatch, useSelector } from 'react-redux' import type { UniswapInterfaceMulticall } from './abi/types' import { CHUNK_GAS_LIMIT, DEFAULT_CALL_GAS_REQUIRED } from './constants' import type { MulticallContext } from './context' import type { MulticallActions } from './slice' import type { Call, MulticallState, WithMulticallState } from './types' import { parseCallKey, toCallKey } from './utils/callKeys' import chunkCalls from './utils/chunkCalls' import { retry, RetryableError } from './utils/retry' import useDebounce from './utils/useDebounce' const FETCH_RETRY_CONFIG = { n: Infinity, minWait: 1000, maxWait: 2500, } /** * Fetches a chunk of calls, enforcing a minimum block number constraint * @param multicall multicall contract to fetch against * @param chunk chunk of calls to make * @param blockNumber block number passed as the block tag in the eth_call */ async function fetchChunk( multicall: UniswapInterfaceMulticall, chunk: Call[], blockNumber: number, isDebug?: boolean ): Promise<{ success: boolean; returnData: string }[]> { console.debug('Fetching chunk', chunk, blockNumber) try { const { returnData } = await multicall.callStatic.multicall( chunk.map((obj) => ({ target: obj.address, callData: obj.callData, gasLimit: obj.gasRequired ?? DEFAULT_CALL_GAS_REQUIRED, })), // we aren't passing through the block gas limit we used to create the chunk, because it causes a problem with the integ tests { blockTag: blockNumber } ) if (isDebug) { returnData.forEach(({ gasUsed, returnData, success }, i) => { if ( !success && returnData.length === 2 && gasUsed.gte(Math.floor((chunk[i].gasRequired ?? DEFAULT_CALL_GAS_REQUIRED) * 0.95)) ) { console.warn( `A call failed due to requiring ${gasUsed.toString()} vs. allowed ${ chunk[i].gasRequired ?? DEFAULT_CALL_GAS_REQUIRED }`, chunk[i] ) } }) } return returnData } catch (e) { const error = e as any if (error.code === -32000 || error.message?.indexOf('header not found') !== -1) { throw new RetryableError(`header not found for block number ${blockNumber}`) } else if (error.code === -32603 || error.message?.indexOf('execution ran out of gas') !== -1) { if (chunk.length > 1) { if (process.env.NODE_ENV === 'development') { console.debug('Splitting a chunk in 2', chunk) } const half = Math.floor(chunk.length / 2) const [c0, c1] = await Promise.all([ fetchChunk(multicall, chunk.slice(0, half), blockNumber), fetchChunk(multicall, chunk.slice(half, chunk.length), blockNumber), ]) return c0.concat(c1) } } console.error('Failed to fetch chunk', error) throw error } } /** * From the current all listeners state, return each call key mapped to the * minimum number of blocks per fetch. This is how often each key must be fetched. * @param allListeners the all listeners state * @param chainId the current chain id */ export function activeListeningKeys( allListeners: MulticallState['callListeners'], chainId?: number ): { [callKey: string]: number } { if (!allListeners || !chainId) return {} const listeners = allListeners[chainId] if (!listeners) return {} return Object.keys(listeners).reduce<{ [callKey: string]: number }>((memo, callKey) => { const keyListeners = listeners[callKey] memo[callKey] = Object.keys(keyListeners) .filter((key) => { const blocksPerFetch = parseInt(key) if (blocksPerFetch <= 0) return false return keyListeners[blocksPerFetch] > 0 }) .reduce((previousMin, current) => { return Math.min(previousMin, parseInt(current)) }, Infinity) return memo }, {}) } /** * Return the keys that need to be refetched * @param callResults current call result state * @param listeningKeys each call key mapped to how old the data can be in blocks * @param chainId the current chain id * @param latestBlockNumber the latest block number */ export function outdatedListeningKeys( callResults: MulticallState['callResults'], listeningKeys: { [callKey: string]: number }, chainId: number | undefined, latestBlockNumber: number | undefined ): string[] { if (!chainId || !latestBlockNumber) return [] const results = callResults[chainId] // no results at all, load everything if (!results) return Object.keys(listeningKeys) return Object.keys(listeningKeys).filter((callKey) => { const blocksPerFetch = listeningKeys[callKey] const data = callResults[chainId][callKey] // no data, must fetch if (!data) return true const minDataBlockNumber = latestBlockNumber - (blocksPerFetch - 1) // already fetching it for a recent enough block, don't refetch it if (data.fetchingBlockNumber && data.fetchingBlockNumber >= minDataBlockNumber) return false // if data is older than minDataBlockNumber, fetch it return !data.blockNumber || data.blockNumber < minDataBlockNumber }) } interface FetchChunkContext { actions: MulticallActions dispatch: Dispatch<any> chainId: number latestBlockNumber: number isDebug?: boolean } function onFetchChunkSuccess( context: FetchChunkContext, chunk: Call[], result: Array<{ success: boolean; returnData: string }> ) { const { actions, dispatch, chainId, latestBlockNumber, isDebug } = context // split the returned slice into errors and results const { erroredCalls, results } = chunk.reduce<{ erroredCalls: Call[] results: { [callKey: string]: string | null } }>( (memo, call, i) => { if (result[i].success) { memo.results[toCallKey(call)] = result[i].returnData ?? null } else { memo.erroredCalls.push(call) } return memo }, { erroredCalls: [], results: {} } ) // dispatch any new results if (Object.keys(results).length > 0) dispatch( actions.updateMulticallResults({ chainId, results, blockNumber: latestBlockNumber, }) ) // dispatch any errored calls if (erroredCalls.length > 0) { if (isDebug) { result.forEach((returnData, ix) => { if (!returnData.success) { console.debug('Call failed', chunk[ix], returnData) } }) } else { console.debug('Calls errored in fetch', erroredCalls) } dispatch( actions.errorFetchingMulticallResults({ calls: erroredCalls, chainId, fetchingBlockNumber: latestBlockNumber, }) ) } } function onFetchChunkFailure(context: FetchChunkContext, chunk: Call[], error: any) { const { actions, dispatch, chainId, latestBlockNumber } = context if (error.isCancelledError) { console.debug('Cancelled fetch for blockNumber', latestBlockNumber, chunk, chainId) return } console.error('Failed to fetch multicall chunk', chunk, chainId, error) dispatch( actions.errorFetchingMulticallResults({ calls: chunk, chainId, fetchingBlockNumber: latestBlockNumber, }) ) } export interface UpdaterProps { context: MulticallContext chainId: number | undefined // For now, one updater is required for each chainId to be watched latestBlockNumber: number | undefined contract: UniswapInterfaceMulticall isDebug?: boolean } function Updater(props: UpdaterProps): null { const { context, chainId, latestBlockNumber, contract, isDebug } = props const { actions, reducerPath } = context const dispatch = useDispatch() const state = useSelector((state: WithMulticallState) => state[reducerPath]) // wait for listeners to settle before triggering updates const debouncedListeners = useDebounce(state.callListeners, 100) const cancellations = useRef<{ blockNumber: number; cancellations: (() => void)[] }>() const listeningKeys: { [callKey: string]: number } = useMemo(() => { return activeListeningKeys(debouncedListeners, chainId) }, [debouncedListeners, chainId]) const serializedOutdatedCallKeys = useMemo(() => { const outdatedCallKeys = outdatedListeningKeys(state.callResults, listeningKeys, chainId, latestBlockNumber) return JSON.stringify(outdatedCallKeys.sort()) }, [chainId, state.callResults, listeningKeys, latestBlockNumber]) useEffect(() => { if (!latestBlockNumber || !chainId || !contract) return const outdatedCallKeys: string[] = JSON.parse(serializedOutdatedCallKeys) if (outdatedCallKeys.length === 0) return const calls = outdatedCallKeys.map((key) => parseCallKey(key)) const chunkedCalls = chunkCalls(calls, CHUNK_GAS_LIMIT) if (cancellations.current && cancellations.current.blockNumber !== latestBlockNumber) { cancellations.current.cancellations.forEach((c) => c()) } dispatch( actions.fetchingMulticallResults({ calls, chainId, fetchingBlockNumber: latestBlockNumber, }) ) const fetchChunkContext = { actions, dispatch, chainId, latestBlockNumber, isDebug, } // Execute fetches and gather cancellation callbacks const newCancellations = chunkedCalls.map((chunk) => { const { cancel, promise } = retry( () => fetchChunk(contract, chunk, latestBlockNumber, isDebug), FETCH_RETRY_CONFIG ) promise .then((result) => onFetchChunkSuccess(fetchChunkContext, chunk, result)) .catch((error) => onFetchChunkFailure(fetchChunkContext, chunk, error)) return cancel }) cancellations.current = { blockNumber: latestBlockNumber, cancellations: newCancellations, } }, [actions, chainId, contract, dispatch, serializedOutdatedCallKeys, latestBlockNumber, isDebug]) return null } export function createUpdater(context: MulticallContext) { const UpdaterContextBound = (props: Omit<UpdaterProps, 'context'>) => { return <Updater context={context} {...props} /> } return UpdaterContextBound }
the_stack
import * as d3 from 'd3'; import '@material/mwc-icon-button-toggle'; // tslint:disable:no-new-decorators import {property} from 'lit/decorators'; import {customElement} from 'lit/decorators'; import { html, LitElement} from 'lit'; import {classMap} from 'lit/directives/class-map'; import {styleMap} from 'lit/directives/style-map'; import {computed, observable} from 'mobx'; import {styles} from './data_matrix.css'; import {styles as sharedStyles} from '../lib/shared_styles.css'; import {MAJOR_TONAL_COLORS, ramp} from '../lib/colors'; // Custom color ramp for the Data Matrix const LOW = 0, HIGH = 8; // 0: -50, 1: -100, 2: -200, etc., HIGH gets excluded // Text color flips (black => white) above -600, calc the % where that happens const COLOR_FLIP_PCT = Math.floor((6 - LOW) / (HIGH - 1 - LOW) * 100); const COLOR_RAMP = ramp([...MAJOR_TONAL_COLORS.primary.slice(LOW, HIGH) .map(c => c.color)]); /** * Stores information for each confusion matrix cell. */ export interface MatrixCell { ids: string[]; selected: boolean; } /** * An element that displays a confusion-matrix style vis for datapoints. */ @customElement('data-matrix') export class DataMatrix extends LitElement { static override get styles() { return [sharedStyles, styles]; } @observable verticalColumnLabels = false; @property({type: Boolean}) hideEmptyLabels = false; @property({type: Array}) matrixCells: MatrixCell[][] = []; @property({type: String}) colTitle = ""; @property({type: String}) rowTitle = ""; @property({type: Array}) colLabels: string[] = []; @property({type: Array}) rowLabels: string[] = []; @computed get totalIds(): number { let totalIds = 0; for (let rowIndex = 0; rowIndex < this.matrixCells.length; rowIndex++) { const row = this.matrixCells[rowIndex]; for (let colIndex = 0; colIndex < row.length; colIndex++) { const cell = row[colIndex]; totalIds += cell.ids.length; } } return totalIds; } @computed get colorScale() { // Returns a D3 sequential scale with a domain from 0 (i.e., no selected // datapoints are in this cell) to totalIds (i.e., all selected datapoints // are in this cell). // See https://github.com/d3/d3-scale#sequential-scales return d3.scaleSequential(COLOR_RAMP).domain([0, this.totalIds]); } private updateSelection() { let ids: string[] = []; for (const cellInfo of this.matrixCells.flat()) { if (cellInfo.selected) { ids = ids.concat(cellInfo.ids); } } const event = new CustomEvent('matrix-selection', { detail: { ids, } }); this.dispatchEvent(event); } private renderColHeader(label: string, colIndex: number, colsWithNonZeroCounts: Set<string>) { const onColClick = () => { const cells = this.matrixCells.map((cells) => cells[colIndex]); const allSelected = cells.every((cell) => cell.selected); for (const cell of cells) { cell.selected = !allSelected; } this.updateSelection(); this.requestUpdate(); }; if (this.hideEmptyLabels && !colsWithNonZeroCounts.has(label)) { return null; } const classes = classMap({ 'header-cell': true, 'align-bottom': this.verticalColumnLabels, 'label-vertical': this.verticalColumnLabels }); // clang-format off return html` <th class=${classes} @click=${onColClick}> <div>${label}</div> </th> `; // clang-format on } // Render a clickable confusion matrix cell. private renderCell(rowIndex: number, colIndex: number, colsWithNonZeroCounts: Set<string>) { if (this.matrixCells[rowIndex]?.[colIndex] == null) { return null; } const cellInfo = this.matrixCells[rowIndex][colIndex]; const onCellClick = () => { cellInfo.selected = !cellInfo.selected; this.updateSelection(); this.requestUpdate(); }; if (this.hideEmptyLabels && !colsWithNonZeroCounts.has(this.colLabels[colIndex])) { return null; } const backgroundColor = this.colorScale(cellInfo.ids.length); const percentage = cellInfo.ids.length / this.totalIds * 100; const textColor = percentage > COLOR_FLIP_PCT ? 'white' : 'black'; const border = cellInfo.selected ? '2px solid #12B5CB' : '2px solid transparent'; const cellStyle = styleMap({ background: `${backgroundColor}`, color: `${textColor}`, border }); return html` <td class="cell" style=${cellStyle} @click=${onCellClick}> <div class="cell-container"> <div class="percentage">${percentage.toFixed(1)}%</div> <div class="val">(${cellInfo.ids.length})</div> </div> </td>`; } // Render a row of the confusion matrix, starting with the clickable // row header. private renderRow(rowLabel: string, rowIndex: number, rowsWithNonZeroCounts: Set<string>, colsWithNonZeroCounts: Set<string>) { const onRowClick = () => { const cells = this.matrixCells[rowIndex]; const allSelected = cells.every((cell) => cell.selected); for (const cell of cells) { cell.selected = !allSelected; } this.updateSelection(); this.requestUpdate(); }; if (this.hideEmptyLabels && !rowsWithNonZeroCounts.has(rowLabel)) { return null; } let totalRowIds = 0; for (const cell of this.matrixCells[rowIndex]) { totalRowIds += cell.ids.length; } // clang-format off return html` <tr> <th class="header-cell align-right" @click=${onRowClick}> ${rowLabel} </th> ${this.colLabels.map( (colLabel, colIndex) => this.renderCell( rowIndex, colIndex,colsWithNonZeroCounts))} ${this.renderTotalCell(totalRowIds)} </tr>`; // clang-format on } private renderTotalCell(num: number) { const percentage = (num / this.totalIds * 100).toFixed(1); return html` <td class="total-cell"> <div class="cell-container"> <div class="percentage">${percentage}%</div> <div class="val">(${num})</div> </div> </td>`; } private renderColTotalCell(colIndex: number) { let totalColIds = 0; for (const row of this.matrixCells) { totalColIds += row[colIndex].ids.length; } return this.renderTotalCell(totalColIds); } private renderTotalRow(colsWithNonZeroCounts: Set<string>) { // clang-format off return html` <tr> <th class="total-title-cell align-right">Total</th> ${this.colLabels.map( (colLabel, colIndex) => { if (this.hideEmptyLabels && !colsWithNonZeroCounts.has(this.colLabels[colIndex])) { return null; } return this.renderColTotalCell(colIndex); })} <td class="total-cell"></td> </tr>`; // clang-format on } private renderColumnRotateButton() { const toggleVerticalColumnLabels = () => { this.verticalColumnLabels = !this.verticalColumnLabels; this.requestUpdate(); }; // clang-format off return html` <mwc-icon-button-toggle class="icon-button" title="Rotate column labels" onIcon="text_rotate_up" offIcon="text_rotation_none" ?on="${this.verticalColumnLabels}" @MDCIconButtonToggle:change="${toggleVerticalColumnLabels}" @icon-button-toggle-change="${toggleVerticalColumnLabels}"> </mwc-icon-button-toggle> `; // clang-format on } private renderDeleteButton() { const deleteMatrix = () => { const event = new CustomEvent('delete-matrix', {}); this.dispatchEvent(event); }; // clang-format off return html` <mwc-icon class="icon-button" @click=${deleteMatrix}> delete_outline </mwc-icon> `; // clang-format on } override render() { if (this.matrixCells.length === 0) { return null; } const rowsWithNonZeroCounts = new Set<string>(); const colsWithNonZeroCounts = new Set<string>(); for (let rowIndex = 0; rowIndex < this.matrixCells.length; rowIndex++) { const row = this.matrixCells[rowIndex]; for (let colIndex = 0; colIndex < row.length; colIndex++) { const cell = row[colIndex]; if (cell.ids.length > 0) { rowsWithNonZeroCounts.add(this.rowLabels[rowIndex]); colsWithNonZeroCounts.add(this.colLabels[colIndex]); } } } const totalColumnClasses = classMap({ 'total-title-cell': true, 'align-bottom': this.verticalColumnLabels }); const colsLabelSpan = this.hideEmptyLabels ? colsWithNonZeroCounts.size : this.colLabels.length; // Add 2 to the appropriate row count to account for the header rows // above and below the data rows in the matrix. const rowsLabelSpan = (this.hideEmptyLabels ? rowsWithNonZeroCounts.size : this.rowLabels.length) + 2; // clang-format off return html` <table> <tr> <th>${this.renderColumnRotateButton()}</th> <td></td> <td class='axis-title' colspan=${colsLabelSpan}> ${this.colTitle} </td> <th class="delete-cell">${this.renderDeleteButton()}</th> </tr> <tr> <td class='axis-title label-vertical' rowspan=${rowsLabelSpan}> <div>${this.rowTitle}</div> </td> <td></td> ${this.colLabels.map( (colLabel, colIndex) => this.renderColHeader( colLabel, colIndex, colsWithNonZeroCounts))} <th class=${totalColumnClasses}><div>Total</div></th> </tr> ${this.rowLabels.map((rowLabel, rowIndex) => this.renderRow( rowLabel, rowIndex, rowsWithNonZeroCounts, colsWithNonZeroCounts))} ${this.renderTotalRow(colsWithNonZeroCounts)} </table> `; // clang-format on } } declare global { interface HTMLElementTagNameMap { 'data-matrix': DataMatrix; } }
the_stack
import { RequestType, NotificationType } from 'vscode-jsonrpc'; /** * Position in a text document expressed as zero-based line and character offset. */ export interface Position { /** * Line position in a document (zero-based). */ line: number; /** * Character offset on a line in a document (zero-based). */ character: number; } /** * The Position namespace provides helper functions to work with * [Position](#Position) literals. */ export declare namespace Position { /** * Creates a new Position literal from the given line and character. * @param line The position's line. * @param character The position's character. */ function create(line: number, character: number): Position; /** * Checks whether the given liternal conforms to the [Position](#Position) interface. */ function is(value: any): value is Position; } /** * A range in a text document expressed as (zero-based) start and end positions. */ export interface Range { /** * The range's start position */ start: Position; /** * The range's end position */ end: Position; } /** * The Range namespace provides helper functions to work with * [Range](#Range) literals. */ export declare namespace Range { /** * Create a new Range liternal. * @param start The range's start position. * @param end The range's end position. */ function create(start: Position, end: Position): Range; /** * Create a new Range liternal. * @param startLine The start line number. * @param startCharacter The start character. * @param endLine The end line number. * @param endCharacter The end character. */ function create(startLine: number, startCharacter: number, endLine: number, endCharacter: number): Range; /** * Checks whether the given literal conforms to the [Range](#Range) interface. */ function is(value: any): value is Range; } /** * Represents a location inside a resource, such as a line * inside a text file. */ export interface Location { uri: string; range: Range; } /** * The Location namespace provides helper functions to work with * [Location](#Location) literals. */ export declare namespace Location { /** * Creates a Location literal. * @param uri The location's uri. * @param range The location's range. */ function create(uri: string, range: Range): Location; /** * Checks whether the given literal conforms to the [Location](#Location) interface. */ function is(value: any): value is Location; } /** * The diagnostic's serverity. */ export declare enum DiagnosticSeverity { /** * Reports an error. */ Error = 1, /** * Reports a warning. */ Warning = 2, /** * Reports an information. */ Information = 3, /** * Reports a hint. */ Hint = 4, } /** * Represents a diagnostic, such as a compiler error or warning. Diagnostic objects * are only valid in the scope of a resource. */ export interface Diagnostic { /** * The range at which the message applies */ range: Range; /** * The diagnostic's severity. Can be omitted. If omitted it is up to the * client to interpret diagnostics as error, warning, info or hint. */ severity?: number; /** * The diagnostic's code. Can be omitted. */ code?: number | string; /** * A human-readable string describing the source of this * diagnostic, e.g. 'typescript' or 'super lint'. */ source?: string; /** * The diagnostic's message. */ message: string; } /** * The Diagnostic namespace provides helper functions to work with * [Diagnostic](#Diagnostic) literals. */ export declare namespace Diagnostic { /** * Creates a new Diagnostic literal. */ function create(range: Range, message: string, severity?: number, code?: number | string, source?: string): Diagnostic; /** * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface. */ function is(value: any): value is Diagnostic; } /** * Represents a reference to a command. Provides a title which * will be used to represent a command in the UI and, optionally, * an array of arguments which will be passed to the command handler * function when invoked. */ export interface Command { /** * Title of the command, like `save`. */ title: string; /** * The identifier of the actual command handler. */ command: string; /** * Arguments that the command handler should be * invoked with. */ arguments?: any[]; } /** * The Command namespace provides helper functions to work with * [Command](#Command) literals. */ export declare namespace Command { /** * Creates a new Command literal. */ function create(title: string, command: string, ...args: any[]): Command; /** * Checks whether the given literal conforms to the [Command](#Command) interface. */ function is(value: any): value is Command; } /** * A text edit applicable to a text document. */ export interface TextEdit { /** * The range of the text document to be manipulated. To insert * text into a document create a range where start === end. */ range: Range; /** * The string to be inserted. For delete operations use an * empty string. */ newText: string; } /** * The TextEdit namespace provides helper function to create replace, * insert and delete edits more easily. */ export declare namespace TextEdit { /** * Creates a replace text edit. * @param range The range of text to be replaced. * @param newText The new text. */ function replace(range: Range, newText: string): TextEdit; /** * Creates a insert text edit. * @param psotion The position to insert the text at. * @param newText The text to be inserted. */ function insert(position: Position, newText: string): TextEdit; /** * Creates a delete text edit. * @param range The range of text to be deleted. */ function del(range: Range): TextEdit; } /** * A workspace edit represents changes to many resources managed * in the workspace. */ export interface WorkspaceEdit { /** * Holds changes to existing resources. */ changes: { [uri: string]: TextEdit[]; }; } /** * A change to capture text edits for existing resources. */ export interface TextEditChange { /** * Gets all text edits for this change. * * @return An array of text edits. */ all(): TextEdit[]; /** * Clears the edits for this change. */ clear(): void; /** * Insert the given text at the given position. * * @param position A position. * @param newText A string. */ insert(position: Position, newText: string): void; /** * Replace the given range with given text for the given resource. * * @param range A range. * @param newText A string. */ replace(range: Range, newText: string): void; /** * Delete the text at the given range. * * @param range A range. */ delete(range: Range): void; } /** * A workspace change helps constructing changes to a workspace. */ export declare class WorkspaceChange { private workspaceEdit; private textEditChanges; constructor(); /** * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal * use to be returned from a workspace edit operation like rename. */ edit: WorkspaceEdit; /** * Returns the [TextEditChange](#TextEditChange) to manage text edits * for resources. */ getTextEditChange(uri: string): TextEditChange; } /** * A literal to identify a text document in the client. */ export interface TextDocumentIdentifier { /** * The text document's uri. */ uri: string; /** * The text document's language identifier */ languageId: string; } /** * The TextDocumentIdentifier namespace provides helper functions to work with * [TextDocumentIdentifier](#TextDocumentIdentifier) literals. */ export declare namespace TextDocumentIdentifier { /** * Creates a new TextDocumentIdentifier literal. * @param uri The document's uri. * @param languageId The document's language id. */ function create(uri: string, languageId?: string): TextDocumentIdentifier; /** * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface. */ function is(value: any): value is TextDocumentIdentifier; } /** * A literal to define the position in a text document. */ export interface TextDocumentPosition extends TextDocumentIdentifier { /** * The position inside the text document. */ position: Position; } /** * The TextDocumentPosition namespace provides helper functions to work with * [TextDocumentPosition](#TextDocumentPosition) literals. */ export declare namespace TextDocumentPosition { /** * Creates a new TextDocumentPosition * @param uri The document's uri. * @param position The position inside the document. */ function create(uri: string, position: Position): TextDocumentPosition; /** * Creates a new TextDocumentPosition * @param uri The document's uri. * @param position The position inside the document. */ function create(uri: string, languageId: string, position: Position): TextDocumentPosition; /** * Checks whether the given literal conforms to the [TextDocumentPosition](#TextDocumentPosition) interface. */ function is(value: any): value is TextDocumentPosition; } /** * Defines the capabilities provided by the client. */ export interface ClientCapabilities { } /** * Defines how the host (editor) should sync * document changes to the language server. */ export declare enum TextDocumentSyncKind { /** * Documents should not be synced at all. */ None = 0, /** * Documents are synced by always sending the full content * of the document. */ Full = 1, /** * Documents are synced by sending the full content on open. * After that only incremental updates to the document are * send. */ Incremental = 2, } /** * Completion options. */ export interface CompletionOptions { /** * The server provides support to resolve additional * information for a completion item. */ resolveProvider?: boolean; /** * The characters that trigger completion automatically. */ triggerCharacters?: string[]; } /** * Signature help options. */ export interface SignatureHelpOptions { /** * The characters that trigger signature help * automatically. */ triggerCharacters?: string[]; } /** * Code Lens options. */ export interface CodeLensOptions { /** * Code lens has a resolve provider as well. */ resolveProvider?: boolean; } /** * Format document on type options */ export interface DocumentOnTypeFormattingOptions { /** * A character on which formatting should be triggered, like `}`. */ firstTriggerCharacter: string; /** * More trigger characters. */ moreTriggerCharacter?: string[]; } /** * Defines the capabilities provided by a language * server. */ export interface ServerCapabilities { /** * Defines how text documents are synced. */ textDocumentSync?: number; /** * The server provides hover support. */ hoverProvider?: boolean; /** * The server provides completion support. */ completionProvider?: CompletionOptions; /** * The server provides signature help support. */ signatureHelpProvider?: SignatureHelpOptions; /** * The server provides goto definition support. */ definitionProvider?: boolean; /** * The server provides find references support. */ referencesProvider?: boolean; /** * The server provides document highlight support. */ documentHighlightProvider?: boolean; /** * The server provides document symbol support. */ documentSymbolProvider?: boolean; /** * The server provides workspace symbol support. */ workspaceSymbolProvider?: boolean; /** * The server provides code actions. */ codeActionProvider?: boolean; /** * The server provides code lens. */ codeLensProvider?: CodeLensOptions; /** * The server provides document formatting. */ documentFormattingProvider?: boolean; /** * The server provides document range formatting. */ documentRangeFormattingProvider?: boolean; /** * The server provides document formatting on typing. */ documentOnTypeFormattingProvider?: DocumentOnTypeFormattingOptions; /** * The server provides rename support. */ renameProvider?: boolean; } /** * The initialize method is sent from the client to the server. * It is send once as the first method after starting up the * worker. The requests parameter is of type [InitializeParams](#InitializeParams) * the response if of type [InitializeResult](#InitializeResult) of a Thenable that * resolves to such. */ export declare namespace InitializeRequest { const type: RequestType<InitializeParams, InitializeResult, InitializeError>; } /** * The initialize parameters */ export interface InitializeParams { /** * The process Id of the parent process that started * the server. */ processId: number; /** * The rootPath of the workspace. Is null * if no folder is open. */ rootPath: string; /** * The capabilities provided by the client (editor) */ capabilities: ClientCapabilities; /** * User provided initialization options. */ initializationOptions: any; } /** * The result returned from an initilize request. */ export interface InitializeResult { /** * The capabilities the language server provides. */ capabilities: ServerCapabilities; } /** * The error returned if the initilize request fails. */ export interface InitializeError { /** * Indicates whether the client should retry to send the * initilize request after showing the message provided * in the {@link ResponseError} */ retry: boolean; } /** * A shutdown request is sent from the client to the server. * It is send once when the client descides to shutdown the * server. The only notification that is sent after a shudown request * is the exit event. */ export declare namespace ShutdownRequest { const type: RequestType<void, void, void>; } /** * The exit event is sent from the client to the server to * ask the server to exit its process. */ export declare namespace ExitNotification { const type: NotificationType<void>; } /** * The configuration change notification is sent from the client to the server * when the client's configuration has changed. The notification contains * the changed configuration as defined by the language client. */ export declare namespace DidChangeConfigurationNotification { const type: NotificationType<DidChangeConfigurationParams>; } /** * The parameters of a change configuration notification. */ export interface DidChangeConfigurationParams { /** * The actual changed settings */ settings: any; } /** * The message type */ export declare enum MessageType { /** * An error message. */ Error = 1, /** * A warning message. */ Warning = 2, /** * An information message. */ Info = 3, /** * A log message. */ Log = 4, } /** * The show message notification is sent from a server to a client to ask * the client to display a particular message in the user interface. */ export declare namespace ShowMessageNotification { const type: NotificationType<ShowMessageParams>; } /** * The parameters of a notification message. */ export interface ShowMessageParams { /** * The message type. See {@link MessageType} */ type: number; /** * The actual message */ message: string; } /** * The log message notification is send from the server to the client to ask * the client to log a particular message. */ export declare namespace LogMessageNotification { let type: NotificationType<LogMessageParams>; } /** * The log message parameters. */ export interface LogMessageParams { /** * The message type. See {@link MessageType} */ type: number; /** * The actual message */ message: string; } /** * The document open notification is sent from the client to the server to signal * newly opened text documents. The document's truth is now managed by the client * and the server must not try to read the document's truth using the document's * uri. */ export declare namespace DidOpenTextDocumentNotification { const type: NotificationType<DidOpenTextDocumentParams>; } /** * The parameters send in a open text document notification */ export interface DidOpenTextDocumentParams extends TextDocumentIdentifier { /** * The content of the opened text document. */ text: string; } /** * The document change notification is sent from the client to the server to signal * changes to a text document. */ export declare namespace DidChangeTextDocumentNotification { const type: NotificationType<DidChangeTextDocumentParams>; } /** * An event describing a change to a text document. If range and rangeLength are omitted * the new text is considered to be the full content of the document. */ export interface TextDocumentContentChangeEvent { /** * The range of the document that changed. */ range?: Range; /** * The length of the range that got replaced. */ rangeLength?: number; /** * The new text of the document. */ text: string; } /** * The change text document notification's parameters. */ export interface DidChangeTextDocumentParams extends TextDocumentIdentifier { contentChanges: TextDocumentContentChangeEvent[]; } /** * The document close notification is sent from the client to the server when * the document got closed in the client. The document's truth now exists * where the document's uri points to (e.g. if the document's uri is a file uri * the truth now exists on disk). */ export declare namespace DidCloseTextDocumentNotification { const type: NotificationType<TextDocumentIdentifier>; } /** * The watched files notification is sent from the client to the server when * the client detects changes to file watched by the lanaguage client. */ export declare namespace DidChangeWatchedFilesNotification { const type: NotificationType<DidChangeWatchedFilesParams>; } /** * The watched files change notification's parameters. */ export interface DidChangeWatchedFilesParams { /** * The actual file events. */ changes: FileEvent[]; } /** * The file event type */ export declare enum FileChangeType { /** * The file got created. */ Created = 1, /** * The file got changed. */ Changed = 2, /** * The file got deleted. */ Deleted = 3, } /** * An event describing a file change. */ export interface FileEvent { /** * The file's uri. */ uri: string; /** * The change type. */ type: number; } /** * Diagnostics notification are sent from the server to the client to signal * results of validation runs. */ export declare namespace PublishDiagnosticsNotification { const type: NotificationType<PublishDiagnosticsParams>; } /** * The publish diagnostic notification's parameters. */ export interface PublishDiagnosticsParams { /** * The URI for which diagnostic information is reported. */ uri: string; /** * An array of diagnostic information items. */ diagnostics: Diagnostic[]; } /** * The kind of a completion entry. */ export declare enum CompletionItemKind { Text = 1, Method = 2, Function = 3, Constructor = 4, Field = 5, Variable = 6, Class = 7, Interface = 8, Module = 9, Property = 10, Unit = 11, Value = 12, Enum = 13, Keyword = 14, Snippet = 15, Color = 16, File = 17, Reference = 18, } /** * A completion item represents a text snippet that is * proposed to complete text that is being typed. */ export interface CompletionItem { /** * The label of this completion item. By default * also the text that is inserted when selecting * this completion. */ label: string; /** * The kind of this completion item. Based of the kind * an icon is chosen by the editor. */ kind?: number; /** * A human-readable string with additional information * about this item, like type or symbol information. */ detail?: string; /** * A human-readable string that represents a doc-comment. */ documentation?: string; /** * A string that shoud be used when comparing this item * with other items. When `falsy` the [label](#CompletionItem.label) * is used. */ sortText?: string; /** * A string that should be used when filtering a set of * completion items. When `falsy` the [label](#CompletionItem.label) * is used. */ filterText?: string; /** * A string that should be inserted a document when selecting * this completion. When `falsy` the [label](#CompletionItem.label) * is used. */ insertText?: string; /** * An [edit](#TextEdit) which is applied to a document when selecting * this completion. When an edit is provided the value of * [insertText](#CompletionItem.insertText) is ignored. */ textEdit?: TextEdit; /** * An data entry field that is preserved on a completion item between * a [CompletionRequest](#CompletionRequest) and a [CompletionResolveRequest] * (#CompletionResolveRequest) */ data?: any; } /** * The CompletionItem namespace provides functions to deal with * completion items. */ export declare namespace CompletionItem { /** * Create a completion item and seed it with a label. * @param label The completion item's label */ function create(label: string): CompletionItem; } /** * Represents a collection of [completion items](#CompletionItem) to be presented * in the editor. */ export declare class CompletionList { /** * This list it not complete. Further typing should result in recomputing * this list. */ isIncomplete: boolean; /** * The completion items. */ items: CompletionItem[]; } /** * The CompletionList namespace provides functions to deal with * completion lists. */ export declare namespace CompletionList { /** * Creates a new completion list. * * @param items The completion items. * @param isIncomplete The list is not complete. */ function create(items?: CompletionItem[], isIncomplete?: boolean): CompletionList; } /** * Request to request completion at a given text document position. The request's * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response * is of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList) * or a Thenable that resolves to such. */ export declare namespace CompletionRequest { const type: RequestType<TextDocumentPosition, CompletionItem[] | CompletionList, void>; } /** * Request to resolve additional information for a given completion item.The request's * parameter is of type [CompletionItem](#CompletionItem) the response * is of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such. */ export declare namespace CompletionResolveRequest { const type: RequestType<CompletionItem, CompletionItem, void>; } export declare type MarkedString = string | { language: string; value: string; }; /** * The result of a hove request. */ export interface Hover { /** * The hover's content */ contents: MarkedString | MarkedString[]; /** * An optional range */ range?: Range; } /** * Request to request hover information at a given text document position. The request's * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of * type [Hover](#Hover) or a Thenable that resolves to such. */ export declare namespace HoverRequest { const type: RequestType<TextDocumentPosition, Hover, void>; } /** * Represents a parameter of a callable-signature. A parameter can * have a label and a doc-comment. */ export interface ParameterInformation { /** * The label of this signature. Will be shown in * the UI. */ label: string; /** * The human-readable doc-comment of this signature. Will be shown * in the UI but can be omitted. */ documentation?: string; } /** * The ParameterInformation namespace provides helper functions to work with * [ParameterInformation](#ParameterInformation) literals. */ export declare namespace ParameterInformation { /** * Creates a new parameter information literal. * * @param label A label string. * @param documentation A doc string. */ function create(label: string, documentation?: string): ParameterInformation; } /** * Represents the signature of something callable. A signature * can have a label, like a function-name, a doc-comment, and * a set of parameters. */ export interface SignatureInformation { /** * The label of this signature. Will be shown in * the UI. */ label: string; /** * The human-readable doc-comment of this signature. Will be shown * in the UI but can be omitted. */ documentation?: string; /** * The parameters of this signature. */ parameters?: ParameterInformation[]; } /** * The SignatureInformation namespace provides helper functions to work with * [SignatureInformation](#SignatureInformation) literals. */ export declare namespace SignatureInformation { function create(label: string, documentation?: string, ...parameters: ParameterInformation[]): SignatureInformation; } /** * Signature help represents the signature of something * callable. There can be multiple signature but only one * active and only one active parameter. */ export interface SignatureHelp { /** * One or more signatures. */ signatures: SignatureInformation[]; /** * The active signature. */ activeSignature?: number; /** * The active parameter of the active signature. */ activeParameter?: number; } export declare namespace SignatureHelpRequest { const type: RequestType<TextDocumentPosition, SignatureHelp, void>; } /** * The definition of a symbol represented as one or many [locations](#Location). * For most programming languages there is only one location at which a symbol is * defined. */ export declare type Definition = Location | Location[]; /** * A request to resolve the defintion location of a symbol at a given text * document position. The request's parameter is of type [TextDocumentPosition] * (#TextDocumentPosition) the response is of type [Definition](#Definition) or a * Thenable that resolves to such. */ export declare namespace DefinitionRequest { const type: RequestType<TextDocumentPosition, Definition, void>; } /** * Value-object that contains additional information when * requesting references. */ export interface ReferenceContext { /** * Include the declaration of the current symbol. */ includeDeclaration: boolean; } /** * Parameters for a [ReferencesRequest](#ReferencesRequest). */ export interface ReferenceParams extends TextDocumentPosition { context: ReferenceContext; } /** * A request to resolve project-wide references for the symbol denoted * by the given text document position. The request's parameter is of * type [ReferenceParams](#ReferenceParams) the response is of type * [Location[]](#Location) or a Thenable that resolves to such. */ export declare namespace ReferencesRequest { const type: RequestType<ReferenceParams, Location[], void>; } /** * A document highlight kind. */ export declare enum DocumentHighlightKind { /** * A textual occurrance. */ Text = 1, /** * Read-access of a symbol, like reading a variable. */ Read = 2, /** * Write-access of a symbol, like writing to a variable. */ Write = 3, } /** * A document highlight is a range inside a text document which deserves * special attention. Usually a document highlight is visualized by changing * the background color of its range. */ export interface DocumentHighlight { /** * The range this highlight applies to. */ range: Range; /** * The highlight kind, default is [text](#DocumentHighlightKind.Text). */ kind?: number; } /** * DocumentHighlight namespace to provide helper functions to work with * [DocumentHighlight](#DocumentHighlight) literals. */ export declare namespace DocumentHighlight { /** * Create a DocumentHighlight object. * @param range The range the highlight applies to. */ function create(range: Range, kind?: number): DocumentHighlight; } /** * Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given * text document position. The request's parameter is of type [TextDocumentPosition] * (#TextDocumentPosition) the request reponse is of type [DocumentHighlight[]] * (#DocumentHighlight) or a Thenable that resolves to such. */ export declare namespace DocumentHighlightRequest { const type: RequestType<TextDocumentPosition, DocumentHighlight[], void>; } /** * A symbol kind. */ export declare enum SymbolKind { File = 1, Module = 2, Namespace = 3, Package = 4, Class = 5, Method = 6, Property = 7, Field = 8, Constructor = 9, Enum = 10, Interface = 11, Function = 12, Variable = 13, Constant = 14, String = 15, Number = 16, Boolean = 17, Array = 18, } /** * Represents information about programming constructs like variables, classes, * interfaces etc. */ export interface SymbolInformation { /** * The name of this symbol. */ name: string; /** * The kind of this symbol. */ kind: number; /** * The location of this symbol. */ location: Location; /** * The name of the symbol containing this symbol. */ containerName?: string; } export declare namespace SymbolInformation { /** * Creates a new symbol information literal. * * @param name The name of the symbol. * @param kind The kind of the symbol. * @param range The range of the location of the symbol. * @param uri The resource of the location of symbol, defaults to the current document. * @param containerName The name of the symbol containg the symbol. */ function create(name: string, kind: SymbolKind, range: Range, uri?: string, containerName?: string): SymbolInformation; } /** * A request to list all symbols found in a given text document. The request's * parameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the * response is of type [SymbolInformation[]](#SymbolInformation) or a Thenable * that resolves to such. */ export declare namespace DocumentSymbolRequest { const type: RequestType<TextDocumentIdentifier, SymbolInformation[], void>; } /** * The parameters of a [WorkspaceSymbolRequest](#WorkspaceSymbolRequest). */ export interface WorkspaceSymbolParams { /** * A non-empty query string */ query: string; } /** * A request to list project-wide symbols matching the query string given * by the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is * of type [SymbolInformation[]](#SymbolInformation) or a Thenable that * resolves to such. */ export declare namespace WorkspaceSymbolRequest { const type: RequestType<WorkspaceSymbolParams, SymbolInformation[], void>; } /** * Contains additional diagnostic information about the context in which * a [code action](#CodeActionProvider.provideCodeActions) is run. */ export interface CodeActionContext { /** * An array of diagnostics. */ diagnostics: Diagnostic[]; } /** * The CodeActionContext namespace provides helper functions to work with * [CodeActionContext](#CodeActionContext) literals. */ export declare namespace CodeActionContext { /** * Creates a new CodeActionContext literal. */ function create(diagnostics: Diagnostic[]): CodeActionContext; /** * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface. */ function is(value: any): value is CodeActionContext; } /** * Params for the CodeActionRequest */ export interface CodeActionParams { /** * The document in which the command was invoked. */ textDocument: TextDocumentIdentifier; /** * The range for which the command was invoked. */ range: Range; /** * Context carrying additional information. */ context: CodeActionContext; } /** * A request to provide commands for the given text document and range. */ export declare namespace CodeActionRequest { const type: RequestType<CodeActionParams, Command[], void>; } /** * A code lens represents a [command](#Command) that should be shown along with * source text, like the number of references, a way to run tests, etc. * * A code lens is _unresolved_ when no command is associated to it. For performance * reasons the creation of a code lens and resolving should be done to two stages. */ export interface CodeLens { /** * The range in which this code lens is valid. Should only span a single line. */ range: Range; /** * The command this code lens represents. */ command?: Command; /** * An data entry field that is preserved on a code lens item between * a [CodeLensRequest](#CodeLensRequest) and a [CodeLensResolveRequest] * (#CodeLensResolveRequest) */ data?: any; } /** * The CodeLens namespace provides helper functions to work with * [CodeLens](#CodeLens) literals. */ export declare namespace CodeLens { /** * Creates a new CodeLens literal. */ function create(range: Range, data?: any): CodeLens; /** * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface. */ function is(value: any): value is CodeLens; } /** * A request to provide code lens for the given text document. */ export declare namespace CodeLensRequest { const type: RequestType<TextDocumentIdentifier, CodeLens[], void>; } /** * A request to resolve a command for a given code lens. */ export declare namespace CodeLensResolveRequest { const type: RequestType<CodeLens, CodeLens, void>; } /** * Value-object describing what options formatting should use. */ export interface FormattingOptions { /** * Size of a tab in spaces. */ tabSize: number; /** * Prefer spaces over tabs. */ insertSpaces: boolean; /** * Signature for further properties. */ [key: string]: boolean | number | string; } /** * The FormattingOptions namespace provides helper functions to work with * [FormattingOptions](#FormattingOptions) literals. */ export declare namespace FormattingOptions { /** * Creates a new FormattingOptions literal. */ function create(tabSize: number, insertSpaces: boolean): FormattingOptions; /** * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface. */ function is(value: any): value is FormattingOptions; } export interface DocumentFormattingParams { /** * The document to format. */ textDocument: TextDocumentIdentifier; /** * The format options */ options: FormattingOptions; } /** * A request to to format a whole document. */ export declare namespace DocumentFormattingRequest { const type: RequestType<DocumentFormattingParams, TextEdit[], void>; } export interface DocumentRangeFormattingParams { /** * The document to format. */ textDocument: TextDocumentIdentifier; /** * The range to format */ range: Range; /** * The format options */ options: FormattingOptions; } /** * A request to to format a range in a document. */ export declare namespace DocumentRangeFormattingRequest { const type: RequestType<DocumentRangeFormattingParams, TextEdit[], void>; } export interface DocumentOnTypeFormattingParams { /** * The document to format. */ textDocument: TextDocumentIdentifier; /** * The position at which this request was send. */ position: Position; /** * The character that has been typed. */ ch: string; /** * The format options. */ options: FormattingOptions; } /** * A request to format a document on type. */ export declare namespace DocumentOnTypeFormattingRequest { const type: RequestType<DocumentOnTypeFormattingParams, TextEdit[], void>; } export interface RenameParams { /** * The document to format. */ textDocument: TextDocumentIdentifier; /** * The position at which this request was send. */ position: Position; /** * The new name of the symbol. If the given name is not valid the * request must return a [ResponseError](#ResponseError) with an * appropriate message set. */ newName: string; } /** * A request to rename a symbol. */ export declare namespace RenameRequest { const type: RequestType<RenameParams, WorkspaceEdit, void>; }
the_stack
import * as service from '../src/service'; import * as embed from '../src/embed'; import * as report from '../src/report'; import * as create from '../src/create'; import * as factories from '../src/factories'; import { EmbedUrlNotSupported } from '../src/errors'; // Todo: remove JQuery usage from this tests file. function ValidateDashboardConfigurationWorksAsExpected(pageView: string, exceptionExpected: boolean, powerbi: service.Service): void { const embedUrl = `https://app.powerbi.com/dashboardEmbed`; const component = $(`<div powerbi-embed-url="${embedUrl}" powerbi-type="report"></div>`) .appendTo('#powerbi-fixture'); const dashboardEmbedConfig = { type: "dashboard", id: "fakeReportId", groupId: "fakeGroupId", accessToken: "fakeAccessToken", embedUrl: "fakeEmbedUrl", pageView: pageView }; let exceptionThrown = false; // Act try { powerbi.embed(component[0], <any>dashboardEmbedConfig); } catch (e) { exceptionThrown = true; } // Assert expect(exceptionThrown).toBe(exceptionExpected); } describe('service', function () { let powerbi: service.Service; let element: HTMLDivElement; beforeEach(function () { powerbi = new service.Service(factories.hpmFactory, factories.wpmpFactory, factories.routerFactory); powerbi.accessToken = 'ABC123'; element = document.createElement('div'); element.id = 'powerbi-fixture'; document.body.appendChild(element); }); afterEach(function () { element.remove(); powerbi.wpmp.stop(); }); it('is defined', function () { expect(powerbi).toBeDefined(); }); describe('init', function () { it('embeds all components found in the DOM', function () { // Arrange const elements = [ '<div id="reportContainer1" powerbi-embed-url="https://embedded.powerbi.com/appTokenReportEmbed?reportId=ABC123" powerbi-type="report"></div>', '<div id="reportContainer2" powerbi-embed-url="https://embedded.powerbi.com/appTokenReportEmbed?reportId=XYZ456" powerbi-type="report"></div>', ]; elements.forEach(element => { $(element).appendTo('#powerbi-fixture'); }); // Act powerbi.init(); // Assert // If embed element has iframe inside it, assume embed action occurred const iframes = document.querySelectorAll('[powerbi-embed-url] iframe'); expect(iframes.length).toEqual(2); }); it('embeds all components found in the DOM without id attribute', function () { // Arrange const elements = [ '<div powerbi-embed-url="https://embedded.powerbi.com/appTokenReportEmbed?reportId=ABC123" powerbi-type="report"></div>', '<div powerbi-embed-url="https://embedded.powerbi.com/appTokenReportEmbed?reportId=XYZ456" powerbi-type="report"></div>', ]; elements.forEach(element => { $(element).appendTo('#powerbi-fixture'); }); // Act powerbi.init(); // Assert // If embed element has iframe inside it, assume embed action occurred const iframes = document.querySelectorAll('[powerbi-embed-url] iframe'); expect(iframes.length).toEqual(2); }); it('embeds all components found in the DOM with duplicate id attribute', function () { // Arrange const elements = [ '<div id="reportContainer1" powerbi-embed-url="https://embedded.powerbi.com/appTokenReportEmbed?reportId=ABC123" powerbi-type="report"></div>', '<div id="reportContainer1" powerbi-embed-url="https://embedded.powerbi.com/appTokenReportEmbed?reportId=XYZ456" powerbi-type="report"></div>', ]; elements.forEach(element => { $(element).appendTo('#powerbi-fixture'); }); // Act powerbi.init(); // Assert // If embed element has iframe inside it, assume embed action occurred const iframes = document.querySelectorAll('[powerbi-embed-url] iframe'); expect(iframes.length).toEqual(2); }); }); describe('get', function () { it('if attempting to get a powerbi component on an element which was not embedded, throw an error', function () { // Arrange const $component = $('<div></div>'); // Act const attemptGet = (): void => { powerbi.get($component[0]); }; // Assert expect(attemptGet).toThrowError(Error); }); it('calling get on element with embeded report component returns the instance', function () { // Arrange const $element = $('<div powerbi-type="report" powerbi-embed-url="https://app.powerbi.com/reportEmbed?reportId=ABC123"></div>') .appendTo('#powerbi-fixture'); const componentInstance = powerbi.embed($element[0]); // Act const componentInstance2 = powerbi.get($element[0]); // Assert expect(componentInstance).toEqual(componentInstance2); }); it('calling get on element with embeded dashboard component returns the instance', function () { // Arrange const $element = $('<div powerbi-type="dashboard" powerbi-embed-url="https://app.powerbi.com/dashboardEmbed?dashboardId=ABC123"></div>') .appendTo('#powerbi-fixture'); const componentInstance = powerbi.embed($element[0]); // Act const componentInstance2 = powerbi.get($element[0]); // Assert expect(componentInstance).toEqual(componentInstance2); }); }); describe('embed', function () { it('if attempting to embed without specifying a type, throw error', function () { // Arrange const component = $('<div></div>') .appendTo('#powerbi-fixture'); // Act const attemptEmbed = (): void => { powerbi.embed(component[0]); }; // Assert expect(attemptEmbed).toThrowError(Error); }); it('if attempting to embed with an unknown type, throw error', function () { // Arrange const component = $('<div powerbi-type="unknownType"></div>') .appendTo('#powerbi-fixture'); // Act const attemptEmbed = (): void => { powerbi.embed(component[0]); }; // Assert expect(attemptEmbed).toThrowError(Error); }); it('if attempting to embed on existing element with different type than previous embed, throw error', function () { // Arrange const component = $('<div></div>') .appendTo('#powerbi-fixture'); const reportEmbedConfig: embed.IEmbedConfiguration = { type: "report", id: "fakeReportId", accessToken: "fakeAccessToken", embedUrl: "fakeEmbedUrl", groupId: "fakeGroupId", }; const dashboardEmbedConfig: embed.IEmbedConfiguration = { type: "dashboard", id: "fakeDashboardId", accessToken: "fakeAccessToken", embedUrl: "fakeEmbedUrl", groupId: "fakeGroupId" }; powerbi.embed(component[0], reportEmbedConfig); // Act const attemptEmbed = (): void => { powerbi.embed(component[0], dashboardEmbedConfig); }; // Assert expect(attemptEmbed).toThrowError(Error); }); it('if Create is already embedded in element re-use the existing component by calling load with the new information', function () { // Arrange const $element = $('<div powerbi-embed-url="https://app.powerbi.com/reportEmbed?reportId=ABC123" powerbi-type="report"></div>') .appendTo('#powerbi-fixture'); const testConfiguration = { accessToken: "fakeAccessToken", embedUrl: 'fakeUrl', id: 'report2', type: 'report', groupId: "fakeGroupId" }; const createConfig: embed.IEmbedConfiguration = { datasetId: "fakeDashboardId", accessToken: "fakeAccessToken", embedUrl: "fakeEmbedUrl", groupId: "fakeGroupId" }; // Act const component = powerbi.createReport($element[0], createConfig); const component2 = powerbi.embed($element[0], testConfiguration); const component3 = powerbi.get($element[0]); // Assert expect(component).toBeDefined(); expect(component2).toBeDefined(); expect(component2).toBe(component3); }); it('Create embed url with correct locale parameters', function () { // Arrange const $reportContainer = $('<div powerbi-embed-url="https://app.powerbi.com/reportEmbed?reportId=ABC123" powerbi-type="report"></div>') .appendTo('#powerbi-fixture'); const testConfiguration: embed.IEmbedConfiguration = { accessToken: "fakeAccessToken", embedUrl: 'fakeUrl?reportId=1', id: 'report2', type: 'report', settings: { localeSettings: { language: 'languageName', formatLocale: 'formatName' } }, groupId: "fakeGroupId", uniqueId: "fakeUid", }; powerbi.embed($reportContainer[0], testConfiguration); let iframe = $reportContainer.find('iframe'); expect(iframe.attr('src')).toEqual('fakeUrl?reportId=1&language=languageName&formatLocale=formatName&uid=fakeUid'); }); it('if attempting to embed without specifying an embed url, throw error', function () { // Arrange const component = $('<div></div>') .appendTo('#powerbi-fixture'); // Act const attemptEmbed = (): void => { const configuration: embed.IEmbedConfiguration = { type: "report", embedUrl: null, accessToken: null, id: null }; powerbi.embed(component[0], configuration); }; // Assert expect(attemptEmbed).toThrowError(Error); }); it('if attempting to embed without specifying an access token, throw error', function () { // Arrange const component = $('<div></div>') .appendTo('#powerbi-fixture'); const originalToken = powerbi.accessToken; powerbi.accessToken = undefined; // Act const attemptEmbed = (): void => { const configuration: embed.IEmbedConfiguration = { type: "report", embedUrl: null, accessToken: null, id: null }; powerbi.embed(component[0], configuration); }; // Assert expect(attemptEmbed).toThrowError(Error); // Cleanup powerbi.accessToken = originalToken; }); it('if attempting to embed without specifying an id, throw error', function () { // Arrange const embedUrl = `https://embedded.powerbi.com/appTokenReportEmbed`; const $reportContainer = $(`<div powerbi-embed-url="${embedUrl}" powerbi-type="report"></div>`) .appendTo('#powerbi-fixture'); // Act const attemptToEmbed = (): void => { powerbi.embed($reportContainer[0]); }; // Assert expect(attemptToEmbed).toThrowError(); }); it('if attempting to embed a dashboard with an invalid pageView, throw error', function () { ValidateDashboardConfigurationWorksAsExpected("notValid", true, powerbi); }); it('if attempting to embed a dashboard with a pageView equals fitToWidth, don\'t throw error', function () { ValidateDashboardConfigurationWorksAsExpected("fitToWidth", false, powerbi); }); it('if attempting to embed a dashboard with a pageView equals oneColumn, don\'t throw error', function () { ValidateDashboardConfigurationWorksAsExpected("oneColumn", false, powerbi); }); it('if attempting to embed a dashboard with a pageView equals actualSize, don\'t throw error', function () { ValidateDashboardConfigurationWorksAsExpected("actualSize", false, powerbi); }); it('if attempting to embed a dashboard with an undefined pageView, don\'t throw error', function () { ValidateDashboardConfigurationWorksAsExpected(undefined, false, powerbi); }); it('should get uqiqueId from config first', function () { // Arrange const testUniqueId = 'fakeUniqueId'; const embedUrl = `https://embedded.powerbi.com/appTokenReportEmbed`; const $reportContainer = $(`<div powerbi-embed-url="${embedUrl}" powerbi-type="report" powerbi-report-id="abc123" powerbi-name="differentUniqueId"></div>`) .appendTo('#powerbi-fixture'); // Act const report = powerbi.embed($reportContainer[0], { uniqueId: testUniqueId }); // Assert expect(report.config.uniqueId).toEqual(testUniqueId); }); it('should get uqiqueId from name attribute if uniqueId is not specified in config', function () { // Arrange const testUniqueId = 'fakeUniqueId'; const embedUrl = `https://embedded.powerbi.com/appTokenReportEmbed`; const $reportContainer = $(`<div powerbi-embed-url="${embedUrl}" powerbi-type="report" powerbi-report-id="abc123" powerbi-name="${testUniqueId}"></div>`) .appendTo('#powerbi-fixture'); // Act const report = powerbi.embed($reportContainer[0]); // Assert expect(report.config.uniqueId).toEqual(testUniqueId); }); it('should generate uqiqueId if uniqueId is not specified in config or attribute', function () { // Arrange const embedUrl = `https://embedded.powerbi.com/appTokenReportEmbed`; const $reportContainer = $(`<div powerbi-embed-url="${embedUrl}" powerbi-type="report" powerbi-report-id="abc123"></div>`) .appendTo('#powerbi-fixture'); // Act const report = powerbi.embed($reportContainer[0]); // Assert expect(report.config.uniqueId).toEqual(jasmine.any(String)); }); it('should get group id from configuration first', function () { // Arrange const testGroupId = "ABC123"; const embedUrl = `https://embedded.powerbi.com/appTokenReportEmbed?groupId=DIFFERENTID`; const $reportContainer = $(`<div powerbi-embed-url="${embedUrl}" powerbi-type="report"></div>`) .appendTo('#powerbi-fixture'); const configuration: embed.IEmbedConfiguration = { id: 'fakeId', groupId: testGroupId }; // Act const report = powerbi.embed($reportContainer[0], configuration); // Assert expect((<embed.IEmbedConfiguration>report.config).groupId).toEqual(testGroupId); }); it('should get groupId from embeddUrl is not specified in config', function () { // Arrange const embedUrl = `https://embedded.powerbi.com/appTokenReportEmbed?groupId=DIFFERENTID`; const $reportContainer = $(`<div powerbi-embed-url="${embedUrl}" powerbi-type="report"></div>`) .appendTo('#powerbi-fixture'); const configuration: embed.IEmbedConfiguration = { id: 'fakeId' }; // Act const report = powerbi.embed($reportContainer[0], configuration); // Assert expect((<embed.IEmbedConfiguration>report.config).groupId).toEqual('DIFFERENTID'); }); it('should get groupId undefined if not specified in embeddUrl or config', function () { // Arrange const embedUrl = `https://embedded.powerbi.com/appTokenReportEmbed?reportId=fakeId`; const $reportContainer = $(`<div powerbi-embed-url="${embedUrl}" powerbi-type="report"></div>`) .appendTo('#powerbi-fixture'); const configuration: embed.IEmbedConfiguration = { id: 'fakeId' }; // Act const report = powerbi.embed($reportContainer[0], configuration); // Assert expect((<embed.IEmbedConfiguration>report.config).groupId).toBeUndefined(); }); it('should get filterPaneEnabled setting from attribute from config and then attribute', function () { // Arrange const embedUrl = `https://embedded.powerbi.com/appTokenReportEmbed`; const $reportContainer = $(`<div powerbi-embed-url="${embedUrl}" powerbi-type="report" powerbi-report-id="abc123" powerbi-settings-filter-pane-enabled="false"></div>`) .appendTo('#powerbi-fixture'); // Act const report = powerbi.embed($reportContainer[0]); // Assert expect(report.config.settings.filterPaneEnabled).toEqual(false); }); it('should get navContentPaneEnabled setting from attribute from config and then attribute', function () { // Arrange const embedUrl = `https://embedded.powerbi.com/appTokenReportEmbed`; const $reportContainer = $(`<div powerbi-embed-url="${embedUrl}" powerbi-type="report" powerbi-report-id="abc123" powerbi-settings-nav-content-pane-enabled="false"></div>`) .appendTo('#powerbi-fixture'); // Act const report = powerbi.embed($reportContainer[0]); // Assert expect(report.config.settings.navContentPaneEnabled).toEqual(false); }); it('if component is already embedded in element re-use the existing component by calling load with the new information', function () { // Arrange const $element = $('<div powerbi-embed-url="https://app.powerbi.com/reportEmbed?reportId=ABC123" powerbi-type="report"></div>') .appendTo('#powerbi-fixture'); const component = powerbi.embed($element[0]); spyOn(component, "load"); const testConfiguration: embed.IEmbedConfiguration = { accessToken: "fakeToken", embedUrl: 'fakeUrl', id: 'report2', }; // Act const component2 = powerbi.embed($element[0], testConfiguration); const actualConfig = <embed.IEmbedConfiguration>component2.config; // Assert expect(component.load).toHaveBeenCalled(); expect(actualConfig.accessToken).toEqual(testConfiguration.accessToken); expect(actualConfig.embedUrl).toEqual(testConfiguration.embedUrl); expect(actualConfig.id).toEqual(testConfiguration.id); expect(component2).toBe(component); }); it('if report embed component was not previously created, creates an instance and return it', function () { // Arrange let component = $('<div powerbi-embed-url="https://app.powerbi.com/reportEmbed?reportId=ABC123" powerbi-type="report"></div>') .appendTo('#powerbi-fixture'); // Act let report = powerbi.embed(component[0]); // Assert expect(report).toBeDefined(); }); it('if dashboard embed component was not previously created, creates an instance and return it', function () { // Arrange let component = $('<div powerbi-embed-url="https://app.powerbi.com/dashboardEmbed?dashboardId=ABC123" powerbi-type="dashboard"></div>') .appendTo('#powerbi-fixture'); // Act let dashboard = powerbi.embed(component[0]); // Assert expect(dashboard).toBeDefined(); }); it("looks for a token first from attribute 'powerbi-access-token'", function () { // Arrange let embedUrl = 'https://embedded.powerbi.com/appTokenReportEmbed?reportId=ABC123'; let testToken = "fakeToken1"; let $reportContainer = $(`<div powerbi-embed-url="${embedUrl}" powerbi-type="report" powerbi-access-token="${testToken}"></div>`) .appendTo('#powerbi-fixture'); // Act powerbi.embed($reportContainer[0]); // Assert let report = powerbi.get($reportContainer[0]); let accessToken = report.config.accessToken; expect(accessToken).toEqual(testToken); }); it("if token is not found by attribute 'powerbi-access-token', fallback to using global", function () { // Arrange let embedUrl = 'https://embedded.powerbi.com/appTokenReportEmbed?reportId=ABC123'; let testToken = "fakeToken1"; let $reportContainer = $(`<div powerbi-embed-url="${embedUrl}" powerbi-type="report"></div>`) .appendTo('#powerbi-fixture'); let originalToken = powerbi.accessToken; powerbi.accessToken = testToken; // Act powerbi.embed($reportContainer[0]); // Assert let report = powerbi.get($reportContainer[0]); let accessToken = report.config.accessToken; expect(accessToken).toEqual(testToken); // Cleanup powerbi.accessToken = originalToken; }); describe('createReport', function () { const embedUrl = `https://embedded.powerbi.com/appTokenReportEmbed`; const accessToken = 'ABC123'; it('if attempting to createReport without specifying an embed url, throw error', function () { // Arrange const component = $('<div></div>') .appendTo('#powerbi-fixture'); // Act const attemptCreate = (): void => { powerbi.createReport(component[0], { embedUrl: null, accessToken: accessToken, datasetId: '123' }); }; // Assert expect(attemptCreate).toThrowError(Error); }); it('if attempting to createReport without specifying an access token, throw error', function () { // Arrange const component = $('<div></div>') .appendTo('#powerbi-fixture'); const originalToken = powerbi.accessToken; powerbi.accessToken = undefined; // Act const attemptCreate = (): void => { powerbi.createReport(component[0], { embedUrl: embedUrl, accessToken: null, datasetId: '123' }); }; // Assert expect(attemptCreate).toThrowError(Error); // Cleanup powerbi.accessToken = originalToken; }); it('if attempting to createReport without specifying an datasetId, throw error', function () { // Arrange const $reportContainer = $(`<div powerbi-embed-url="${embedUrl}"></div>`) .appendTo('#powerbi-fixture'); // Act const attemptCreate = (): void => { powerbi.createReport($reportContainer[0], { embedUrl: embedUrl, accessToken: accessToken }); }; // Assert expect(attemptCreate).toThrowError(); }); }); describe('findIdFromEmbedUrl of Create', function () { it('should return value of datasetId query parameter in embedUrl', function () { // Arrange const testDatasetId = "ABC123"; const testEmbedUrl = `http://embedded.powerbi.com/appTokenReportEmbed?datasetId=${testDatasetId}`; // Act const datasetId = create.Create.findIdFromEmbedUrl(testEmbedUrl); // Assert expect(datasetId).toEqual(testDatasetId); }); it('should return undefinded if the datasetId parameter is not in the url', function () { // Arrange const testEmbedUrl = `http://embedded.powerbi.com/appTokenReportEmbed`; // Act const datasetId = create.Create.findIdFromEmbedUrl(testEmbedUrl); // Assert expect(datasetId).toBeUndefined(); }); it('should get datasetId from configuration first', function () { // Arrange const testDatasetId = "ABC123"; const accessToken = 'ABC123'; const embedUrl = `https://embedded.powerbi.com/appTokenReportEmbed?datasetId=DIFFERENTID`; const $reportContainer = $(`<div powerbi-embed-url="${embedUrl}"></div>`) .appendTo('#powerbi-fixture'); // Act const report = powerbi.createReport($reportContainer[0], { embedUrl: embedUrl, accessToken: accessToken, datasetId: testDatasetId }); // Assert expect(report.createConfig.datasetId).toEqual(testDatasetId); }); it('should fallback to using datasetId from embedUrl if not supplied in create configuration', function () { // Arrange const testDatasetId = "ABC123"; const accessToken = 'ABC123'; const embedUrl = `https://embedded.powerbi.com/appTokenReportEmbed?datasetId=${testDatasetId}`; const $reportContainer = $(`<div powerbi-embed-url="${embedUrl}"</div>`) .appendTo('#powerbi-fixture'); // Act const report = powerbi.createReport($reportContainer[0], { embedUrl: embedUrl, accessToken: accessToken }); // Assert expect(report.createConfig.datasetId).toEqual(testDatasetId); }); it('theme should be in create config if exists is embedConfig', function () { // Arrange const testDatasetId = "ABC123"; const accessToken = 'ABC123'; const theme = { themeJson: { name: "Theme ABC 123" } }; const embedUrl = `https://app.powerbi.com/reportEmbed?datasetId=${testDatasetId}`; const $reportContainer = $(`<div powerbi-embed-url="${embedUrl}"</div>`) .appendTo('#powerbi-fixture'); // Act const report = powerbi.createReport($reportContainer[0], { embedUrl: embedUrl, accessToken: accessToken, theme: theme }); // Assert expect(report.createConfig.theme).toEqual(theme); }); it('theme should be undefined in create config if not exists is embedConfig', function () { // Arrange const testDatasetId = "ABC123"; const accessToken = 'ABC123'; const embedUrl = `https://app.powerbi.com/reportEmbed?datasetId=${testDatasetId}`; const $reportContainer = $(`<div powerbi-embed-url="${embedUrl}"</div>`) .appendTo('#powerbi-fixture'); // Act const report = powerbi.createReport($reportContainer[0], { embedUrl: embedUrl, accessToken: accessToken }); // Assert expect(report.createConfig.theme).toBeUndefined(); }); }); describe('reports', function () { it('creates report iframe from embedUrl', function () { // Arrange let embedUrl = 'https://embedded.powerbi.com/appTokenReportEmbed?reportId=ABC123'; let $reportContainer = $(`<div powerbi-embed-url="${embedUrl}" powerbi-type="report"></div>`) .appendTo('#powerbi-fixture'); // Act powerbi.embed($reportContainer[0], { uniqueId: "fakeUid" }); // Assert let iframe = $reportContainer.find('iframe'); expect(iframe.length).toEqual(1); expect(iframe.attr('src')).toEqual(embedUrl + "&uid=fakeUid"); }); describe('findIdFromEmbedUrl', function () { it('should return value of reportId query parameter in embedUrl', function () { // Arrange const testReportId = "ABC123"; const testEmbedUrl = `http://embedded.powerbi.com/appTokenReportEmbed?reportId=${testReportId}`; // Act const reportId = report.Report.findIdFromEmbedUrl(testEmbedUrl); // Assert expect(reportId).toEqual(testReportId); }); it('should return undefinded if the query parameter is not in the url', function () { // Arrange const testEmbedUrl = `http://embedded.powerbi.com/appTokenReportEmbed`; // Act const reportId = report.Report.findIdFromEmbedUrl(testEmbedUrl); // Assert expect(reportId).toBeUndefined(); }); }); it('should get report id from configuration first', function () { // Arrange const testReportId = "ABC123"; const embedUrl = `https://embedded.powerbi.com/appTokenReportEmbed?reportId=DIFFERENTID`; const $reportContainer = $(`<div powerbi-embed-url="${embedUrl}" powerbi-type="report"></div>`) .appendTo('#powerbi-fixture'); const configuration: embed.IEmbedConfiguration = { id: testReportId }; // Act const report = powerbi.embed($reportContainer[0], configuration); // Assert expect((<embed.IEmbedConfiguration>report.config).id).toEqual(testReportId); }); it('should fallback to using id from attribute if not supplied in embed/load configuration', function () { // Arrange const testReportId = "ABC123"; const embedUrl = `https://embedded.powerbi.com/appTokenReportEmbed?reportId=DIFFERENTID`; const $reportContainer = $(`<div powerbi-embed-url="${embedUrl}" powerbi-type="report" powerbi-report-id="${testReportId}"></div>`) .appendTo('#powerbi-fixture'); // Act const report = powerbi.embed($reportContainer[0]); const config: embed.IEmbedConfiguration = report.config; // Assert expect(config.id).toEqual(testReportId); }); it('should fallback to using id from embedUrl if not supplied in embed/load configuration or attribute', function () { // Arrange const testReportId = "ABC123"; const embedUrl = `https://embedded.powerbi.com/appTokenReportEmbed?reportId=${testReportId}`; const $reportContainer = $(`<div powerbi-embed-url="${embedUrl}" powerbi-type="report" powerbi-report-id></div>`) .appendTo('#powerbi-fixture'); // Act const report = powerbi.embed($reportContainer[0]); // Assert expect((<embed.IEmbedConfiguration>report.config).id).toEqual(testReportId); }); it('theme should be in report config if exists is embedConfig', function () { // Arrange const testReportId = "ABC123"; const embedUrl = `https://app.powerbi.com/reportEmbed?reportId=${testReportId}`; const $reportContainer = $(`<div powerbi-embed-url="${embedUrl}" powerbi-type="report" powerbi-report-id></div>`) .appendTo('#powerbi-fixture'); const theme = { themeJson: { name: "Theme ABC 123" } }; const configuration: embed.IEmbedConfiguration = { theme: theme }; // Act const report = powerbi.embed($reportContainer[0], configuration); // Assert expect((<embed.IEmbedConfiguration>report.config).theme).toEqual(theme); }); it('theme should be undefined in report config if not exists is embedConfig', function () { // Arrange const testReportId = "ABC123"; const embedUrl = `https://app.powerbi.com/reportEmbed?reportId=${testReportId}`; const $reportContainer = $(`<div powerbi-embed-url="${embedUrl}" powerbi-type="report" powerbi-report-id></div>`) .appendTo('#powerbi-fixture'); const configuration: embed.IEmbedConfiguration = {}; // Act const report = powerbi.embed($reportContainer[0], configuration); // Assert expect((<embed.IEmbedConfiguration>report.config).theme).toBeUndefined(); }); }); describe('tiles', function () { it('creates tile iframe from embedUrl', function () { // Arrange let embedUrl = 'https://app.powerbi.com/embed?dashboardId=D1&tileId=T1'; let $tileContainer = $('<div powerbi-embed-url="' + embedUrl + '" powerbi-type="tile"></div>') .appendTo('#powerbi-fixture'); // Act powerbi.embed($tileContainer[0], { dashboardId: "D1", embedUrl: embedUrl }); // Assert let iframe = $tileContainer.find('iframe'); expect(iframe.length).toEqual(1); expect(iframe.attr('src').indexOf(embedUrl)).toEqual(0); }); }); }); describe('bootstrap', function () { it('if attempting to bootstrap without specifying a type, throw error', function () { // Arrange const component = $('<div></div>') .appendTo('#powerbi-fixture'); // Act const attemptEmbed = (): void => { powerbi.bootstrap(component[0], {}); }; // Assert expect(attemptEmbed).toThrowError(Error); }); it('if attempting to bootstrap with an unknown type, throw error', function () { // Arrange const component = $('<div powerbi-type="unknownType"></div>') .appendTo('#powerbi-fixture'); // Act const attemptEmbed = (): void => { powerbi.bootstrap(component[0], {}); }; // Assert expect(attemptEmbed).toThrowError(Error); }); it('if attempting to bootstrap on existing element, throw error', function () { // Arrange const component = $('<div></div>') .appendTo('#powerbi-fixture'); const reportEmbedConfig: embed.IEmbedConfiguration = { type: "report", id: "fakeReportId", accessToken: "fakeAccessToken", embedUrl: "fakeEmbedUrl", groupId: "fakeGroupId", }; const reportEmbedConfig2: embed.IEmbedConfiguration = { type: "report", id: "fakeReportId2", accessToken: "fakeAccessToken", embedUrl: "fakeEmbedUrl", groupId: "fakeGroupId" }; powerbi.embed(component[0], reportEmbedConfig); // Act const attemptBootstrap = (): void => { powerbi.bootstrap(component[0], reportEmbedConfig2); }; // Assert expect(attemptBootstrap).toThrowError(Error); }); it('powerbi.embed should use the same iframe is already embedded with powerbi.bootstrap', function () { // Arrange const $element = $('<div powerbi-embed-url="https://app.powerbi.com/reportEmbed?reportId=ABC123" powerbi-type="report"></div>') .appendTo('#powerbi-fixture'); const testConfiguration = { accessToken: "fakeAccessToken", embedUrl: 'fakeUrl', id: 'report2', type: 'report', groupId: "fakeGroupId" }; // Act const component = powerbi.bootstrap($element[0], { type: 'report', embedUrl: 'fakeUrl2', }); const component2 = powerbi.embed($element[0], testConfiguration); const component3 = powerbi.get($element[0]); // Assert expect(component).toBeDefined(); expect(component2).toBeDefined(); expect(component2).toBe(component3); }); it('powerbi.bootstrap url with correct locale parameters', function () { // Arrange const $reportContainer = $('<div powerbi-embed-url="https://app.powerbi.com/reportEmbed?reportId=ABC123" powerbi-type="report"></div>') .appendTo('#powerbi-fixture'); const testConfiguration: embed.IEmbedConfiguration = { embedUrl: 'fakeUrl?reportId=1', id: 'report2', type: 'report', settings: { localeSettings: { language: 'languageName', formatLocale: 'formatName' } }, uniqueId: "fakeUid", }; powerbi.bootstrap($reportContainer[0], testConfiguration); let iframe = $reportContainer.find('iframe'); expect(iframe.attr('src')).toEqual('fakeUrl?reportId=1&language=languageName&formatLocale=formatName&uid=fakeUid'); }); it('Cannot use JS SDK if autoAuth in embed url', function () { const embedUrl = `https://app.powerbi.com/reportEmbed?reportId=ABC123&autoAuth=true`; const $element = $(`<div powerbi-type="dashboard" powerbi-embed-url="${embedUrl}"></div>`) .appendTo('#powerbi-fixture'); const reportEmbedConfig = { type: "report", id: "fakeReportId", groupId: "fakeGroupId", accessToken: "fakeAccessToken", embedUrl: embedUrl }; let exceptionThrown = false; try { powerbi.embed($element[0], reportEmbedConfig); } catch (e) { exceptionThrown = true; expect(e.message).toBe(EmbedUrlNotSupported); } expect(exceptionThrown).toBe(true); $element.empty(); $element.remove(); }); }); describe('reset', function () { it('deletes the powerBiEmbed property on the element', function () { // Arrange const $element = $('<div></div>'); const config: embed.IEmbedConfiguration = { type: 'report', embedUrl: 'fakeUrl', id: 'fakeId', accessToken: 'fakeToken' }; powerbi.embed($element.get(0), config); // Act expect((<service.IPowerBiElement>$element.get(0)).powerBiEmbed).toBeDefined(); powerbi.reset($element.get(0)); // Assert expect((<service.IPowerBiElement>$element.get(0)).powerBiEmbed).toBeUndefined(); }); it('clears the innerHTML of the element', function () { // Arrange const $element = $('<div></div>'); const config: embed.IEmbedConfiguration = { type: 'report', embedUrl: 'fakeUrl', id: 'fakeReportId', accessToken: 'fakeToken' }; powerbi.embed($element.get(0), config); // Act let iframe = $element.find('iframe'); expect(iframe.length).toEqual(1); powerbi.reset($element.get(0)); // Assert expect($element.html()).toEqual(''); }); it('removes the powerbi instance from the list of embeds', function () { // Arrange const $element = $('<div></div>'); const testEmbedConfig = { type: 'report', embedUrl: 'fakeUrl', id: 'fakeReportId', accessToken: 'fakeToken', uniqueId: 'fakeUniqeId' }; powerbi.embed($element.get(0), testEmbedConfig); // Act const report = powerbi.find(testEmbedConfig.uniqueId); expect(report).toBeDefined(); powerbi.reset($element.get(0)); // Assert const report2 = powerbi.find(testEmbedConfig.uniqueId); expect(report2).toBeUndefined(); }); }); });
the_stack
import { blockchainTests, constants, expect, getRandomInteger, Numberish, randomAddress, } from '@0x/contracts-test-utils'; import { AuthorizableRevertErrors } from '@0x/contracts-utils'; import { AssetProxyId } from '@0x/types'; import { AbiEncoder, BigNumber, hexUtils, StringRevertError } from '@0x/utils'; import { DecodedLogs } from 'ethereum-types'; import * as _ from 'lodash'; import { artifacts } from './artifacts'; import { ERC20BridgeProxyContract, TestERC20BridgeContract } from './wrappers'; blockchainTests.resets('ERC20BridgeProxy unit tests', env => { const PROXY_ID = AssetProxyId.ERC20Bridge; const BRIDGE_SUCCESS_RETURN_DATA = hexUtils.rightPad(PROXY_ID); let owner: string; let badCaller: string; let assetProxy: ERC20BridgeProxyContract; let bridgeContract: TestERC20BridgeContract; let testTokenAddress: string; before(async () => { [owner, badCaller] = await env.getAccountAddressesAsync(); assetProxy = await ERC20BridgeProxyContract.deployFrom0xArtifactAsync( artifacts.ERC20BridgeProxy, env.provider, env.txDefaults, artifacts, ); bridgeContract = await TestERC20BridgeContract.deployFrom0xArtifactAsync( artifacts.TestERC20Bridge, env.provider, env.txDefaults, artifacts, ); testTokenAddress = await bridgeContract.testToken().callAsync(); await assetProxy.addAuthorizedAddress(owner).awaitTransactionSuccessAsync(); }); interface AssetDataOpts { tokenAddress: string; bridgeAddress: string; bridgeData: BridgeDataOpts; } interface BridgeDataOpts { transferAmount: Numberish; revertError?: string; returnData: string; } function createAssetData(opts?: Partial<AssetDataOpts>): AssetDataOpts { return _.merge( { tokenAddress: testTokenAddress, bridgeAddress: bridgeContract.address, bridgeData: createBridgeData(), }, opts, ); } function createBridgeData(opts?: Partial<BridgeDataOpts>): BridgeDataOpts { return _.merge( { transferAmount: constants.ZERO_AMOUNT, returnData: BRIDGE_SUCCESS_RETURN_DATA, }, opts, ); } function encodeAssetData(opts: AssetDataOpts): string { const encoder = AbiEncoder.createMethod('ERC20BridgeProxy', [ { name: 'tokenAddress', type: 'address' }, { name: 'bridgeAddress', type: 'address' }, { name: 'bridgeData', type: 'bytes' }, ]); return encoder.encode([opts.tokenAddress, opts.bridgeAddress, encodeBridgeData(opts.bridgeData)]); } function encodeBridgeData(opts: BridgeDataOpts): string { const encoder = AbiEncoder.create([ { name: 'transferAmount', type: 'int256' }, { name: 'revertData', type: 'bytes' }, { name: 'returnData', type: 'bytes' }, ]); const revertErrorBytes = opts.revertError !== undefined ? new StringRevertError(opts.revertError).encode() : '0x'; return encoder.encode([new BigNumber(opts.transferAmount), revertErrorBytes, opts.returnData]); } async function setTestTokenBalanceAsync(_owner: string, balance: Numberish): Promise<void> { await bridgeContract.setTestTokenBalance(_owner, new BigNumber(balance)).awaitTransactionSuccessAsync(); } describe('transferFrom()', () => { interface TransferFromOpts { assetData: AssetDataOpts; from: string; to: string; amount: Numberish; } function createTransferFromOpts(opts?: Partial<TransferFromOpts>): TransferFromOpts { const transferAmount = _.get(opts, ['amount'], getRandomInteger(1, 100e18)) as BigNumber; return _.merge( { assetData: createAssetData({ bridgeData: createBridgeData({ transferAmount, }), }), from: randomAddress(), to: randomAddress(), amount: transferAmount, }, opts, ); } async function transferFromAsync(opts?: Partial<TransferFromOpts>, caller?: string): Promise<DecodedLogs> { const _opts = createTransferFromOpts(opts); const { logs } = await assetProxy .transferFrom(encodeAssetData(_opts.assetData), _opts.from, _opts.to, new BigNumber(_opts.amount)) .awaitTransactionSuccessAsync({ from: caller }); return (logs as any) as DecodedLogs; } it('succeeds if the bridge succeeds and balance increases by `amount`', async () => { const tx = transferFromAsync(); return expect(tx).to.be.fulfilled(''); }); it('succeeds if balance increases more than `amount`', async () => { const amount = getRandomInteger(1, 100e18); const tx = transferFromAsync({ amount, assetData: createAssetData({ bridgeData: createBridgeData({ transferAmount: amount.plus(1), }), }), }); return expect(tx).to.be.fulfilled(''); }); it('passes the correct arguments to the bridge contract', async () => { const opts = createTransferFromOpts(); const logs = await transferFromAsync(opts); expect(logs.length).to.eq(1); const args = logs[0].args; expect(args.tokenAddress).to.eq(opts.assetData.tokenAddress); expect(args.from).to.eq(opts.from); expect(args.to).to.eq(opts.to); expect(args.amount).to.bignumber.eq(opts.amount); expect(args.bridgeData).to.eq(encodeBridgeData(opts.assetData.bridgeData)); }); it('fails if not called by an authorized address', async () => { const tx = transferFromAsync({}, badCaller); return expect(tx).to.revertWith(new AuthorizableRevertErrors.SenderNotAuthorizedError(badCaller)); }); it('fails if asset data is truncated', async () => { const opts = createTransferFromOpts(); const truncatedAssetData = hexUtils.slice(encodeAssetData(opts.assetData), 0, -1); const tx = assetProxy .transferFrom(truncatedAssetData, opts.from, opts.to, new BigNumber(opts.amount)) .awaitTransactionSuccessAsync(); return expect(tx).to.be.rejected(); }); it('fails if bridge returns nothing', async () => { const tx = transferFromAsync({ assetData: createAssetData({ bridgeData: createBridgeData({ returnData: '0x', }), }), }); // This will actually revert when the AP tries to decode the return // value. return expect(tx).to.be.rejected(); }); it('fails if bridge returns true', async () => { const tx = transferFromAsync({ assetData: createAssetData({ bridgeData: createBridgeData({ returnData: hexUtils.leftPad('0x1'), }), }), }); // This will actually revert when the AP tries to decode the return // value. return expect(tx).to.be.rejected(); }); it('fails if bridge returns 0x1', async () => { const tx = transferFromAsync({ assetData: createAssetData({ bridgeData: createBridgeData({ returnData: hexUtils.rightPad('0x1'), }), }), }); return expect(tx).to.revertWith('BRIDGE_FAILED'); }); it('fails if bridge is an EOA', async () => { const tx = transferFromAsync({ assetData: createAssetData({ bridgeAddress: randomAddress(), }), }); // This will actually revert when the AP tries to decode the return // value. return expect(tx).to.be.rejected(); }); it('fails if bridge reverts', async () => { const revertError = 'FOOBAR'; const tx = transferFromAsync({ assetData: createAssetData({ bridgeData: createBridgeData({ revertError, }), }), }); return expect(tx).to.revertWith(revertError); }); it('fails if balance of `to` increases by less than `amount`', async () => { const amount = getRandomInteger(1, 100e18); const tx = transferFromAsync({ amount, assetData: createAssetData({ bridgeData: createBridgeData({ transferAmount: amount.minus(1), }), }), }); return expect(tx).to.revertWith('BRIDGE_UNDERPAY'); }); it('fails if balance of `to` decreases', async () => { const toAddress = randomAddress(); await setTestTokenBalanceAsync(toAddress, 1e18); const tx = transferFromAsync({ to: toAddress, assetData: createAssetData({ bridgeData: createBridgeData({ transferAmount: -1, }), }), }); return expect(tx).to.revertWith('BRIDGE_UNDERPAY'); }); }); describe('balanceOf()', () => { it('retrieves the balance of the encoded token', async () => { const _owner = randomAddress(); const balance = getRandomInteger(1, 100e18); await bridgeContract.setTestTokenBalance(_owner, balance).awaitTransactionSuccessAsync(); const assetData = createAssetData({ tokenAddress: testTokenAddress, }); const actualBalance = await assetProxy.balanceOf(encodeAssetData(assetData), _owner).callAsync(); expect(actualBalance).to.bignumber.eq(balance); }); }); describe('getProxyId()', () => { it('returns the correct proxy ID', async () => { const proxyId = await assetProxy.getProxyId().callAsync(); expect(proxyId).to.eq(PROXY_ID); }); }); });
the_stack
import { declare } from "@babel/helper-plugin-utils"; import hoistVariables from "@babel/helper-hoist-variables"; import { template, types as t } from "@babel/core"; import { getImportSource } from "babel-plugin-dynamic-import-node/utils"; import { rewriteThis, getModuleName } from "@babel/helper-module-transforms"; import { isIdentifierName } from "@babel/helper-validator-identifier"; const buildTemplate = template(` SYSTEM_REGISTER(MODULE_NAME, SOURCES, function (EXPORT_IDENTIFIER, CONTEXT_IDENTIFIER) { "use strict"; BEFORE_BODY; return { setters: SETTERS, execute: EXECUTE, }; }); `); const buildExportAll = template(` for (var KEY in TARGET) { if (KEY !== "default" && KEY !== "__esModule") EXPORT_OBJ[KEY] = TARGET[KEY]; } `); const MISSING_PLUGIN_WARNING = `\ WARNING: Dynamic import() transformation must be enabled using the @babel/plugin-proposal-dynamic-import plugin. Babel 8 will no longer transform import() without using that plugin. `; const MISSING_PLUGIN_ERROR = `\ ERROR: Dynamic import() transformation must be enabled using the @babel/plugin-proposal-dynamic-import plugin. Babel 8 no longer transforms import() without using that plugin. `; //todo: use getExportSpecifierName in `helper-module-transforms` when this library is refactored to NodePath usage. export function getExportSpecifierName( node: t.Node, stringSpecifiers: Set<string>, ): string { if (node.type === "Identifier") { return node.name; } else if (node.type === "StringLiteral") { const stringValue = node.value; // add specifier value to `stringSpecifiers` only when it can not be converted to an identifier name // i.e In `import { "foo" as bar }` // we do not consider `"foo"` to be a `stringSpecifier` because we can treat it as // `import { foo as bar }` // This helps minimize the size of `stringSpecifiers` and reduce overhead of checking valid identifier names // when building transpiled code from metadata if (!isIdentifierName(stringValue)) { stringSpecifiers.add(stringValue); } return stringValue; } else { throw new Error( `Expected export specifier to be either Identifier or StringLiteral, got ${node.type}`, ); } } type PluginState = { contextIdent: string; // List of names that should only be printed as string literals. // i.e. `import { "any unicode" as foo } from "some-module"` // `stringSpecifiers` is Set(1) ["any unicode"] // In most cases `stringSpecifiers` is an empty Set stringSpecifiers: Set<string>; }; function constructExportCall( path, exportIdent, exportNames, exportValues, exportStarTarget, stringSpecifiers: Set<string>, ) { const statements = []; if (!exportStarTarget) { if (exportNames.length === 1) { statements.push( t.expressionStatement( t.callExpression(exportIdent, [ t.stringLiteral(exportNames[0]), exportValues[0], ]), ), ); } else { const objectProperties = []; for (let i = 0; i < exportNames.length; i++) { const exportName = exportNames[i]; const exportValue = exportValues[i]; objectProperties.push( t.objectProperty( stringSpecifiers.has(exportName) ? t.stringLiteral(exportName) : t.identifier(exportName), exportValue, ), ); } statements.push( t.expressionStatement( t.callExpression(exportIdent, [t.objectExpression(objectProperties)]), ), ); } } else { const exportObj = path.scope.generateUid("exportObj"); statements.push( t.variableDeclaration("var", [ t.variableDeclarator(t.identifier(exportObj), t.objectExpression([])), ]), ); statements.push( buildExportAll({ KEY: path.scope.generateUidIdentifier("key"), EXPORT_OBJ: t.identifier(exportObj), TARGET: exportStarTarget, }), ); for (let i = 0; i < exportNames.length; i++) { const exportName = exportNames[i]; const exportValue = exportValues[i]; statements.push( t.expressionStatement( t.assignmentExpression( "=", t.memberExpression( t.identifier(exportObj), t.identifier(exportName), ), exportValue, ), ), ); } statements.push( t.expressionStatement( t.callExpression(exportIdent, [t.identifier(exportObj)]), ), ); } return statements; } export default declare((api, options) => { api.assertVersion(7); const { systemGlobal = "System", allowTopLevelThis = false } = options; const IGNORE_REASSIGNMENT_SYMBOL = Symbol(); const reassignmentVisitor = { "AssignmentExpression|UpdateExpression"(path) { if (path.node[IGNORE_REASSIGNMENT_SYMBOL]) return; path.node[IGNORE_REASSIGNMENT_SYMBOL] = true; const arg = path.get(path.isAssignmentExpression() ? "left" : "argument"); if (arg.isObjectPattern() || arg.isArrayPattern()) { const exprs = [path.node]; for (const name of Object.keys(arg.getBindingIdentifiers())) { if (this.scope.getBinding(name) !== path.scope.getBinding(name)) { return; } const exportedNames = this.exports[name]; if (!exportedNames) return; for (const exportedName of exportedNames) { exprs.push( this.buildCall(exportedName, t.identifier(name)).expression, ); } } path.replaceWith(t.sequenceExpression(exprs)); return; } if (!arg.isIdentifier()) return; const name = arg.node.name; // redeclared in this scope if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; const exportedNames = this.exports[name]; if (!exportedNames) return; let node = path.node; // if it is a non-prefix update expression (x++ etc) // then we must replace with the expression (_export('x', x + 1), x++) // in order to ensure the same update expression value const isPostUpdateExpression = path.isUpdateExpression({ prefix: false }); if (isPostUpdateExpression) { node = t.binaryExpression( node.operator[0], t.unaryExpression("+", t.cloneNode(node.argument)), t.numericLiteral(1), ); } for (const exportedName of exportedNames) { node = this.buildCall(exportedName, node).expression; } if (isPostUpdateExpression) { node = t.sequenceExpression([node, path.node]); } path.replaceWith(node); }, }; return { name: "transform-modules-systemjs", pre() { this.file.set("@babel/plugin-transform-modules-*", "systemjs"); }, visitor: { CallExpression(path, state: PluginState) { if (t.isImport(path.node.callee)) { if (!this.file.has("@babel/plugin-proposal-dynamic-import")) { if (process.env.BABEL_8_BREAKING) { throw new Error(MISSING_PLUGIN_ERROR); } else { console.warn(MISSING_PLUGIN_WARNING); } } path.replaceWith( t.callExpression( t.memberExpression( t.identifier(state.contextIdent), t.identifier("import"), ), [getImportSource(t, path.node)], ), ); } }, MetaProperty(path, state: PluginState) { if ( path.node.meta.name === "import" && path.node.property.name === "meta" ) { path.replaceWith( t.memberExpression( t.identifier(state.contextIdent), t.identifier("meta"), ), ); } }, ReferencedIdentifier(path, state) { if ( path.node.name === "__moduleName" && !path.scope.hasBinding("__moduleName") ) { path.replaceWith( t.memberExpression( t.identifier(state.contextIdent), t.identifier("id"), ), ); } }, Program: { enter(path, state) { state.contextIdent = path.scope.generateUid("context"); state.stringSpecifiers = new Set(); if (!allowTopLevelThis) { rewriteThis(path); } }, exit(path, state: PluginState) { const scope = path.scope; const exportIdent = scope.generateUid("export"); const { contextIdent, stringSpecifiers } = state; const exportMap = Object.create(null); const modules = []; const beforeBody = []; const setters = []; const sources = []; const variableIds = []; const removedPaths = []; function addExportName(key, val) { exportMap[key] = exportMap[key] || []; exportMap[key].push(val); } function pushModule(source, key, specifiers) { let module; modules.forEach(function (m) { if (m.key === source) { module = m; } }); if (!module) { modules.push( (module = { key: source, imports: [], exports: [] }), ); } module[key] = module[key].concat(specifiers); } function buildExportCall(name, val) { return t.expressionStatement( t.callExpression(t.identifier(exportIdent), [ t.stringLiteral(name), val, ]), ); } const exportNames = []; const exportValues = []; const body: Array<any> = path.get("body"); for (const path of body) { if (path.isFunctionDeclaration()) { beforeBody.push(path.node); removedPaths.push(path); } else if (path.isClassDeclaration()) { variableIds.push(t.cloneNode(path.node.id)); path.replaceWith( t.expressionStatement( t.assignmentExpression( "=", t.cloneNode(path.node.id), t.toExpression(path.node), ), ), ); } else if (path.isImportDeclaration()) { const source = path.node.source.value; pushModule(source, "imports", path.node.specifiers); for (const name of Object.keys(path.getBindingIdentifiers())) { scope.removeBinding(name); variableIds.push(t.identifier(name)); } path.remove(); } else if (path.isExportAllDeclaration()) { pushModule(path.node.source.value, "exports", path.node); path.remove(); } else if (path.isExportDefaultDeclaration()) { const declar = path.get("declaration"); const id = declar.node.id; if (declar.isClassDeclaration()) { if (id) { exportNames.push("default"); exportValues.push(scope.buildUndefinedNode()); variableIds.push(t.cloneNode(id)); addExportName(id.name, "default"); path.replaceWith( t.expressionStatement( t.assignmentExpression( "=", t.cloneNode(id), t.toExpression(declar.node), ), ), ); } else { exportNames.push("default"); exportValues.push(t.toExpression(declar.node)); removedPaths.push(path); } } else if (declar.isFunctionDeclaration()) { if (id) { beforeBody.push(declar.node); exportNames.push("default"); exportValues.push(t.cloneNode(id)); addExportName(id.name, "default"); } else { exportNames.push("default"); exportValues.push(t.toExpression(declar.node)); } removedPaths.push(path); } else { path.replaceWith(buildExportCall("default", declar.node)); } } else if (path.isExportNamedDeclaration()) { const declar = path.get("declaration"); if (declar.node) { path.replaceWith(declar); if (path.isFunction()) { const node = declar.node; const name = node.id.name; addExportName(name, name); beforeBody.push(node); exportNames.push(name); exportValues.push(t.cloneNode(node.id)); removedPaths.push(path); } else if (path.isClass()) { const name = declar.node.id.name; exportNames.push(name); exportValues.push(scope.buildUndefinedNode()); variableIds.push(t.cloneNode(declar.node.id)); path.replaceWith( t.expressionStatement( t.assignmentExpression( "=", t.cloneNode(declar.node.id), t.toExpression(declar.node), ), ), ); addExportName(name, name); } else { for (const name of Object.keys( declar.getBindingIdentifiers(), )) { addExportName(name, name); } } } else { const specifiers = path.node.specifiers; if (specifiers?.length) { if (path.node.source) { pushModule(path.node.source.value, "exports", specifiers); path.remove(); } else { const nodes = []; for (const specifier of specifiers) { const { local, exported } = specifier; const binding = scope.getBinding(local.name); const exportedName = getExportSpecifierName( exported, stringSpecifiers, ); // hoisted function export if ( binding && t.isFunctionDeclaration(binding.path.node) ) { exportNames.push(exportedName); exportValues.push(t.cloneNode(local)); } // only globals also exported this way else if (!binding) { nodes.push(buildExportCall(exportedName, local)); } addExportName(local.name, exportedName); } path.replaceWithMultiple(nodes); } } else { path.remove(); } } } } modules.forEach(function (specifiers) { const setterBody = []; const target = scope.generateUid(specifiers.key); for (let specifier of specifiers.imports) { if (t.isImportNamespaceSpecifier(specifier)) { setterBody.push( t.expressionStatement( t.assignmentExpression( "=", specifier.local, t.identifier(target), ), ), ); } else if (t.isImportDefaultSpecifier(specifier)) { specifier = t.importSpecifier( specifier.local, t.identifier("default"), ); } if (t.isImportSpecifier(specifier)) { const { imported } = specifier; setterBody.push( t.expressionStatement( t.assignmentExpression( "=", specifier.local, t.memberExpression( t.identifier(target), specifier.imported, /* computed */ imported.type === "StringLiteral", ), ), ), ); } } if (specifiers.exports.length) { const exportNames = []; const exportValues = []; let hasExportStar = false; for (const node of specifiers.exports) { if (t.isExportAllDeclaration(node)) { hasExportStar = true; } else if (t.isExportSpecifier(node)) { const exportedName = getExportSpecifierName( node.exported, stringSpecifiers, ); exportNames.push(exportedName); exportValues.push( t.memberExpression( t.identifier(target), node.local, t.isStringLiteral(node.local), ), ); } else { // todo } } setterBody.push( ...constructExportCall( path, t.identifier(exportIdent), exportNames, exportValues, hasExportStar ? t.identifier(target) : null, stringSpecifiers, ), ); } sources.push(t.stringLiteral(specifiers.key)); setters.push( t.functionExpression( null, [t.identifier(target)], t.blockStatement(setterBody), ), ); }); let moduleName = getModuleName(this.file.opts, options); // @ts-expect-error todo(flow->ts): do not reuse variables if (moduleName) moduleName = t.stringLiteral(moduleName); hoistVariables( path, (id, name, hasInit) => { variableIds.push(id); if (!hasInit && name in exportMap) { for (const exported of exportMap[name]) { exportNames.push(exported); exportValues.push(scope.buildUndefinedNode()); } } }, null, ); if (variableIds.length) { beforeBody.unshift( t.variableDeclaration( "var", variableIds.map(id => t.variableDeclarator(id)), ), ); } if (exportNames.length) { beforeBody.push( ...constructExportCall( path, t.identifier(exportIdent), exportNames, exportValues, null, stringSpecifiers, ), ); } path.traverse(reassignmentVisitor, { exports: exportMap, buildCall: buildExportCall, scope, }); for (const path of removedPaths) { path.remove(); } let hasTLA = false; path.traverse({ AwaitExpression(path) { hasTLA = true; path.stop(); }, Function(path) { path.skip(); }, noScope: true, }); path.node.body = [ buildTemplate({ SYSTEM_REGISTER: t.memberExpression( t.identifier(systemGlobal), t.identifier("register"), ), BEFORE_BODY: beforeBody, MODULE_NAME: moduleName, SETTERS: t.arrayExpression(setters), EXECUTE: t.functionExpression( null, [], t.blockStatement(path.node.body), false, hasTLA, ), SOURCES: t.arrayExpression(sources), EXPORT_IDENTIFIER: t.identifier(exportIdent), CONTEXT_IDENTIFIER: t.identifier(contextIdent), }), ]; }, }, }, }; });
the_stack
import assert from "assert"; import { db } from "../../src/databases/databases"; import { UserID } from "../../src/types/user.model"; import { getHash } from "../../src/utils/getHash"; import { getReputation, calculateReputationFromMetrics } from "../../src/utils/reputation"; describe("reputation", () => { // constants const userIDLowSubmissions = "reputation-lowsubmissions" as UserID; const userHashLowSubmissions = getHash(userIDLowSubmissions); const userIDHighDownvotes = "reputation-highdownvotes" as UserID; const userHashHighDownvotes = getHash(userIDHighDownvotes); const userIDHighNonSelfDownvotes = "reputation-highnonselfdownvotes" as UserID; const userHashHighNonSelfDownvotes = getHash(userIDHighNonSelfDownvotes); const userIDNewSubmissions = "reputation-newsubmissions" as UserID; const userHashNewSubmissions = getHash(userIDNewSubmissions); const userIDLowSum = "reputation-lowsum" as UserID; const userHashLowSum = getHash(userIDLowSum); const userIDHighRepBeforeManualVote = "reputation-oldhighrep" as UserID; const userHashHighRepBeforeManualVote = getHash(userIDHighRepBeforeManualVote); const userIDHighRep = "reputation-highrep" as UserID; const userHashHighRep = getHash(userIDHighRep); const userIDHighRepAndLocked = "reputation-highlockedrep" as UserID; const userHashHighAndLocked = getHash(userIDHighRepAndLocked); const userIDHaveMostUpvotedInLockedVideo = "reputation-mostupvotedaslocked" as UserID; const userHashHaveMostUpvotedInLockedVideo = getHash(userIDHaveMostUpvotedInLockedVideo); before(async function() { this.timeout(5000); // this preparation takes longer then usual const videoID = "reputation-videoID"; const videoID2 = "reputation-videoID-2"; const sponsorTimesInsertQuery = 'INSERT INTO "sponsorTimes" ("videoID", "startTime", "endTime", "votes", "locked", "UUID", "userID", "timeSubmitted", "views", "category", "hidden", "shadowHidden") VALUES(?,?,?,?,?,?,?,?,?,?,?,?)'; await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-0-uuid-0", userHashLowSubmissions, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-0-uuid-1", userHashLowSubmissions, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 100, 0, "reputation-0-uuid-2", userHashLowSubmissions, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-1-uuid-0", userHashHighDownvotes, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -2, 0, "reputation-1-uuid-1", userHashHighDownvotes, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -2, 0, "reputation-1-uuid-2", userHashHighDownvotes, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -2, 0, "reputation-1-uuid-3", userHashHighDownvotes, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -2, 0, "reputation-1-uuid-4", userHashHighDownvotes, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-1-uuid-5", userHashHighDownvotes, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-uuid-6", userHashHighDownvotes, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-uuid-7", userHashHighDownvotes, 1606240000000, 50, "sponsor", 0, 0]); // First video is considered a normal downvote, second is considered a self-downvote (ie. they didn't resubmit to fix their downvote) await db.prepare("run", sponsorTimesInsertQuery, [`${videoID}A`, 1, 11, 2, 0, "reputation-1-1-uuid-0", userHashHighNonSelfDownvotes, 1606240000000, 50, "sponsor", 0, 0]); // Different category, same video await db.prepare("run", sponsorTimesInsertQuery, [`${videoID}A`, 1, 11, -2, 0, "reputation-1-1-uuid-1", userHashHighNonSelfDownvotes, 1606240000000, 50, "intro", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-1-uuid-2", userHashHighNonSelfDownvotes, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-1-uuid-3", userHashHighNonSelfDownvotes, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-1-uuid-4", userHashHighNonSelfDownvotes, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-1-1-uuid-5", userHashHighNonSelfDownvotes, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-1-uuid-6", userHashHighNonSelfDownvotes, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-1-1-uuid-7", userHashHighNonSelfDownvotes, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-2-uuid-0", userHashNewSubmissions, Date.now(), 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-2-uuid-1", userHashNewSubmissions, Date.now(), 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-2-uuid-2", userHashNewSubmissions, Date.now(), 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-2-uuid-3", userHashNewSubmissions, Date.now(), 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-2-uuid-4", userHashNewSubmissions, Date.now(), 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-2-uuid-5", userHashNewSubmissions, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-2-uuid-6", userHashNewSubmissions, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-2-uuid-7", userHashNewSubmissions, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-3-uuid-0", userHashLowSum, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 1, 0, "reputation-3-uuid-1", userHashLowSum, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-3-uuid-2", userHashLowSum, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-3-uuid-3", userHashLowSum, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 1, 0, "reputation-3-uuid-4", userHashLowSum, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-3-uuid-5", userHashLowSum, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-3-uuid-6", userHashLowSum, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-3-uuid-7", userHashLowSum, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-4-uuid-0", userHashHighRepBeforeManualVote, 0, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-4-uuid-1", userHashHighRepBeforeManualVote, 0, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-4-uuid-2", userHashHighRepBeforeManualVote, 0, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-4-uuid-3", userHashHighRepBeforeManualVote, 0, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-4-uuid-4", userHashHighRepBeforeManualVote, 0, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-4-uuid-5", userHashHighRepBeforeManualVote, 0, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-4-uuid-6", userHashHighRepBeforeManualVote, 0, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-4-uuid-7", userHashHighRepBeforeManualVote, 0, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-5-uuid-0", userHashHighRep, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-5-uuid-1", userHashHighRep, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-5-uuid-2", userHashHighRep, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-5-uuid-3", userHashHighRep, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-5-uuid-4", userHashHighRep, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-5-uuid-5", userHashHighRep, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-5-uuid-6", userHashHighRep, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-5-uuid-7", userHashHighRep, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 1, "reputation-6-uuid-0", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 1, "reputation-6-uuid-1", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 1, "reputation-6-uuid-2", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 1, "reputation-6-uuid-3", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-6-uuid-4", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-6-uuid-5", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-6-uuid-6", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-6-uuid-7", userHashHighAndLocked, 1606240000000, 50, "sponsor", 0, 0]); //Record has most upvoted await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 5, 0, "reputation-7-uuid-0", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 101, 0, "reputation-7-uuid-1", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "intro", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID2, 1, 11, 5, 0, "reputation-7-uuid-8", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID2, 1, 11, 0, 0, "reputation-7-uuid-9", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]); // other segments await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-7-uuid-2", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-7-uuid-3", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 2, 0, "reputation-7-uuid-4", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, -1, 0, "reputation-7-uuid-5", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-7-uuid-6", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]); await db.prepare("run", sponsorTimesInsertQuery, [videoID, 1, 11, 0, 0, "reputation-7-uuid-7", userHashHaveMostUpvotedInLockedVideo, 1606240000000, 50, "sponsor", 0, 0]); // lock video const insertVipUserQuery = 'INSERT INTO "vipUsers" ("userID") VALUES (?)'; await db.prepare("run", insertVipUserQuery, [getHash("VIPUser-getLockCategories")]); const insertLockCategoryQuery = 'INSERT INTO "lockCategories" ("userID", "videoID", "category") VALUES (?, ?, ?)'; await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), videoID, "sponsor"]); await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), videoID, "intro"]); await db.prepare("run", insertLockCategoryQuery, [getHash("VIPUser-getLockCategories"), videoID2, "sponsor"]); }); it("user in grace period", async () => { const data = await getReputation(getHash(userIDLowSubmissions)); assert.strictEqual(data, 0); }); it("user with high downvote ratio", async () => { const metrics = { totalSubmissions: 8, downvotedSubmissions: 5, nonSelfDownvotedSubmissions: 0, votedSum: -7, lockedSum: 0, semiOldUpvotedSubmissions: 1, oldUpvotedSubmissions: 1, mostUpvotedInLockedVideoSum: 0 }; const data = await getReputation(getHash(userIDHighDownvotes)); assert.strictEqual(data, calculateReputationFromMetrics(metrics)); assert.strictEqual(data, -2.125); }); it("user with high non self downvote ratio", async () => { const metrics = { totalSubmissions: 8, downvotedSubmissions: 2, nonSelfDownvotedSubmissions: 2, votedSum: -1, lockedSum: 0, semiOldUpvotedSubmissions: 1, oldUpvotedSubmissions: 1, mostUpvotedInLockedVideoSum: 0 }; const data = await getReputation(userHashHighNonSelfDownvotes); assert.strictEqual(data, calculateReputationFromMetrics(metrics)); assert.strictEqual(data, -1.6428571428571428); }); it("user with mostly new submissions", async () => { assert.strictEqual(await getReputation(userHashNewSubmissions), 0); }); it("user with not enough vote sum", async () => { assert.strictEqual(await getReputation(userHashLowSum), 0); }); it("user with lots of old votes (before autovote was disabled) ", async () => { assert.strictEqual(await getReputation(userHashHighRepBeforeManualVote), 0); }); it("user with high reputation", async () => { const metrics = { totalSubmissions: 8, downvotedSubmissions: 1, nonSelfDownvotedSubmissions: 0, votedSum: 9, lockedSum: 0, semiOldUpvotedSubmissions: 5, oldUpvotedSubmissions: 5, mostUpvotedInLockedVideoSum: 0 }; const data = await getReputation(userHashHighRep); assert.strictEqual(data, calculateReputationFromMetrics(metrics)); assert.strictEqual(data, 0.19310344827586207); }); it("user with high reputation and locked segments", async () => { const metrics = { totalSubmissions: 8, downvotedSubmissions: 1, nonSelfDownvotedSubmissions: 0, votedSum: 9, lockedSum: 4, semiOldUpvotedSubmissions: 5, oldUpvotedSubmissions: 5, mostUpvotedInLockedVideoSum: 0 }; const data = await getReputation(userHashHighAndLocked); assert.strictEqual(data, calculateReputationFromMetrics(metrics)); assert.strictEqual(data, 1.793103448275862); }); it("user with most upvoted segments in locked video", async () => { const metrics = { totalSubmissions: 10, downvotedSubmissions: 1, nonSelfDownvotedSubmissions: 0, votedSum: 116, lockedSum: 0, semiOldUpvotedSubmissions: 6, oldUpvotedSubmissions: 6, mostUpvotedInLockedVideoSum: 2 }; const data = await getReputation(userHashHaveMostUpvotedInLockedVideo); assert.strictEqual(data, calculateReputationFromMetrics(metrics)); assert.strictEqual(data, 6.158620689655172); }); });
the_stack
import { IConnector, IConnectorOpts, ICryptoLib, ITransportLib, ISessionStorage, IEncryptionPayload, ISocketMessage, ISessionStatus, ISessionError, IJsonRpcResponseSuccess, IJsonRpcResponseError, IJsonRpcRequest, ITxData, IClientMeta, IParseURIResult, ISessionParams, IUpdateChainParams, IRequestOptions, IInternalRequestOptions, ICreateSessionOptions, IQRCodeModal, IPushSubscription, IPushServerOptions, IWalletConnectSession, IQRCodeModalOptions, } from '@walletconnect/types' import { parsePersonalSign, parseTransactionData, convertArrayBufferToHex, convertHexToArrayBuffer, getClientMeta, payloadId, uuid, formatRpcError, parseWalletConnectUri, convertNumberToHex, isJsonRpcResponseSuccess, isJsonRpcResponseError, isSilentPayload, getLocal, signingMethods, mobileLinkChoiceKey, isMobile, removeLocal, } from '@walletconnect/utils' import { ERROR_SESSION_CONNECTED, ERROR_SESSION_DISCONNECTED, ERROR_SESSION_REJECTED, ERROR_MISSING_JSON_RPC, ERROR_MISSING_RESULT, ERROR_MISSING_ERROR, ERROR_MISSING_METHOD, ERROR_MISSING_ID, ERROR_INVALID_RESPONSE, ERROR_INVALID_URI, ERROR_MISSING_REQUIRED, ERROR_QRCODE_MODAL_NOT_PROVIDED, ERROR_QRCODE_MODAL_USER_CLOSED, } from '@walletconnect/core/dist/cjs/errors' import EventManager from '@walletconnect/core/dist/cjs/events' import SessionStorage from '@walletconnect/core/dist/cjs/storage' import CustomTransport from '../socket-transport' // -- Connector ------------------------------------------------------------ // class Connector implements IConnector { public readonly protocol = 'wc' public readonly version = 1 // -- connection ----------------------------------------------------- // private _bridge = '' private _key: ArrayBuffer | null = null // -- client ----------------------------------------------------- // private _clientId = '' private _clientMeta: IClientMeta | null = null // -- peer ----------------------------------------------------- // private _peerId = '' private _peerMeta: IClientMeta | null = null // -- handshake ----------------------------------------------------- // private _handshakeId = 0 private _handshakeTopic = '' // -- session ----------------------------------------------------- // private _connected = false private _accounts: string[] = [] private _chainId = 0 private _networkId = 0 private _rpcUrl = '' // -- controllers ----------------------------------------------------- // private _cryptoLib: ICryptoLib private _transport: ITransportLib private _eventManager: EventManager = new EventManager() private _sessionStorage: ISessionStorage | undefined // -- qrcodeModal ----------------------------------------------------- // private _qrcodeModal: IQRCodeModal | undefined private _qrcodeModalOptions: IQRCodeModalOptions | undefined // -- constructor ----------------------------------------------------- // constructor(opts: IConnectorOpts) { this._clientMeta = getClientMeta() || opts.connectorOpts.clientMeta || null this._cryptoLib = opts.cryptoLib this._sessionStorage = opts.sessionStorage || new SessionStorage() this._qrcodeModal = opts.connectorOpts.qrcodeModal this._qrcodeModalOptions = opts.connectorOpts.qrcodeModalOptions if ( !opts.connectorOpts.bridge && !opts.connectorOpts.uri && !opts.connectorOpts.session ) { throw new Error(ERROR_MISSING_REQUIRED) } if (opts.connectorOpts.bridge) { this.bridge = opts.connectorOpts.bridge } if (opts.connectorOpts.uri) { this.uri = opts.connectorOpts.uri } const session = opts.connectorOpts.session || this._getStorageSession() if (session) { this.session = session } if (this.handshakeId) { this._subscribeToSessionResponse( this.handshakeId, 'Session request rejected' ) } this._transport = new CustomTransport({ protocol: this.protocol, version: this.version, url: this.bridge, subscriptions: [this.clientId], }) this._subscribeToInternalEvents() this._initTransport() if (opts.connectorOpts.uri) { this._subscribeToSessionRequest() } if (opts.pushServerOpts) { this._registerPushServer(opts.pushServerOpts) } } // -- setters / getters ----------------------------------------------- // set bridge(value: string) { if (!value) { return } this._bridge = value } get bridge() { return this._bridge } set key(value: string) { if (!value) { return } const key: ArrayBuffer = convertHexToArrayBuffer(value) this._key = key } get key(): string { if (this._key) { const key: string = convertArrayBufferToHex(this._key, true) return key } return '' } set clientId(value: string) { if (!value) { return } this._clientId = value } get clientId() { let clientId: string | null = this._clientId if (!clientId) { clientId = this._clientId = uuid() } return this._clientId } set peerId(value) { if (!value) { return } this._peerId = value } get peerId() { return this._peerId } set clientMeta(value) { // empty } get clientMeta() { let clientMeta: IClientMeta | null = this._clientMeta if (!clientMeta) { clientMeta = this._clientMeta = getClientMeta() } return clientMeta } set peerMeta(value) { this._peerMeta = value } get peerMeta() { const peerMeta: IClientMeta | null = this._peerMeta return peerMeta } set handshakeTopic(value) { if (!value) { return } this._handshakeTopic = value } get handshakeTopic() { return this._handshakeTopic } set handshakeId(value) { if (!value) { return } this._handshakeId = value } get handshakeId() { return this._handshakeId } get uri() { const _uri = this._formatUri() return _uri } set uri(value) { if (!value) { return } const { handshakeTopic, bridge, key } = this._parseUri(value) this.handshakeTopic = handshakeTopic this.bridge = bridge this.key = key } set chainId(value) { this._chainId = value } get chainId() { const chainId: number | null = this._chainId return chainId } set networkId(value) { this._networkId = value } get networkId() { const networkId: number | null = this._networkId return networkId } set accounts(value) { this._accounts = value } get accounts() { const accounts: string[] | null = this._accounts return accounts } set rpcUrl(value) { this._rpcUrl = value } get rpcUrl() { const rpcUrl: string | null = this._rpcUrl return rpcUrl } set connected(value) { // empty } get connected() { return this._connected } set pending(value) { // empty } get pending() { return !!this._handshakeTopic } get session() { return { connected: this.connected, accounts: this.accounts, chainId: this.chainId, bridge: this.bridge, key: this.key, clientId: this.clientId, clientMeta: this.clientMeta, peerId: this.peerId, peerMeta: this.peerMeta, handshakeId: this.handshakeId, handshakeTopic: this.handshakeTopic, } } set session(value) { if (!value) { return } this._connected = value.connected this.accounts = value.accounts this.chainId = value.chainId this.bridge = value.bridge this.key = value.key this.clientId = value.clientId this.clientMeta = value.clientMeta this.peerId = value.peerId this.peerMeta = value.peerMeta this.handshakeId = value.handshakeId this.handshakeTopic = value.handshakeTopic } // -- public ---------------------------------------------------------- // public on( event: string, callback: (error: Error | null, payload: any | null) => void ): void { const eventEmitter = { event, callback, } this._eventManager.subscribe(eventEmitter) } public async createInstantRequest( instantRequest: Partial<IJsonRpcRequest> ): Promise<void> { this._key = await this._generateKey() const request: IJsonRpcRequest = this._formatRequest({ method: 'wc_instantRequest', params: [ { peerId: this.clientId, peerMeta: this.clientMeta, request: this._formatRequest(instantRequest), }, ], }) this.handshakeId = request.id this.handshakeTopic = uuid() this._eventManager.trigger({ event: 'display_uri', params: [this.uri], }) this.on('modal_closed', () => { throw new Error(ERROR_QRCODE_MODAL_USER_CLOSED) }) const endInstantRequest = () => { this.killSession() } try { const result = await this._sendCallRequest(request) if (result) { endInstantRequest() } return result } catch (error) { endInstantRequest() throw error } } public async connect(opts?: ICreateSessionOptions): Promise<ISessionStatus> { if (!this._qrcodeModal) { throw new Error(ERROR_QRCODE_MODAL_NOT_PROVIDED) } if (this.connected) { return { chainId: this.chainId, accounts: this.accounts, } } await this.createSession(opts) return new Promise<ISessionStatus>(async (resolve, reject) => { this.on('modal_closed', () => reject(new Error(ERROR_QRCODE_MODAL_USER_CLOSED)) ) this.on('connect', (error, payload) => { if (error) { return reject(error) } resolve(payload.params[0]) }) }) } public async createSession(opts?: ICreateSessionOptions): Promise<void> { if (this._connected) { throw new Error(ERROR_SESSION_CONNECTED) } if (this.pending) { return } this._key = await this._generateKey() const request: IJsonRpcRequest = this._formatRequest({ method: 'wc_sessionRequest', params: [ { peerId: this.clientId, peerMeta: this.clientMeta, chainId: opts && opts.chainId ? opts.chainId : null, }, ], }) this.handshakeId = request.id this.handshakeTopic = uuid() this._sendSessionRequest(request, 'Session update rejected', { topic: this.handshakeTopic, }) this._eventManager.trigger({ event: 'display_uri', params: [this.uri], }) } public approveSession(sessionStatus: ISessionStatus) { if (this._connected) { throw new Error(ERROR_SESSION_CONNECTED) } this.chainId = sessionStatus.chainId this.accounts = sessionStatus.accounts this.networkId = sessionStatus.networkId || 0 this.rpcUrl = sessionStatus.rpcUrl || '' const sessionParams: ISessionParams = { approved: true, chainId: this.chainId, networkId: this.networkId, accounts: this.accounts, rpcUrl: this.rpcUrl, peerId: this.clientId, peerMeta: this.clientMeta, } const response = { id: this.handshakeId, jsonrpc: '2.0', result: sessionParams, } this._sendResponse(response) this._connected = true this._setStorageSession() this._eventManager.trigger({ event: 'connect', params: [ { peerId: this.peerId, peerMeta: this.peerMeta, chainId: this.chainId, accounts: this.accounts, }, ], }) } public rejectSession(sessionError?: ISessionError) { if (this._connected) { throw new Error(ERROR_SESSION_CONNECTED) } const message = sessionError && sessionError.message ? sessionError.message : ERROR_SESSION_REJECTED const response = this._formatResponse({ id: this.handshakeId, error: { message }, }) this._sendResponse(response) this._connected = false this._eventManager.trigger({ event: 'disconnect', params: [{ message }], }) this._removeStorageSession() } public updateSession(sessionStatus: ISessionStatus) { if (!this._connected) { throw new Error(ERROR_SESSION_DISCONNECTED) } this.chainId = sessionStatus.chainId this.accounts = sessionStatus.accounts this.networkId = sessionStatus.networkId || 0 this.rpcUrl = sessionStatus.rpcUrl || '' const sessionParams: ISessionParams = { approved: true, chainId: this.chainId, networkId: this.networkId, accounts: this.accounts, rpcUrl: this.rpcUrl, } const request = this._formatRequest({ method: 'wc_sessionUpdate', params: [sessionParams], }) this._sendSessionRequest(request, 'Session update rejected') this._eventManager.trigger({ event: 'session_update', params: [ { chainId: this.chainId, accounts: this.accounts, }, ], }) this._manageStorageSession() } public async killSession(sessionError?: ISessionError) { const message = sessionError ? sessionError.message : 'Session Disconnected' const sessionParams: ISessionParams = { approved: false, chainId: null, networkId: null, accounts: null, } const request = this._formatRequest({ method: 'wc_sessionUpdate', params: [sessionParams], }) await this._sendRequest(request) this._handleSessionDisconnect(message) } public async sendTransaction(tx: ITxData) { if (!this._connected) { throw new Error(ERROR_SESSION_DISCONNECTED) } const parsedTx = parseTransactionData(tx) const request = this._formatRequest({ method: 'eth_sendTransaction', params: [parsedTx], }) const result = await this._sendCallRequest(request) return result } public async signTransaction(tx: ITxData) { if (!this._connected) { throw new Error(ERROR_SESSION_DISCONNECTED) } const parsedTx = parseTransactionData(tx) const request = this._formatRequest({ method: 'eth_signTransaction', params: [parsedTx], }) const result = await this._sendCallRequest(request) return result } public async signMessage(params: any[]) { if (!this._connected) { throw new Error(ERROR_SESSION_DISCONNECTED) } const request = this._formatRequest({ method: 'eth_sign', params, }) const result = await this._sendCallRequest(request) return result } public async signPersonalMessage(params: any[]) { if (!this._connected) { throw new Error(ERROR_SESSION_DISCONNECTED) } params = parsePersonalSign(params) const request = this._formatRequest({ method: 'personal_sign', params, }) const result = await this._sendCallRequest(request) return result } public async signTypedData(params: any[]) { if (!this._connected) { throw new Error(ERROR_SESSION_DISCONNECTED) } const request = this._formatRequest({ method: 'eth_signTypedData', params, }) const result = await this._sendCallRequest(request) return result } public async updateChain(chainParams: IUpdateChainParams) { if (!this._connected) { throw new Error('Session currently disconnected') } const request = this._formatRequest({ method: 'wallet_updateChain', params: [chainParams], }) const result = await this._sendCallRequest(request) return result } public unsafeSend( request: IJsonRpcRequest, options?: IRequestOptions ): Promise<IJsonRpcResponseSuccess | IJsonRpcResponseError> { this._sendRequest(request, options) return new Promise((resolve, reject) => { this._subscribeToResponse( request.id, (error: Error | null, payload: any | null) => { if (error) { reject(error) return } if (!payload) { throw new Error(ERROR_MISSING_JSON_RPC) } resolve(payload) } ) }) } public async sendCustomRequest( request: Partial<IJsonRpcRequest>, options?: IRequestOptions ) { if (!this._connected) { throw new Error(ERROR_SESSION_DISCONNECTED) } switch (request.method) { case 'eth_accounts': return this.accounts case 'eth_chainId': return convertNumberToHex(this.chainId) case 'eth_sendTransaction': case 'eth_signTransaction': if (request.params) { request.params[0] = parseTransactionData(request.params[0]) } break case 'personal_sign': if (request.params) { request.params = parsePersonalSign(request.params) } break default: break } const formattedRequest = this._formatRequest(request) const result = await this._sendCallRequest(formattedRequest, options) return result } public approveRequest(response: Partial<IJsonRpcResponseSuccess>) { if (isJsonRpcResponseSuccess(response)) { const formattedResponse = this._formatResponse(response) this._sendResponse(formattedResponse) } else { throw new Error(ERROR_MISSING_RESULT) } } public rejectRequest(response: Partial<IJsonRpcResponseError>) { if (isJsonRpcResponseError(response)) { const formattedResponse = this._formatResponse(response) this._sendResponse(formattedResponse) } else { throw new Error(ERROR_MISSING_ERROR) } } // -- private --------------------------------------------------------- // protected async _sendRequest( request: Partial<IJsonRpcRequest>, options?: Partial<IInternalRequestOptions> ) { const callRequest: IJsonRpcRequest = this._formatRequest(request) const encryptionPayload: IEncryptionPayload | null = await this._encrypt( callRequest ) const topic: string = typeof options?.topic !== 'undefined' ? options.topic : this.peerId const payload: string = JSON.stringify(encryptionPayload) const silent = typeof options?.forcePushNotification !== 'undefined' ? !options.forcePushNotification : isSilentPayload(callRequest) this._transport.send(payload, topic, silent) } protected async _sendResponse( response: IJsonRpcResponseSuccess | IJsonRpcResponseError ) { const encryptionPayload: IEncryptionPayload | null = await this._encrypt( response ) const topic: string = this.peerId const payload: string = JSON.stringify(encryptionPayload) const silent = true this._transport.send(payload, topic, silent) } protected async _sendSessionRequest( request: IJsonRpcRequest, errorMsg: string, options?: IInternalRequestOptions ) { this._sendRequest(request, options) this._subscribeToSessionResponse(request.id, errorMsg) } protected _sendCallRequest( request: IJsonRpcRequest, options?: IRequestOptions ): Promise<any> { this._sendRequest(request, options) this._eventManager.trigger({ event: 'call_request_sent', params: [{ request, options }], }) if (isMobile() && signingMethods.includes(request.method)) { const mobileLinkUrl = getLocal(mobileLinkChoiceKey) if (mobileLinkUrl) { window.location.href = mobileLinkUrl.href } } return this._subscribeToCallResponse(request.id) } protected _formatRequest(request: Partial<IJsonRpcRequest>): IJsonRpcRequest { if (typeof request.method === 'undefined') { throw new Error(ERROR_MISSING_METHOD) } const formattedRequest: IJsonRpcRequest = { id: typeof request.id === 'undefined' ? payloadId() : request.id, jsonrpc: '2.0', method: request.method, params: typeof request.params === 'undefined' ? [] : request.params, } return formattedRequest } protected _formatResponse( response: Partial<IJsonRpcResponseSuccess | IJsonRpcResponseError> ): IJsonRpcResponseSuccess | IJsonRpcResponseError { if (typeof response.id === 'undefined') { throw new Error(ERROR_MISSING_ID) } const baseResponse = { id: response.id, jsonrpc: '2.0' } if (isJsonRpcResponseError(response)) { const error = formatRpcError(response.error) const errorResponse: IJsonRpcResponseError = { ...baseResponse, ...response, error, } return errorResponse } else if (isJsonRpcResponseSuccess(response)) { const successResponse: IJsonRpcResponseSuccess = { ...baseResponse, ...response, } return successResponse } throw new Error(ERROR_INVALID_RESPONSE) } private _handleSessionDisconnect(errorMsg?: string) { const message = errorMsg || 'Session Disconnected' if (!this._connected) { if (this._qrcodeModal) { this._qrcodeModal.close() } removeLocal(mobileLinkChoiceKey) } if (this._connected) { this._connected = false } if (this._handshakeId) { this._handshakeId = 0 } if (this._handshakeTopic) { this._handshakeTopic = '' } this._eventManager.trigger({ event: 'disconnect', params: [{ message }], }) this._removeStorageSession() this._transport.close() } private _handleSessionResponse( errorMsg: string, sessionParams?: ISessionParams ) { if (sessionParams) { if (sessionParams.approved) { if (!this._connected) { this._connected = true if (sessionParams.chainId) { this.chainId = sessionParams.chainId } if (sessionParams.accounts) { this.accounts = sessionParams.accounts } if (sessionParams.peerId && !this.peerId) { this.peerId = sessionParams.peerId } if (sessionParams.peerMeta && !this.peerMeta) { this.peerMeta = sessionParams.peerMeta } this._eventManager.trigger({ event: 'connect', params: [ { peerId: this.peerId, peerMeta: this.peerMeta, chainId: this.chainId, accounts: this.accounts, }, ], }) } else { if (sessionParams.chainId) { this.chainId = sessionParams.chainId } if (sessionParams.accounts) { this.accounts = sessionParams.accounts } this._eventManager.trigger({ event: 'session_update', params: [ { chainId: this.chainId, accounts: this.accounts, }, ], }) } this._manageStorageSession() } else { this._handleSessionDisconnect(errorMsg) } } else { this._handleSessionDisconnect(errorMsg) } } private async _handleIncomingMessages(socketMessage: ISocketMessage) { const activeTopics = [this.clientId, this.handshakeTopic] if (!activeTopics.includes(socketMessage.topic)) { return } let encryptionPayload: IEncryptionPayload try { encryptionPayload = JSON.parse(socketMessage.payload) } catch (error) { return } const payload: | IJsonRpcRequest | IJsonRpcResponseSuccess | IJsonRpcResponseError | null = await this._decrypt(encryptionPayload) if (payload) { this._eventManager.trigger(payload) } } private _subscribeToSessionRequest() { this._transport.subscribe(this.handshakeTopic) } private _subscribeToResponse( id: number, callback: (error: Error | null, payload: any | null) => void ) { this.on(`response:${id}`, callback) } private _subscribeToSessionResponse(id: number, errorMsg: string) { this._subscribeToResponse(id, (error, payload) => { if (error) { this._handleSessionResponse(error.message) return } if (payload.result) { this._handleSessionResponse(errorMsg, payload.result) } else if (payload.error && payload.error.message) { this._handleSessionResponse(payload.error.message) } else { this._handleSessionResponse(errorMsg) } }) } private _subscribeToCallResponse(id: number): Promise<any> { return new Promise((resolve, reject) => { this._subscribeToResponse(id, (error, payload) => { if (error) { reject(error) return } if (payload.result) { resolve(payload.result) } else if (payload.error && payload.error.message) { reject(new Error(payload.error.message)) } else { reject(new Error(ERROR_INVALID_RESPONSE)) } }) }) } private _subscribeToInternalEvents() { this.on('display_uri', () => { if (this._qrcodeModal) { this._qrcodeModal.open( this.uri, () => { this._eventManager.trigger({ event: 'modal_closed', params: [], }) }, this._qrcodeModalOptions ) } }) this.on('connect', () => { if (this._qrcodeModal) { this._qrcodeModal.close() } }) this.on('wc_sessionRequest', (error, payload) => { if (error) { this._eventManager.trigger({ event: 'error', params: [ { code: 'SESSION_REQUEST_ERROR', message: error.toString(), }, ], }) } this.handshakeId = payload.id this.peerId = payload.params[0].peerId this.peerMeta = payload.params[0].peerMeta const internalPayload = { ...payload, method: 'session_request', } this._eventManager.trigger(internalPayload) }) this.on('wc_sessionUpdate', (error, payload) => { if (error) { this._handleSessionResponse(error.message) } this._handleSessionResponse('Session disconnected', payload.params[0]) }) } private _initTransport() { this._transport.on('message', (socketMessage: ISocketMessage) => this._handleIncomingMessages(socketMessage) ) this._transport.on('open', () => this._eventManager.trigger({ event: 'transport_open', params: [] }) ) this._transport.on('close', () => this._eventManager.trigger({ event: 'transport_close', params: [] }) ) this._transport.on('error', () => this._eventManager.trigger({ event: 'transport_error', params: ['Websocket connection failed'], }) ) this._transport.open() } // -- uri ------------------------------------------------------------- // private _formatUri() { const protocol = this.protocol const handshakeTopic = this.handshakeTopic const version = this.version const bridge = encodeURIComponent(this.bridge) const key = this.key const uri = `${protocol}:${handshakeTopic}@${version}?bridge=${bridge}&key=${key}` return uri } private _parseUri(uri: string) { const result: IParseURIResult = parseWalletConnectUri(uri) if (result.protocol === this.protocol) { if (!result.handshakeTopic) { throw Error('Invalid or missing handshakeTopic parameter value') } const handshakeTopic = result.handshakeTopic if (!result.bridge) { throw Error('Invalid or missing bridge url parameter value') } const bridge = decodeURIComponent(result.bridge) if (!result.key) { throw Error('Invalid or missing key parameter value') } const key = result.key return { handshakeTopic, bridge, key } } else { throw new Error(ERROR_INVALID_URI) } } // -- crypto ---------------------------------------------------------- // private async _generateKey(): Promise<ArrayBuffer | null> { if (this._cryptoLib) { const result = await this._cryptoLib.generateKey() return result } return null } private async _encrypt( data: IJsonRpcRequest | IJsonRpcResponseSuccess | IJsonRpcResponseError ): Promise<IEncryptionPayload | null> { const key: ArrayBuffer | null = this._key if (this._cryptoLib && key) { const result: IEncryptionPayload = await this._cryptoLib.encrypt( data, key ) return result } return null } private async _decrypt( payload: IEncryptionPayload ): Promise< IJsonRpcRequest | IJsonRpcResponseSuccess | IJsonRpcResponseError | null > { const key: ArrayBuffer | null = this._key if (this._cryptoLib && key) { const result: | IJsonRpcRequest | IJsonRpcResponseSuccess | IJsonRpcResponseError | null = await this._cryptoLib.decrypt(payload, key) return result } return null } // -- sessionStorage --------------------------------------------------------- // private _getStorageSession() { let result: IWalletConnectSession | null = null if (this._sessionStorage) { result = this._sessionStorage.getSession() } return result } private _setStorageSession() { if (this._sessionStorage) { this._sessionStorage.setSession(this.session) } } private _removeStorageSession() { if (this._sessionStorage) { this._sessionStorage.removeSession() } } private _manageStorageSession() { if (this._connected) { this._setStorageSession() } else { this._removeStorageSession() } } // -- pushServer ------------------------------------------------------------- // private _registerPushServer(pushServerOpts: IPushServerOptions) { if (!pushServerOpts.url || typeof pushServerOpts.url !== 'string') { throw Error('Invalid or missing pushServerOpts.url parameter value') } if (!pushServerOpts.type || typeof pushServerOpts.type !== 'string') { throw Error('Invalid or missing pushServerOpts.type parameter value') } if (!pushServerOpts.token || typeof pushServerOpts.token !== 'string') { throw Error('Invalid or missing pushServerOpts.token parameter value') } const pushSubscription: IPushSubscription = { bridge: this.bridge, topic: this.clientId, type: pushServerOpts.type, token: pushServerOpts.token, peerName: '', language: pushServerOpts.language || '', } this.on('connect', async (error: Error | null, payload: any) => { if (error) { throw error } if (pushServerOpts.peerMeta) { const peerName = payload.params[0].peerMeta.name pushSubscription.peerName = peerName } try { const response = await fetch(`${pushServerOpts.url}/new`, { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(pushSubscription), }) const json = await response.json() if (!json.success) { throw Error('Failed to register in Push Server') } } catch (error) { throw Error('Failed to register in Push Server') } }) } } export default Connector
the_stack
import { Address, DomOperation, Operation } from '@stencila/stencila' import { collab, receiveTransaction, sendableSteps } from 'prosemirror-collab' import { baseKeymap } from 'prosemirror-commands' import { dropCursor } from 'prosemirror-dropcursor' import { gapCursor } from 'prosemirror-gapcursor' import { history } from 'prosemirror-history' import { keymap } from 'prosemirror-keymap' import { DOMParser, Mark, Node, ResolvedPos, Slice } from 'prosemirror-model' import { EditorState, Transaction } from 'prosemirror-state' import { ReplaceStep, Step } from 'prosemirror-transform' import { EditorView } from 'prosemirror-view' import { isNumber, JsonValue } from '../../../patches/checks' import { applyPatch, diff } from '../../../patches/json' import { stencilaElement, StencilaElement } from '../../base' import { prosemirrorToStencila } from './convert' import { articleInputRules } from './inputRules' import { articleKeymap } from './keymap' import { articleSchema } from './schema' // Import ProseMirror's `EditorView` styles for correct whitespace handling etc import 'prosemirror-view/style/prosemirror.css' // The following interfaces were necessary because the way they are defined // in @types/prosemirror-transform (as classes with only constructors) does // not seem to permit typed access to properties interface ReplaceStepInterface extends Step { from: number to: number slice: Slice structure?: boolean } interface _ReplaceAroundStepInterface extends Step { from: number to: number gapFrom: number gapTo: number slice: Slice insert: number structure?: boolean } interface _AddMarkStepInterface extends Step { from: number to: number mark: Mark } interface _RemoveMarkStepInterface extends Step { from: number to: number mark: Mark } export class Article extends StencilaElement { initialized = false version = 0 doc?: Node root?: JsonValue view?: EditorView static hydrate(): void { StencilaElement.hydrate(this, 'http://schema.org/Article') } /** * Initialize the custom element by parsing the `<article>` in the `<slot>`, * rendering the editor as a child of this element, and hiding (or removing) * the original `<article>` element. */ initialize(): void { // Avoid recursion triggered by slotchange event if (this.initialized) return this.initialized = true // Get the source <article> element and hide it const sourceElem = this.getSlot(0) sourceElem.style.display = 'none' // Parse the source into a document and hold onto it // so that we can use it to map reconcile and map operations const parser = DOMParser.fromSchema(articleSchema) this.doc = parser.parse(sourceElem) this.root = prosemirrorToStencila(this.doc) // Create the editor state const state = EditorState.create({ schema: articleSchema, doc: this.doc, plugins: [ // Locally defined input rules and keymap articleInputRules, keymap(articleKeymap), // Plugin that enables undo and redo history(), // Plugin for collaboration that talks to the store collab({ version: this.version }), // The `baseKeymap` contains "bindings not specific to any schema" e.g. // `Enter` (to split paragraphs, add a newline to a code blocks), // `Mod-Enter` (to exit code block), `Backspace`, `Delete` etc etc. // These can be overridden above. keymap(baseKeymap), // Plugin that "causes a decoration to show up at the drop position when something is dragged over the editor" dropCursor({ class: 'drop-cursor' }), // Plugin that provides "a block-level cursor that can be used to focus places that don't allow regular selection" gapCursor(), ], }) // Create the editor <article> element const editorElem = document.createElement('article') editorElem.setAttribute('data-itemscope', 'root') editorElem.setAttribute('itemtype', 'http://schema.org/Article') editorElem.setAttribute('itemscope', '') this.appendChild(editorElem) // Render the editor view // eslint-disable-next-line @typescript-eslint/no-this-alias const me = this const view = new EditorView(editorElem, { state, dispatchTransaction(transaction) { // Send any new state to the view and the store const newState = view.state.apply(transaction) view.updateState(newState) me.receiveState(newState) }, }) // Hold on to the view so that transactions can be dispatched to it this.view = view } /** * Receive a new ProseMirror `EditorState` and send a `Patch` to the server. * * Obtains any new document `Step`s associated with the new state, * applies them to `this.doc`, transforms each into one or * more `Operation`s, and sends them as a `Patch` to the server. */ receiveState(newState: EditorState): void { if (this.doc === undefined) throw new Error('The `doc` has not been initialized') if (this.root === undefined) throw new Error('The `root` has not been initialized') // Get any new steps const sendable = sendableSteps(newState) if (!sendable) return const { version, steps, clientID } = sendable // TODO: instead of ignoring this, is some sort of reset required if (version !== this.version) return // Each step is converted to an operation, which is then applied to `this.root`, // and the step is applied to the ProseMirror document const ops: Operation[] = [] for (const step of steps) { // Attempt to generate an operation from the step // TODO: enable this call when stepToOperation is fixed const op = undefined // this.stepToOperation(step) // Apply the step this `this.doc` so it is up to date and // so that positions in the step can be correctly resolved to addresses. const { failed, doc } = step.apply(this.doc) if (typeof failed === 'string') { console.error(failed) } else if (doc) { this.doc = doc } // If necessary, generate operations from the change in the `this.root`, // otherwise apply the operation so that `this.root` stays up to date if (op === undefined) { console.debug('⚠️ Generating patch from diff') // TODO: do diff on the smallest part of the doc possible e.g a single paragraph const newRoot = prosemirrorToStencila(this.doc) const patch = diff(this.root, newRoot) ops.push(...patch.ops) this.root = newRoot } else { ops.push(op) try { applyPatch(this.root, { ops: ops.map((op): DomOperation => { // @ts-expect-error because this is a temporary until we unify Operation and DomOperation // eslint-disable-next-line return { ...op, json: op.value } }), }) } catch (error) { // There was an error applying the patch so recover by setting root to // the current state of the document console.error(error) this.root = prosemirrorToStencila(this.doc) } } } this.sendPatch({ ops }) this.version = this.version + steps.length // Notify the editor of the new steps and the client ids that // are associated with them. Even though the steps came from the same // client, the editor, this is necessary to "flush" the sendable steps and increment // the version in the editor. if (!this.view) throw new Error('Article `view` was not initialized') this.view.dispatch( receiveTransaction( this.view.state, steps, steps.map(() => clientID) ) ) } /** * Receive a Stencila `Operation` from the server. * * Transforms each `Operation` into a ProseMirror `Step` and sends them to the editor. */ receiveOperation(_op: DomOperation): boolean { // Pretends to handle the operation, so that some other handler // does not modify the ProseMirror managed DOM console.warn('TODO: Incoming patch operations are not currently handled') return true } /** * Convert a ProseMirror transaction `Step` to a Stencila patch `Operation`. * * Return `undefined` if the conversion has not been implemented yet, in which * case diff-based operations will be created. */ stepToOperation(step: Step): Operation | undefined { if (!this.doc) throw new Error('The `doc` has not been initialized') if (step.constructor === ReplaceStep) { const { from, to, slice } = step as ReplaceStepInterface if (slice.size !== 0) { // Slice has content, so adding or replacing const { content, openStart, openEnd } = slice if (openStart === 0 && openEnd === 0) { // Adding text e.g. a keypress or pasting if (content.childCount === 1 && content.child(0).isText) { const position = this.doc.resolve(from) const address = this.offsetToAddress(position) if (address === undefined) return const value = content.child(0).textContent const length = value.length if (from === to) { if (position.parent.childCount === 0) { // The parent does not have any children yet, so add the value as the // first child of the parent return { type: 'Add', address: address.slice(0, -1), value: [value], length, } } else { // Add the text to the existing text node return { type: 'Add', address, value, length, } } } else { return { type: 'Replace', address, items: to - from, value, length, } } } else { console.log('Unexpected content') } } } else { // Slice is empty, so removing something. // If the parent node (e.g. a Paragraph) is the same for the `to` and `from` // positions then do the remove with the items calculated form the addresses const fromPos = this.doc.resolve(from) const toPos = this.doc.resolve(to) if (fromPos.parent === toPos.parent) { const address = this.offsetToAddress(fromPos) if (address === undefined) return const toAddress = this.offsetToAddress(toPos) if (toAddress === undefined) return const lastFrom = address[address.length - 1] const lastTo = toAddress[toAddress.length - 1] if (!(isNumber(lastFrom) && isNumber(lastTo))) return const items = lastTo - lastFrom if (items > 0) { return { type: 'Remove', address, items, } } } } } } /** * Convert a Stencila document operation to a ProseMirror document transaction */ operationToStep(op: DomOperation): Transaction { if (!this.doc) throw new Error('The `doc` has not been initialized') const transaction = new Transaction(this.doc) switch (op.type) { case 'Add': { const { address } = op return transaction.insert(this.addressToOffset(address), []) } default: { // TODO: All the other operation types return transaction } } } /** * Convert a ProseMirror `ResolvedPos` into a Stencila document address. * * For relevant ProseMirror documentation see: * - https://prosemirror.net/docs/guide/#doc.indexing * - https://prosemirror.net/docs/ref/#model.Resolved_Positions */ offsetToAddress(position: ResolvedPos): Address | undefined { // Check that there are no ProseMirror nodes before this one in the parent // node that have multiple marks as that will invalidate the address // This may be able to be dealt with; rather than throwing a wobbly like this for (let index = 0; index < position.index(position.depth); index++) { if (position.parent.content.child(index).marks.length > 1) { return } } let textOffset = position.textOffset // For each depth level that the position is in the node tree // calculate the Stencila slot(s) to add to the address const address: Address = [] for (let depth = 1; depth <= position.depth; depth++) { const ancestor = position.node(depth) let index = position.index(depth) // This seems to be necessary for when characters are being added to the // end of a paragraph if ( ancestor.content.childCount > 0 && index >= ancestor.content.childCount ) { index = ancestor.content.childCount - 1 textOffset = ancestor.child(index).nodeSize } if (depth === 1) { // At this depth, the ancestor should be one of the article attributes // e.g. `content`, `title`, `abstract` address.push(ancestor.type.name) address.push(index) } else { // At other depths, the ancestor will have a `contentProp` (defaulting to 'content') // that the index points to address.push(ancestor.type.spec.contentProp ?? 'content') address.push(index) } } // If there are marks on this node then we need to add to the address const marks = position.marks() if (marks.length === 1) { address.push('content') address.push(0) } else if (marks.length > 1) { // Currently unable to determine address if more than one mark return } address.push(textOffset) return address } /** * Convert a Stencila document address to a ProseMirror document offset. */ addressToOffset(_address: Address): number { // TODO calculate offsets return 0 } } stencilaElement('stencila-article')(Article)
the_stack
import type { Nullable } from "@thi.ng/api"; import { isArray } from "@thi.ng/checks/is-array"; import { isFunction } from "@thi.ng/checks/is-function"; import { isIterable } from "@thi.ng/checks/is-iterable"; import { ESCAPES } from "@thi.ng/strings/escape"; import { split } from "@thi.ng/strings/split"; import type { Reducer, Transducer } from "@thi.ng/transducers"; import { compR } from "@thi.ng/transducers/compr"; import { iterator1 } from "@thi.ng/transducers/iterator"; import type { ColumnSpec, CommonCSVOpts, CSVOpts, CSVRecord, CSVRow, SimpleCSVOpts, } from "./api.js"; /** @internal */ type IndexEntry = { i: number; spec: ColumnSpec }; /** * Default parser options. * * @internal */ const DEFAULT_OPTS: Partial<CommonCSVOpts> = { delim: ",", quote: '"', comment: "#", trim: false, }; /** * Configurable CSV parsing transducer, operating on line-based string iterables * and yielding tuple objects of CSV row records. If called with input, returns * ES6 iterator instead. * * @remarks * Parsing behavior can be customized via given {@link CSVOpts}. The default * behavior is: * * - comma delimiter * - field names are obtained from first line/row * - all columns are processed, but no coercions * - untrimmed cell values * - line comment prefix `#` * * Using the `cols` option, specific columns can be renamed and their values * coerced/transformed. Additionally, if `all` option is `false`, then the * result objects will only contain values of the columns specified in `cols`. * * Also see: * - thi.ng/transducers * - {@link CSVOpts} * - {@link parseCSVFromString}. * * @example * ```ts * import { parseCSV, upper, float } from "@thi.ng/csv"; * * [...parseCSV( * { * all: false, * cols: { * "country": { tx: upper }, * "latitude": { alias: "lat", tx: float() }, * "longitude": { alias: "lon", tx: float() }, * } * }, * [ * `"country","country group","name (en)","latitude","longitude"`, * `"at","eu","Austria","47.6965545","13.34598005"`, * `"be","eu","Belgium","50.501045","4.47667405"`, * `"bg","eu","Bulgaria","42.72567375","25.4823218"`, * ] * )] * * // [ * // { country: 'AT', lat: 47.6965545, lon: 13.34598005 }, * // { country: 'BE', lat: 50.501045, lon: 4.47667405 }, * // { country: 'BG', lat: 42.72567375, lon: 25.4823218 } * // ] * ``` * * @param opts */ export function parseCSV( opts?: Partial<CSVOpts> ): Transducer<string, CSVRecord>; export function parseCSV( opts: Partial<CSVOpts>, src: Iterable<string> ): IterableIterator<CSVRecord>; export function parseCSV(opts?: Partial<CSVOpts>, src?: Iterable<string>): any { return isIterable(src) ? iterator1(parseCSV(opts), src) : (rfn: Reducer<any, CSVRecord>) => { const { all, cols, delim, quote, comment, trim, header } = { all: true, ...DEFAULT_OPTS, ...opts, }; const reduce = rfn[2]; let index: Record<string, IndexEntry>; let revIndex: Record<number, string>; let first = true; let isQuoted = false; let record: string[] = []; const init = (header: string[]) => { cols && (index = initIndex(header, cols)); all && (revIndex = initRevIndex(header)); first = false; }; const collectAll = (row: CSVRecord) => record.reduce( (acc, x, i) => ( (acc[revIndex[i]] = trim ? x.trim() : x), acc ), row ); const collectIndexed = (row: CSVRecord) => Object.entries(index).reduce((acc, [id, { i, spec }]) => { let val = record[i]; if (val !== undefined) { trim && (val = val.trim()); all && spec.alias && delete acc[id]; acc[spec.alias || id] = spec.tx ? spec.tx(val, acc) : val; } return acc; }, row); header && init(header); return compR(rfn, (acc, line: string) => { if ((!line.length || line.startsWith(comment!)) && !isQuoted) return acc; if (!first) { isQuoted = parseLine( line, record, isQuoted, delim!, quote! ); if (isQuoted) return acc; const row: CSVRecord = {}; all && collectAll(row); index && collectIndexed(row); record = []; return reduce(acc, row); } else { isQuoted = parseLine( line, record, isQuoted, delim!, quote! ); if (!isQuoted) { init(record); record = []; } return acc; } }); }; } /** * Simplified version of {@link parseCSV} for use cases when no object mapping * is desired/required. Here, each CSV row will be emitted as simple array, * optionally with only filtered or transformed columns. * * @remarks * See {@link SimpleCSVOpts} for available options. Defaults are similar to * those used by {@link parseCSV}. * * @example * ```ts * [...parseCSVSimple({ cols: [float(), ,float()]}, ["a,b,c","1,2,3","4,5,6"])] * // [ [ 1, 3 ], [ 4, 6 ] ] * ``` * * @param opts */ export function parseCSVSimple( opts?: Partial<SimpleCSVOpts> ): Transducer<string, CSVRow>; export function parseCSVSimple( opts: Partial<SimpleCSVOpts>, src: Iterable<string> ): IterableIterator<CSVRow>; export function parseCSVSimple( opts?: Partial<SimpleCSVOpts>, src?: Iterable<string> ): any { return isIterable(src) ? iterator1(parseCSVSimple(opts), src) : (rfn: Reducer<any, CSVRecord>) => { const { cols, delim, quote, comment, trim, header } = { header: true, ...DEFAULT_OPTS, ...opts, }; const reduce = rfn[2]; let first = header; let isQuoted = false; let record: string[] = []; const collect = () => cols!.reduce((acc, col, i) => { if (col) { let val = record[i]; if (val !== undefined) { trim && (val = val.trim()); acc.push(isFunction(col) ? col(val, acc) : val); } } return acc; }, <CSVRow>[]); return compR(rfn, (acc, line: string) => { if ((!line.length || line.startsWith(comment!)) && !isQuoted) return acc; if (!first) { isQuoted = parseLine( line, record, isQuoted, delim!, quote! ); if (isQuoted) return acc; const row: CSVRow = cols ? collect() : record; record = []; return reduce(acc, row); } else { isQuoted = parseLine( line, record, isQuoted, delim!, quote! ); first = false; record = []; return acc; } }); }; } /** * Syntax sugar for iterator version of {@link parseCSV}, efficiently splitting * given source string into a line based input using * {@link @thi.ng/strings#split}. * * @param opts * @param src */ export const parseCSVFromString = (opts: Partial<CSVOpts>, src: string) => parseCSV(opts, split(src)); /** * Syntax sugar for iterator version of {@link parseCSVSimple}, efficiently * splitting given source string into a line based input using * {@link @thi.ng/strings#split}. * * @param opts * @param src */ export const parseCSVSimpleFromString = ( opts: Partial<SimpleCSVOpts>, src: string ) => parseCSVSimple(opts, split(src)); /** * Parses line into `acc`, taking quoted cell values and linebreaks into * account. * * @remarks * If `isQuoted` is true, the previous line ended with a quoted cell value, * which might only end in the new or a future line. If that's the case, then * the current line's contents will be added to the current last value of `acc` * until the quoted cell is complete. * * Function returns current state of `isQuoted` (i.e. if line terminated in a * quoted cell) and should be (re)called with new lines until it returns false. * * @param line * @param acc * @param isQuoted * @param delim * @param quote */ const parseLine = ( line: string, acc: string[], isQuoted: boolean, delim: string, quote: string ) => { let curr = ""; let p = ""; let openQuote = isQuoted; for (let i = 0, n = line.length; i < n; i++) { const c = line[i]; // escaped char if (p === "\\") { curr += ESCAPES[c] || c; } // quote open/close & CSV escape pair (aka `""`) else if (c === quote) { if (!isQuoted) { p = ""; isQuoted = true; continue; } else if (p === quote) { curr += quote; p = ""; continue; } else if (line[i + 1] !== quote) isQuoted = false; } // field delimiter else if (!isQuoted && c === delim) { collectCell(acc, curr, openQuote); openQuote = false; curr = ""; } // record unless escape seq start else if (c !== "\\") { curr += c; } p = c; } curr !== "" && collectCell(acc, curr, openQuote); return isQuoted; }; const collectCell = (acc: string[], curr: string, openQuote: boolean) => openQuote ? (acc[acc.length - 1] += "\n" + curr) : acc.push(curr); const initIndex = ( line: string[], cols: Nullable<ColumnSpec>[] | Record<string, ColumnSpec> ) => isArray(cols) ? cols.reduce((acc, spec, i) => { if (spec) { const alias = spec.alias || line[i] || String(i); acc[alias] = { i, spec: { alias, ...spec } }; } return acc; }, <Record<string, IndexEntry>>{}) : line.reduce( (acc, id, i) => cols![id] ? ((acc[id] = { i, spec: cols![id] }), acc) : acc, <Record<string, IndexEntry>>{} ); const initRevIndex = (line: string[]) => line.reduce((acc, x, i) => ((acc[i] = x), acc), <Record<number, string>>{});
the_stack
import express from 'express'; import * as bodyParser from 'body-parser'; import { Server } from 'http'; let server: Server; // holds server object for shutdown /** * Starts the server at the given port */ export function startServer(PORT: number) { const app = express(); app.use(bodyParser.text()); app.use(bodyParser.json()); const Users = { arlene: { name: 'Arlene L McMahon', address: { street: '4656 Cherry Camp Road', city: 'Elk Grove Village', }, address2: { street: '3180 Little Acres Lane', city: 'Macomb', }, employerId: 'binsol', hobbies: ['tap dancing', 'bowling'], status: 'staff', nomenclature: { suborder: 'Haplorhini', family: 'Hominidae', genus: 'Homo', species: 'sapiens', }, friends: ['will', 'johnny', 'heather'], }, will: { name: 'William B Ropp', address: { street: '3180 Little Acres Lane', city: 'Macomb', }, employerId: 'binsol', hobbies: ['tap dancing', 'baseball'], status: 'staff', nomenclature: { suborder: 'Haplorhini', family: 'Hominidae', genus: 'Homo', species: 'sapiens', }, friends: ['arlene', 'johnny'], }, johnny: { name: 'John C Barnes', address: { street: '372 Elk Rd Little', city: 'Tucson', }, employerId: 'binsol', hobbies: ['chess', 'tennis'], status: 'staff', nomenclature: { suborder: 'Haplorhini', family: 'Hominidae', genus: 'Homo', species: 'sapiens', }, friends: ['arlene'], }, heather: { name: 'Heather J Tate', address: { street: '3636 Poplar Chase Lane', city: 'Post Falls', }, employerId: 'ccc', hobbies: ['making money', 'counting money'], status: 'alumni', nomenclature: { suborder: 'Haplorhini', family: 'Hominidae', genus: 'Homo', species: 'ihavelotsofmoneyus', }, friends: [] as string[], }, }; const Cars = { arlene: { model: 'Retro Rides', color: 'yellow', kind: 'SEDAN', rating: 100, features: { color: 'banana yellow to be specific', }, }, will: { model: 'Speedzone Speedster', color: 'red', tags: { speed: 'extreme', }, kind: 'RACE_CAR', rating: 100, }, johnny: { model: 'Glossy German', color: 'silver', tags: { impression: 'decadent', condition: 'slightly beat-up', }, kind: 'LIMOSINE', rating: 101, }, heather: { model: 'Glossy German', color: 'black', tags: { impression: 'decadent', }, kind: 'LIMOSINE', rating: 200, }, }; const Companies = { binsol: { id: 'binsol', name: 'Binary Solutions', legalForm: 'public', ceoUsername: 'johnny', offices: [ { street: '122 Elk Rd Little', city: 'Tucson', }, { street: '124 Elk Rd Little', city: 'Tucson', }, ], }, ccc: { id: 'ccc', name: 'Cool Computers Company', legalForm: 'public', ceoUsername: 'heather', offices: [ { street: '300 Elk Rd Little', city: 'Tucson', }, { street: '301 Elk Rd Little', city: 'Tucson', }, ], }, }; const Offices = [ { employeeId: 'arlene', 'room number': 100, employerId: 'binsol', }, { employeeId: 'will', 'room number': 101, employerId: 'binsol', }, { employeeId: 'johnny', 'room number': 102, employerId: 'binsol', }, { employeeId: 'heather', 'room number': 100, employerId: 'ccc', }, ]; const Patents = { 'CCC OSv1': { 'patent-id': '100', 'inventor-id': 'heather', }, }; const Projects = { 'Peace Among Companies': { projectId: 1, active: true, leadId: 'arlene', patentId: '', }, 'Operation: Control CCC': { projectId: 2, active: false, leadId: 'will', patentId: '', }, 'CCC operation system': { projectId: 3, active: true, leadId: 'will', patentId: '100', }, }; const Papers = { apples: { name: 'Deliciousness of apples', published: true, }, coffee: { name: 'How much coffee is too much coffee?', published: false, }, tennis: { name: 'How many tennis balls can fit into the average building?', published: true, }, }; const TrashCans = { arlene: { brand: 'Garbage Emporium', contents: [ { type: 'apple', message: 'Half-eaten', }, { type: 'sock', message: 'Lost one', }, ], }, will: { brand: 'Garbage Emporium', contents: [ { type: 'sock', message: 'Lost one', }, ], }, johnny: { brand: 'Garbage Emporium', contents: [] as { type: string; message: string }[], }, heather: { brand: 'Solid Gold Products', contents: [ { type: 'tissue', message: 'Used', }, ], }, }; const Auth = { arlene: { username: 'arlene123', password: 'password123', accessToken: 'abcdef', }, will: { username: 'catloverxoxo', password: 'IActuallyPreferDogs', accessToken: '123456', }, johnny: { username: 'johnny', password: 'password', accessToken: 'xyz', }, heather: { username: 'cccrulez', password: 'johnnyisabully', accessToken: 'ijk', }, }; const authMiddleware = (req: any, res: any, next: Function) => { if (req.headers.authorization) { const encoded = req.headers.authorization.split(' ')[1]; const decoded = Buffer.from(encoded, 'base64').toString('utf8').split(':'); if (decoded.length === 2) { const credentials = { username: decoded[0], password: decoded[1], }; for (const user in Auth) { if (Auth[user].username === credentials.username && Auth[user].password === credentials.password) { return next(); } } res.status(401).send({ message: 'Incorrect credentials', }); } else { res.status(401).send({ message: 'Basic Auth expects a single username and a single password', }); } } else if ('access_token' in req.headers) { for (const user in Auth) { if (Auth[user].accessToken === req.headers.access_token) { return next(); } } res.status(401).send({ message: 'Incorrect credentials', }); return false; } else if ('cookie' in req.headers) { for (const user in Auth) { if (Auth[user].accessToken === req.headers.cookie.split('=')[1]) { return next(); } } res.status(401).send({ message: 'Incorrect credentials', }); return false; } else if ('access_token' in req.query) { for (const user in Auth) { if (Auth[user].accessToken === req.query.access_token) { return next(); } } res.status(401).send({ message: 'Incorrect credentials', }); } else { res.status(401).send({ message: 'Unknown/missing credentials', }); } }; app.get('/api/users', (req, res) => { const limit = req.query.limit; if (typeof limit === 'string') { res.send(Object.values(Users).slice(0, Number(limit))); } else { res.send(Object.values(Users)); } }); app.get('/api/users/:username', (req, res) => { if (req.params.username in Users) { res.send(Users[req.params.username]); } else { res.status(404).send({ message: 'Wrong username', }); } }); app.get('/api/users/:username/car', (req, res) => { if (req.params.username in Users) { res.send(Cars[req.params.username]); } else { res.status(404).send({ message: 'Wrong username', }); } }); app.get('/api/users/:username/friends', (req, res) => { if (req.params.username in Users) { const friends = Users[req.params.username].friends.map((friendName: string | number) => { return Users[friendName]; }); res.status(200).send(friends); } else { res.status(404).send({ message: 'Wrong username', }); } }); app.post('/api/users', (req, res) => { const user = req.body; if ('name' in user && 'address' in user && 'employerId' in user && 'hobbies' in user) { res.status(201).send(user); } else { res.status(400).send({ message: 'Wrong data', }); } }); app.get('/api/assets/:companyId', (req, res) => { const assets: { name: string; address: { street: string; city: string }; employerId: string; hobbies: string[]; status: string; nomenclature: { suborder: string; family: string; genus: string; species: string }; friends: string[]; }[] = []; Object.entries(Users).forEach(([username, user]) => { if (req.params.companyId === user.employerId) { assets.push(user); if (username in Cars) { assets.push(Cars[username]); } if (username in TrashCans) { assets.push(TrashCans[username]); } } }); res.send(assets); }); app.get('/api/cars', (req, res) => { res.send(Object.values(Cars)); }); app.get('/api/companies/:id', (req, res) => { if (req.params.id in Companies) { res.status(200).send(Companies[req.params.id]); } else { res.status(404).send({ message: 'Wrong company ID.', }); } }); app.get('/api/coffeeLocation', (req: any, res: any) => { res.send({ lat: parseFloat(req.query.lat) + 5, long: parseFloat(req.query.long) + 5, }); }); app.get('/api/cookie', (req, res) => { if ('cookie' in req.headers) { res .set('Content-Type', 'text/plain') .status(200) .send(`Thanks for your cookie preferences: "${req.headers.cookie.trim()}"`); } else { res.status(400).send('Need Cookie header parameter'); } }); app.get('/api/copier', (req, res) => { res.status(200).send({ body: req.query.query, }); }); app.get('/api/cleanDesks', (req, res) => { res.set('Content-Type', 'text/plain').status(200).send('5 clean desks'); }); app.get('/api/dirtyDesks', (req, res) => { res.set('Content-Type', 'text/plain').status(200).send('5 dirty desks'); }); app.get('/api/bonuses', (req, res) => { res.status(204).send(); }); app.get('/api/offices/:id', (req: any, res: any) => { const accept = req.headers.accept; if (accept.includes('text/plain')) { res.set('Content-Type', 'text/plain').status(200).send('You asked for text!'); } else if (accept.includes('application/json')) { if (req.params.id >= 0 && req.params.id < Offices.length) { res.status(200).send(Offices[req.params.id]); } else { res.status(404).send({ message: 'Cannot find office', }); } } else { res.set('Content-Type', 'text/plain').status(412).send('Please try with an accept parameter!'); } }); app.post('/api/products', (req, res) => { const product = req.body; if ('product-name' in product && 'product-id' in product && 'product-tag' in product) { res.status(201).send(product); } else { res.status(400).send({ message: 'wrong data', }); } }); app.get('/api/products/:id', (req, res) => { if (typeof req.params.id !== 'undefined' && typeof req.query['product-tag'] !== 'undefined') { const product = { // eslint-disable-next-line @typescript-eslint/camelcase product_id: req.params.id, 'product-tag': req.query['product-tag'], 'product-name': 'Super Product', }; res.status(200).send(product); } else { res.status(400).send({ message: 'Wrong data', }); } }); app.get('/api/products/:id/reviews', (req, res) => { if (typeof req.params.id !== 'undefined' && typeof req.query['product-tag'] !== 'undefined') { res.status(200).send([ { text: 'Great product', timestamp: 1502787600000000 }, { text: 'I love it', timestamp: 1502787400000000 }, ]); } else { res.status(400).send({ message: 'wrong data', }); } }); app.get('/api/papers', (req, res) => { res.status(200).send(Object.values(Papers)); }); app.post('/api/papers', (req, res) => { const contentType = req.headers['content-type']; if (contentType.includes('text/plain')) { res .set('Content-Type', 'text/plain') .status(201) .send('You sent the paper idea: ' + req.body); } else { res.status(400).send({ message: "Wrong content-type, expected 'text/plain' but received " + contentType, }); } }); app.get('/api/patents/:id', authMiddleware, (req, res) => { // Find patent based off of patent ID const patent = Object.values(Patents).find(currentPatent => { return currentPatent['patent-id'] === req.params.id; }); if (typeof patent === 'object') { res.status(200).send(patent); } else { res.status(404).send({ message: 'Patent does not exist.' }); } }); app.post('/api/projects', authMiddleware, (req, res) => { const project = req.body; if ('project-id' in project && 'lead-id' in project) { res.status(201).send(project); } else { res.status(400).send({ message: 'Wrong data', }); } }); app.get('/api/projects/:id', authMiddleware, (req, res) => { // Find project based off of projectId const project = Object.values(Projects).find(currentProject => { return currentProject.projectId === Number(req.params.id); }); if (typeof project === 'object') { res.status(200).send(project); } else { res.status(404).send({ message: 'Project does not exist.' }); } }); app.get('/api/scanner', (req, res) => { res.status(200).send({ body: req.query.query }); }); app.post('/api/scanner/:path', (req, res) => { res.status(200).send({ body: `req.body: ${req.body}, req.query.query: ${req.query.query}, req.path.path: ${req.params.path}`, }); }); app.get('/api/snack', (req, res) => { if ('snack_type' in req.headers && 'snack_size' in req.headers) { res .set('Content-Type', 'text/plain') .status(200) .send(`Here is a ${req.headers.snack_size} ${req.headers.snack_type}`); } else { res.status(400).send('Need snack_type and snack_size header parameters'); } }); app.get('/api/status', (req, res) => { if (typeof req.query.limit !== 'undefined' && typeof req.get('exampleHeader') !== 'undefined') { res.set('Content-Type', 'text/plain').status(200).send('Ok'); } else { res.status(400).send({ message: 'wrong request', }); } }); app.post('/api/status', (req, res) => { if ('hello' in req.body && req.body.hello === 'world') { res.status(200).send('success'); } else { res.status(400).send({ message: "Wrong data, try 'hello': 'world'", }); } }); app.get('/api/secure', (req, res) => { if (req.get('authorization') === 'Bearer abcdef') { res.status(200).set('Content-Type', 'text/plain').send('A secure message.'); } else { res.status(401).send({ message: 'Missing authorization header', }); } }); app.get('/api/trashcans', (req, res) => { res.status(200).send(Array.from(Object.values(TrashCans))); }); app.get('/api/trashcans/:username', (req, res) => { if (req.params.username in Users) { res.status(200).send(TrashCans[req.params.username]); } else { res.status(404).send({ message: 'Wrong username', }); } }); app.post('/api/trashcans/:username', (req, res) => { const trashItem = req.body; if (req.params.username in Users) { const trashCan = TrashCans[req.params.username]; trashCan.contents.push(trashItem); res.status(201).send(TrashCans[req.params.username]); } else { res.status(404).send({ message: 'Wrong username', }); } }); return new Promise(resolve => { server = app.listen(PORT, resolve as () => void); }); } /** * Stops server. */ export function stopServer() { return new Promise(resolve => { server.close(resolve); }); } // if run from command line, start server: if (require.main === module) { startServer(3001); }
the_stack
module Kiwi.Geom { /** * An area defined by its position, as indicated by its top-left corner (x,y) and width and height * * @class Rectangle * @namespace Kiwi.Geom * @constructor * @param [x=0] {Number} The x coordinate of the top-left corner of the rectangle. * @param [y=0] {Number} The y coordinate of the top-left corner of the rectangle. * @param [width=0] {Number} width The width of the rectangle in pixels. * @param [height=0] {Number} height The height of the rectangle in pixels. * @return {Kiwi.Geom.Rectangle} This rectangle object * */ export class Rectangle { /** * Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. If you call this function without parameters, a rectangle with x, y, width, and height properties set to 0 is created. **/ constructor (x: number = 0, y: number = 0, width: number = 0, height: number = 0) { this.setTo(x, y, width, height); } /** * The type of this object. * @method objType * @return {String} "Rectangle" * @public */ public objType() { return "Rectangle"; } /** * The x coordinate of the top-left corner of the rectangle * @property x * @type Number * @default 0 * @public */ public x: number = 0; /** * The y coordinate of the top-left corner of the rectangle * @property y * @type Number * @default 0 * @public */ public y: number = 0; /** * The width of the rectangle in pixels * @property width * @type Number * @default 0 * @public */ public width: number = 0; /** * The height of the rectangle in pixels * @property height * @type Number * @default 0 * @public */ public height: number = 0; /** * The sum of the y and height properties. * Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, * but does change the height property. * * @property bottom * @type Number * @public */ public set bottom(value: number) { if (value) { if (value < this.y) { this.height = 0; } else { this.height = value; } } } public get bottom(): number { return this.y + this.height; } /** * Returns a Point containing the location of the center of the Rectangle, relative to the top left edge * @property center * @type Kiwi.Geom.Point * @readOnly * @public */ public get center(): Point { var output: Point = new Point(); return output.setTo(Math.round(this.width / 2), Math.round(this.height / 2)); } /** * Returns a Point containing the location of the Rectangle's bottom-right corner, determined by the values of the right and bottom properties. * @property bottomRight * @type Kiwi.Geom.Point * @public */ public set bottomRight(value: Point) { if (value) { this.right = value.x; this.bottom = value.y; } } public get bottomRight(): Point { var output: Point = new Point(); return output.setTo(this.right, this.bottom); } /** * The x coordinate of the top-left corner of the rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. * @property left * @type Number * @public */ public set left(value: number) { if (value) { var diff = this.x - value; if (this.width + diff < 0) { this.width = 0; this.x = value; } else { this.width += diff; this.x = value; } } } public get left(): number { return this.x; } /** * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. However it does affect the width property. * @property right * @type Number * @public */ public set right(value: number) { if (value) { if (value < this.x) { this.width = 0; } else { this.width = value - this.x; } } } public get right(): number { return this.x + this.width; } /** * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. * @property size * @type Kiwi.Geom.Point * @readOnly * @public */ public get size(): Point { var output: Point = new Point(); return output.setTo(this.width, this.height); } /** * The volume of the Rectangle object in pixels, derived from width * height * @property volume * @type Number * @readOnly * @return */ public get volume(): number { return this.width * this.height; } /** * The perimeter size of the Rectangle object in pixels. This is the sum of all 4 sides. * @property perimeter * @type Number * @readOnly * @public */ public get perimeter(): number { return (this.width * 2) + (this.height * 2); } /** * The y coordinate of the top-left corner of the rectangle. * Changing the top property of a Rectangle object has no effect on the x and width properties. * However it does affect the height property, whereas changing the y value does not affect the height property. * * @method top * @return {Number} * @public */ public set top(value: number) { if (value) { var diff = this.y - value; if (this.height + diff < 0) { this.height = 0; this.y = value; } else { this.height += diff; this.y = value; } } } public get top(): number { return this.y; } /** * The location of the Rectangle object's top-left corner, determined by the x and y coordinates of the point. * @property topLeft * @type Kiwi.Geom.Point * @public */ public set topLeft(value: Point) { if (value) { this.x = value.x; this.y = value.y; } } public get topLeft(): Point { var output: Point = new Point(); return output.setTo(this.x, this.y); } /** * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. * @method clone * @param [output] {Kiwi.Geom.Rectangle} Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. * @return {Kiwi.Geom.Rectangle} * @public */ public clone(output: Rectangle = new Rectangle): Rectangle { return output.setTo(this.x, this.y, this.width, this.height); } /** * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. * @method contains * @param {Number} x The x coordinate of the point to test. * @param {Number} y The y coordinate of the point to test. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. * @public */ public contains(x: number, y: number): boolean { if (x >= this.x && x <= this.right && y >= this.y && y <= this.bottom) { return true; } return false; } /** * Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. * This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. * * @method containsPoint * @param {Kiwi.Geom.Point} point The point object being checked. Can be Kiwi.Geom.Point or any object with .x and .y values. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. * @public */ public containsPoint(point: Point): boolean { return this.contains(point.x, point.y); } /** * Determines whether the Rectangle object specified by the rect parameter is contained within this Rectangle object. * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. * * @method containsRect * @param rect {Kiwi.Geom.Rectangle} The rectangle object being checked. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. * @public */ public containsRect(rect: Rectangle): boolean { // If the given rect has a larger volume than this one then it can never contain it if (rect.volume > this.volume) { return false; } if (rect.x >= this.x && rect.y >= this.y && rect.right <= this.right && rect.bottom <= this.bottom) { return true; } return false; } /** * Copies all of rectangle data from the source Rectangle object into the calling Rectangle object. * * @method copyFrom * @param source {Kiwi.Geom.Rectangle} The source rectangle object to copy from * @return {Kiwi.Geom.Rectangle} This rectangle object * @public */ public copyFrom(source: Rectangle): Rectangle { return this.setTo(source.x, source.y, source.width, source.height); } /** * Copies all the rectangle data from this Rectangle object into the destination Rectangle object. * Creates a new rectangle if one was not passed. * * @method copyTo * @param [target] {Kiwi.Geom.Rectangle} The destination rectangle object to copy in to. Creates a new rectangle if one is not passed. * @return {Kiwi.Geom.Rectangle} The destination rectangle object * @public */ public copyTo(target: Rectangle = new Rectangle()): Rectangle { return target.copyFrom(this); } /** * Determines whether the object specified in the toCompare parameter is equal to this Rectangle object. * This method compares the x, y, width, and height properties of an object against the same properties of this Rectangle object. * * @method equals * @param toCompare {Kiwi.Geom.Rectangle} toCompare The rectangle to compare to this Rectangle object. * @return {boolean} A value of true if the object has exactly the same values for the x, y, width, and height properties as this Rectangle object; otherwise false. * @public */ public equals(toCompare: Rectangle): boolean { if (this.x === toCompare.x && this.y === toCompare.y && this.width === toCompare.width && this.height === toCompare.height) { return true; } return false; } /** * Increases the size of the Rectangle object by the specified amounts, in pixels. * * The center point of the Rectangle object stays the same, * and its size increases to the left and right by the dx value, * and to the top and the bottom by the dy value. * * @method inflate * @param dx {Number} dx The amount to be added to the left side of this Rectangle. * @param dy {Number} dy The amount to be added to the bottom side of this Rectangle. * @return {Kiwi.Geom.Rectangle} This Rectangle object. * @public */ public inflate(dx: number, dy: number): Rectangle { if (!isNaN(dx) && !isNaN(dy)) { this.x -= dx; this.width += 2 * dx; this.y -= dy; this.height += 2 * dy; } return this; } /** * Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. * * @method inflatePoint * @param point {Kiwi.Geom.Point} The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. * @return {Kiwi.Geom.Rectangle} This Rectangle object. * @public */ public inflatePoint(point: Point): Rectangle { return this.inflate(point.x, point.y); } /** * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, * returns the area of intersection as a Rectangle object. * If the rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. * * @method intersection * @param toIntersect {Kiwi.Geom.Rectangle} The Rectangle object to compare against to see if it intersects with this Rectangle object. * @param [output] {Kiwi.Geom.Rectangle} Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. * @return {Kiwi.Geom.Rectangle} A Rectangle object that equals the area of intersection. If the rectangles do not intersect, this method returns an empty Rectangle object; that is, a rectangle with its x, y, width, and height properties set to 0. * @public */ public intersection(toIntersect: Rectangle, output: Rectangle = new Rectangle): Rectangle { if (this.intersects(toIntersect) === true) { output.x = Math.max(toIntersect.x, this.x); output.y = Math.max(toIntersect.y, this.y); output.width = Math.min(toIntersect.right, this.right) - output.x; output.height = Math.min(toIntersect.bottom, this.bottom) - output.y; } return output; } /** * Determines whether the object specified in the toIntersect parameter intersects with this Rectangle object. * This method checks the x, y, width, and height properties of the specified Rectangle object to see if it intersects with this Rectangle object. * * @method intersects * @param toIntersect {Kiwi.Geom.Rectangle} The Rectangle object to compare against to see if it intersects with this Rectangle object. * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. * @public **/ public intersects(toIntersect: Rectangle): boolean { if (toIntersect.x > this.right - 1) { return false; } if (toIntersect.right - 1 < this.x) { return false; } if (toIntersect.bottom - 1 < this.y) { return false; } if (toIntersect.y > this.bottom - 1) { return false; } return true; } /** * Checks for overlaps between this Rectangle and the given Rectangle. Returns an object with boolean values for each check. * * @method overlap * @param rect {Kiwi.Geom.Rectangle} * @return {Object} An object containing the overlapping details between the two Rectangles * @todo Move to an IntersectResult? Do not want to be generating all of these values each time this is called * @public */ public overlap(rect: Rectangle): any { var result = { top: false, bottom: false, left: false, right: false, contains: false, contained: false }; var interRect: Rectangle = this.intersection(rect); if ( interRect.isEmpty ) return result; if ( this.containsRect(rect) ) result.contains = true; if ( rect.containsRect(this) ) result.contained = true; if ( this.top < rect.top ) result.top = true; if ( this.bottom > rect.bottom ) result.bottom = true; if ( this.left < rect.left ) result.left = true; if ( this.right > rect.right ) result.right = true; return result; } /** * Determines whether or not this Rectangle object is empty. * @method isEmpty * @return {boolean} A value of true if the Rectangle object's width or height is less than or equal to 0; otherwise false. * @public */ public isEmpty(): boolean { if (this.width < 1 || this.height < 1) { return true; } return false; } /** * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. * * @method offset * @param dx {Number} Moves the x value of the Rectangle object by this amount. * @param dy {Number} Moves the y value of the Rectangle object by this amount. * @return {Kiwi.Geom.Rectangle} This Rectangle object. * @public */ public offset(dx: number, dy: number): Rectangle { if (!isNaN(dx) && !isNaN(dy)) { this.x += dx; this.y += dy; } return this; } /** * Adjusts the location of the Rectangle object using a Point object as a parameter. * This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. * * @method offsetPoint * @param point {Kiwi.Geom.Point} A Point object to use to offset this Rectangle object. * @return {Kiwi.Geom.Rectangle} This Rectangle object. * @public */ public offsetPoint(point: Point): Rectangle { return this.offset(point.x, point.y); } /** * Sets all of the Rectangle object's properties to 0. * A Rectangle object is empty if its width or height is less than or equal to 0. * * @method setEmpty * @return {Kiwi.Geom.Rectangle} This rectangle object * @public */ public setEmpty() { return this.setTo(0, 0, 0, 0); } /** * Sets the properties of Rectangle to the specified values. * * @method setTo * @param x {Number} x The x coordinate of the top-left corner of the rectangle. * @param y {Number} y The y coordinate of the top-left corner of the rectangle. * @param width {Number} width The width of the rectangle in pixels. * @param height {Number} height The height of the rectangle in pixels. * @return {Kiwi.Geom.Rectangle} This rectangle object * @public */ public setTo(x: number, y: number, width: number, height: number): Rectangle { if (!isNaN(x) && !isNaN(y) && !isNaN(width) && !isNaN(height)) { this.x = x; this.y = y; if (width >= 0) { this.width = width; } if (height >= 0) { this.height = height; } } return this; } /** * Adds two rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two rectangles. * * @method union * @param toUnion {Kiwi.Geom.Rectangle} toUnion A Rectangle object to add to this Rectangle object. * @param [output] {Kiwi.Geom.Rectangle} output Optional Rectangle object. If given the new values will be set into this object, otherwise a new Rectangle object will be created. * @return {Kiwi.Geom.Rectangle} A Rectangle object that is the union of the two rectangles. * @public */ public union(toUnion: Rectangle, output: Rectangle = new Rectangle): Rectangle { return output.setTo( Math.min(toUnion.x, this.x), Math.min(toUnion.y, this.y), Math.max(toUnion.right, this.right), Math.max(toUnion.bottom, this.bottom) ); } /** * Scales this Rectangle by values passed. * * @method scale * @param x {number} * @param y {number} * @param translation {Kiwi.Geom.Point} * @return {Kiwi.Geom.Rectangle} * @public */ public scale(x:number,y:number,translation:Kiwi.Geom.Point): Rectangle { var trans: Kiwi.Geom.Transform = new Kiwi.Geom.Transform; trans.scaleX = x; trans.scaleY = y; trans.x = translation.x; trans.y = translation.y; var tl: Kiwi.Geom.Point = this.topLeft; trans.transformPoint(tl); this.topLeft = tl; this.width *= x; this.height *= y; return this; } /** * Returns a string representation of this object. * @method toString * @return {String} a string representation of the instance. */ public toString(): string { return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " isEmpty=" + this.isEmpty() + ")}]"; } } }
the_stack