text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import {t} from '@lingui/macro' import {Trans} from '@lingui/react' import {JOBS} from 'data/JOBS' import {Event, Events} from 'event' import {filter, oneOf} from 'parser/core/filter' import {dependency} from 'parser/core/Injectable' import {CounterGauge, Gauge as CoreGauge} from 'parser/core/modules/Gauge' import {Statistics} from 'parser/core/modules/Statistics' import Suggestions, {TieredSuggestion, SEVERITY} from 'parser/core/modules/Suggestions' import {DualStatistic} from 'parser/jobs/rdm/statistics/DualStatistic' import React, {Fragment} from 'react' import {isSuccessfulHit} from 'utilities' interface GaugeModifier { white: number black: number } export const MANA_DIFFERENCE_THRESHOLD = 30 export const MANA_CAP = 100 export class Gauge extends CoreGauge { static override title = t('rdm.gauge.title')`Mana Gauge Usage` @dependency private suggestions!: Suggestions @dependency private statistics!: Statistics private whiteManaGauge = this.add(new CounterGauge({ graph: { label: <Trans id="rdm.gauge.resource.whitemana">White Mana</Trans>, color: JOBS.WHITE_MAGE.colour, }, maximum: 100, minimum: 0, })) private blackManaGauge = this.add(new CounterGauge({ graph: { label: <Trans id="rdm.gauge.resource.blackmana">Black Mana</Trans>, color: JOBS.BLACK_MAGE.colour, }, maximum: 100, minimum: 0, })) public gaugeModifiers = new Map<number, GaugeModifier>([ [this.data.actions.VERAERO.id, {white: 6, black: 0}], [this.data.actions.VERAERO_II.id, {white: 7, black: 0}], [this.data.actions.VERAERO_III.id, {white: 6, black: 0}], [this.data.actions.VERSTONE.id, {white: 5, black: 0}], [this.data.actions.VERHOLY.id, {white: 11, black: 0}], [this.data.actions.VERTHUNDER.id, {white: 0, black: 6}], [this.data.actions.VERTHUNDER_II.id, {white: 0, black: 7}], [this.data.actions.VERTHUNDER_III.id, {white: 0, black: 6}], [this.data.actions.VERFIRE.id, {white: 0, black: 5}], [this.data.actions.VERFLARE.id, {white: 0, black: 11}], [this.data.actions.JOLT.id, {white: 2, black: 2}], [this.data.actions.JOLT_II.id, {white: 2, black: 2}], [this.data.actions.IMPACT.id, {white: 3, black: 3}], [this.data.actions.SCORCH.id, {white: 4, black: 4}], [this.data.actions.RESOLUTION.id, {white: 4, black: 4}], ]) public spenderModifiers = new Map<number, GaugeModifier>([ [this.data.actions.ENCHANTED_REPRISE.id, {white: -5, black: -5}], [this.data.actions.ENCHANTED_MOULINET.id, {white: -20, black: -20}], [this.data.actions.ENCHANTED_RIPOSTE.id, {white: -20, black: -20}], [this.data.actions.ENCHANTED_ZWERCHHAU.id, {white: -15, black: -15}], [this.data.actions.ENCHANTED_REDOUBLEMENT.id, {white: -15, black: -15}], ]) private severityWastedMana = { 1: SEVERITY.MINOR, 20: SEVERITY.MEDIUM, 80: SEVERITY.MAJOR, } private severityLostMana = { 1: SEVERITY.MINOR, 20: SEVERITY.MEDIUM, 80: SEVERITY.MAJOR, } private readonly manaLostDivisor = 2 private readonly manaficationManaGain = 50 manaStatistics = { white: { manaficationLoss: 0, imbalanceLoss: 0, invulnLoss: 0, }, black: { manaficationLoss: 0, imbalanceLoss: 0, invulnLoss: 0, }, } override initialise() { super.initialise() this.addEventHook( filter<Event>() .type('damage') .source(this.parser.actor.id), this.onGaugeModifying ) this.addEventHook( filter<Event>() .type('action') .source(this.parser.actor.id) .action(oneOf(Array.from(this.spenderModifiers.keys()))), this.onGaugeSpender ) this.addEventHook( filter<Event>() .type('action') .source(this.parser.actor.id) .action(this.data.actions.MANAFICATION.id), this.onManafication ) this.addEventHook('complete', this.onComplete) } private onGaugeModifying(event: Events['damage']) { if (event.cause.type !== 'action') { return } const modifier = this.gaugeModifiers.get(event.cause.action) if (modifier == null) { return } const amount = modifier const penalized = this.isOutOfBalance() const whiteModified = penalized.white ? Math.floor(amount.white/ this.manaLostDivisor) : amount.white const blackModified = penalized.black ? Math.floor(amount.black/ this.manaLostDivisor) : amount.black if (!isSuccessfulHit(event)) { //Then we lost this mana, add to statistics and move along. this.manaStatistics.white.invulnLoss += whiteModified this.manaStatistics.black.invulnLoss += blackModified return } this.whiteManaGauge.modify(whiteModified) this.blackManaGauge.modify(blackModified) //Statistics Gathering this.manaStatistics.white.imbalanceLoss += amount.white - whiteModified this.manaStatistics.black.imbalanceLoss += amount.black - blackModified } private onManafication() { let whiteModifier = this.getWhiteMana() + this.manaficationManaGain let blackModifier = this.getBlackMana() + this.manaficationManaGain //Now calculate and store overcap if any. This way we can still utilize the Overcap //From core, but track this loss separately. if (whiteModifier > MANA_CAP) { this.manaStatistics.white.manaficationLoss = whiteModifier - MANA_CAP whiteModifier = MANA_CAP } if (blackModifier > MANA_CAP) { this.manaStatistics.black.manaficationLoss = blackModifier - MANA_CAP blackModifier = MANA_CAP } this.whiteManaGauge.set(whiteModifier) this.blackManaGauge.set(blackModifier) } private onGaugeSpender(event: Events['action']) { const modifier = this.spenderModifiers.get(event.action) if (modifier == null) { return } const amount = modifier this.whiteManaGauge.modify(amount.white) this.blackManaGauge.modify(amount.black) } //Returns which Mana should be penalized, white, black, or neither private isOutOfBalance() : {white: boolean, black: boolean} { const whiteMana = this.getWhiteMana() const blackMana = this.getBlackMana() if (whiteMana && (blackMana - whiteMana > MANA_DIFFERENCE_THRESHOLD)) { //If we have more than 30 Black Mana over White, our White gains are halved. return {white: true, black: false} } if (blackMana && (whiteMana - blackMana> MANA_DIFFERENCE_THRESHOLD)) { //If we have more than 30 White Mana over Black, our Black gains are halved return {white: false, black: true} } return {white: false, black: false} } private onComplete() { this.suggestions.add(new TieredSuggestion({ icon: this.whiteManaGauge.overCap > this.blackManaGauge.overCap ? this.data.actions.VERHOLY.icon : this.data.actions.VERFLARE.icon, content: <Fragment> <Trans id="rdm.gauge.suggestions.mana-wasted-content">Ensure you don't overcap your Mana before a combo; overcapping Mana indicates your balance was off, and you potentially lost out on Enchanted Combo damage.</Trans> </Fragment>, tiers: this.severityWastedMana, value: this.whiteManaGauge.overCap + this.blackManaGauge.overCap, why: <Fragment> <Trans id="rdm.gauge.suggestions.mana-wasted-why">You lost { this.whiteManaGauge.overCap} White Mana and {this.blackManaGauge.overCap} Black Mana due to capped Gauge resources</Trans> </Fragment>, })) this.suggestions.add(new TieredSuggestion({ icon: this.manaStatistics.white.imbalanceLoss > this.manaStatistics.black.imbalanceLoss ? this.data.actions.VERHOLY.icon : this.data.actions.VERFLARE.icon, content: <Fragment> <Trans id="rdm.gauge.suggestions.mana-lost-content">Ensure you don't allow a difference of more than 30 betwen mana types. You lost Mana due to Imbalance which reduces your overall mana gain and potentially costs you one or more Enchanted Combos.</Trans> </Fragment>, tiers: this.severityLostMana, value: this.manaStatistics.white.imbalanceLoss + this.manaStatistics.black.imbalanceLoss, why: <Fragment> <Trans id="rdm.gauge.suggestions.mana-lost-why">You lost { this.manaStatistics.white.imbalanceLoss} White Mana and { this.manaStatistics.black.imbalanceLoss} Black Mana due to overage of black Mana</Trans> </Fragment>, })) this.suggestions.add(new TieredSuggestion({ icon: this.manaStatistics.white.invulnLoss > this.manaStatistics.black.invulnLoss ? this.data.actions.VERHOLY.icon : this.data.actions.VERFLARE.icon, content: <Fragment> <Trans id="rdm.gauge.suggestions.mana-invuln-content">Ensure you don't target a boss that you cannot damage with your damaging spells. Spells that do no damage due to an invulnerable target or due to missing result in no mana gained, which potentially costs you one or more Enchanted Combos.</Trans> </Fragment>, tiers: this.severityLostMana, value: this.manaStatistics.white.invulnLoss + this.manaStatistics.black.invulnLoss, why: <Fragment> <Trans id="rdm.gauge.suggestions.mana-invuln-why">You lost { this.manaStatistics.white.invulnLoss} White Mana and { this.manaStatistics.black.invulnLoss} Black Mana due to misses or spells that targeted an invulnerable target</Trans> </Fragment>, })) this.statistics.add(new DualStatistic({ label: <Trans id="rdm.gauge.title-mana-lost-to-manafication">Manafication Loss:</Trans>, title: <Trans id="rdm.gauge.white-mana-lost-to-manafication">White</Trans>, title2: <Trans id="rdm.gauge.black-mana-lost-to-manafication">Black</Trans>, icon: this.data.actions.VERHOLY.icon, icon2: this.data.actions.VERFLARE.icon, value: this.manaStatistics.white.manaficationLoss, value2: this.manaStatistics.black.manaficationLoss, info: ( <Trans id="rdm.gauge.white-mana-lost-to-manafication-statistics"> It is ok to lose some mana to manafication over the course of a fight, you should however strive to keep this number as low as possible. </Trans> ), })) } public getWhiteMana() { return this.whiteManaGauge.value } public getWhiteManaAt(timestamp: number) { return this.whiteManaGauge.getValueAt(timestamp) } public getBlackMana() { return this.blackManaGauge.value } public getBlackManaAt(timestamp: number) { return this.blackManaGauge.getValueAt(timestamp) } }
the_stack
import {WireDataDelimited, WireDataPlain} from "./support/wire-data"; import {BinaryReader, WireType} from "../src"; import {msg_longs_bytes} from "../../test-fixtures/msg-longs.fixtures"; describe('BinaryReader', () => { beforeEach(function () { jasmine.addCustomEqualityTester((a, b) => (a instanceof Uint8Array && b instanceof Uint8Array) ? a.byteLength === b.byteLength : undefined ); }); it('tag() reads expected fieldNo', function () { let reader = new BinaryReader(WireDataPlain.tag_field_4_wire_type_varint); let [fieldNo] = reader.tag(); expect(fieldNo).toBe(4); }); it('reading length delimited', function () { let reader = new BinaryReader(WireDataDelimited.fixed32_666); let length = reader.uint32(); expect(length).toBe(reader.len - reader.pos); let value = reader.fixed32(); expect(value).toBe(666); }); it('tag() reads expected wireType', function () { let reader = new BinaryReader(WireDataPlain.tag_field_4_wire_type_varint); let [, wireType] = reader.tag(); expect(wireType).toBe(WireType.Varint); }); it('skip() skips varint 64', function () { let reader = new BinaryReader(WireDataPlain.sfixed64_123); let skipped = reader.skip(WireType.Bit64); expect(reader.pos).toBe(reader.len); expect(skipped).toEqual(WireDataPlain.sfixed64_123); }); it('skip() skips varint 32', function () { let reader = new BinaryReader(WireDataPlain.int32_123); let skipped = reader.skip(WireType.Varint); expect(reader.pos).toBe(reader.len); expect(skipped).toEqual(WireDataPlain.int32_123); }); it('skip() skips fixed 64', function () { let reader = new BinaryReader(WireDataPlain.int64_123); let skipped = reader.skip(WireType.Varint); expect(reader.pos).toBe(reader.len); expect(skipped).toEqual(WireDataPlain.int64_123); }); it('skip() skips length-delimited', function () { let reader = new BinaryReader(WireDataDelimited.fixed32_666); let skipped = reader.skip(WireType.LengthDelimited); expect(reader.pos).toBe(reader.len); expect(skipped).toEqual(WireDataDelimited.fixed32_666); }); it('reads spec.LongsMessage with min / max values', function () { let reader = new BinaryReader(msg_longs_bytes); let fieldNo: number; let wireType: WireType; // jstype = normal // 1: fixed64_field_min // not present, because value 0 equals default value and is not written // 2: fixed64_field_max [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(2); expect(wireType).toBe(WireType.Bit64); expect(reader.fixed64().toString()).toBe("18446744073709551615"); // 3: int64_field_min [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(3); expect(wireType).toBe(WireType.Varint); expect(reader.int64().toString()).toBe("-9223372036854775808"); // 4: int64_field_max [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(4); expect(wireType).toBe(WireType.Varint); expect(reader.int64().toString()).toBe("9223372036854775807"); // 5: sfixed64_field_min [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(5); expect(wireType).toBe(WireType.Bit64); expect(reader.sfixed64().toString()).toBe("-9223372036854775808"); // 6: sfixed64_field_max [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(6); expect(wireType).toBe(WireType.Bit64); expect(reader.sfixed64().toString()).toBe("9223372036854775807"); // 7: sint64_field_min [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(7); expect(wireType).toBe(WireType.Varint); expect(reader.sint64().toString()).toBe("-9223372036854775808"); // 8: sint64_field_max [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(8); expect(wireType).toBe(WireType.Varint); expect(reader.sint64().toString()).toBe("9223372036854775807"); // 9: uint64_field_min // not present, because value 0 equals default value and is not written // 10: uint64_field_max [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(10); expect(wireType).toBe(WireType.Varint); expect(reader.uint64().toString()).toBe("18446744073709551615"); // jstype = string // 11: fixed64_field_min // not present, because value 0 equals default value and is not written // 12: fixed64_field_max [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(12); expect(wireType).toBe(WireType.Bit64); expect(reader.fixed64().toString()).toBe("18446744073709551615"); // 13: int64_field_min [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(13); expect(wireType).toBe(WireType.Varint); expect(reader.int64().toString()).toBe("-9223372036854775808"); // 14: int64_field_max [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(14); expect(wireType).toBe(WireType.Varint); expect(reader.int64().toString()).toBe("9223372036854775807"); // 15: sfixed64_field_min [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(15); expect(wireType).toBe(WireType.Bit64); expect(reader.sfixed64().toString()).toBe("-9223372036854775808"); // 16: sfixed64_field_max [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(16); expect(wireType).toBe(WireType.Bit64); expect(reader.sfixed64().toString()).toBe("9223372036854775807"); // 17: sint64_field_min [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(17); expect(wireType).toBe(WireType.Varint); expect(reader.sint64().toString()).toBe("-9223372036854775808"); // 18: sint64_field_max [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(18); expect(wireType).toBe(WireType.Varint); expect(reader.sint64().toString()).toBe("9223372036854775807"); // 19: uint64_field_min // not present, because value 0 equals default value and is not written // 20: uint64_field_max [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(20); expect(wireType).toBe(WireType.Varint); expect(reader.uint64().toString()).toBe("18446744073709551615"); // jstype = number // 21: fixed64_field_min // not present, because value 0 equals default value and is not written // 22: fixed64_field_max [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(22); expect(wireType).toBe(WireType.Bit64); expect(reader.fixed64().toString()).toBe("18446744073709551615"); // 23: int64_field_min [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(23); expect(wireType).toBe(WireType.Varint); expect(reader.int64().toString()).toBe("-9223372036854775808"); // 24: int64_field_max [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(24); expect(wireType).toBe(WireType.Varint); expect(reader.int64().toString()).toBe("9223372036854775807"); // 25: sfixed64_field_min [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(25); expect(wireType).toBe(WireType.Bit64); expect(reader.sfixed64().toString()).toBe("-9223372036854775808"); // 26: sfixed64_field_max [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(26); expect(wireType).toBe(WireType.Bit64); expect(reader.sfixed64().toString()).toBe("9223372036854775807"); // 27: sint64_field_min [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(27); expect(wireType).toBe(WireType.Varint); expect(reader.sint64().toString()).toBe("-9223372036854775808"); // 28: sint64_field_max [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(28); expect(wireType).toBe(WireType.Varint); expect(reader.sint64().toString()).toBe("9223372036854775807"); // 29: uint64_field_min // not present, because value 0 equals default value and is not written // 30: uint64_field_max [fieldNo, wireType] = reader.tag(); expect(fieldNo).toBe(30); expect(wireType).toBe(WireType.Varint); expect(reader.uint64().toString()).toBe("18446744073709551615"); }); it('bool() reads true', function () { let reader = new BinaryReader(WireDataPlain.bool_true); let value = reader.bool(); expect(value).toBe(true); }); it('bool() reads false', function () { let reader = new BinaryReader(WireDataPlain.bool_false); let value = reader.bool(); expect(value).toBe(false); }); it('fixed64() reads 123', function () { let reader = new BinaryReader(WireDataPlain.fixed64_123); let value = reader.fixed64(); expect(value.toString()).toBe("123"); expect(value.toNumber()).toBe(123); if (globalThis.BigInt) expect(value.toBigInt()).toBe(globalThis.BigInt(123)); }); it('sfixed64() reads 123', function () { let reader = new BinaryReader(WireDataPlain.sfixed64_123); let value = reader.sfixed64(); expect(value.toString()).toBe("123"); expect(value.toNumber()).toBe(123); if (globalThis.BigInt) expect(value.toBigInt()).toBe(globalThis.BigInt(123)); }); it('sfixed64() reads -123', function () { let reader = new BinaryReader(WireDataPlain.sfixed64_minus_123); let value = reader.sfixed64(); expect(value.toString()).toBe("-123"); expect(value.toNumber()).toBe(-123); if (globalThis.BigInt) expect(value.toBigInt()).toBe(globalThis.BigInt(-123)); }); it('uint64() reads 123', function () { let reader = new BinaryReader(WireDataPlain.uint64_123); let value = reader.uint64(); expect(value.toString()).toBe("123"); expect(value.toNumber()).toBe(123); if (globalThis.BigInt) expect(value.toBigInt()).toBe(globalThis.BigInt(123)); }); it('sint64() reads 123', function () { let reader = new BinaryReader(WireDataPlain.sint64_123); let value = reader.sint64(); expect(value.toString()).toBe("123"); expect(value.toNumber()).toBe(123); if (globalThis.BigInt) expect(value.toBigInt()).toBe(globalThis.BigInt(123)); }); it('sint64() reads -123', function () { let reader = new BinaryReader(WireDataPlain.sint64_minus_123); let value = reader.sint64(); expect(value.toString()).toBe("-123"); expect(value.toNumber()).toBe(-123); if (globalThis.BigInt) expect(value.toBigInt()).toBe(globalThis.BigInt(-123)); }); it('int32() reads 123', function () { let reader = new BinaryReader(WireDataPlain.int32_123); let value = reader.int32(); expect(value).toBe(123); }); it('int32() reads -123', function () { let reader = new BinaryReader(WireDataPlain.int32_minus_123); let value = reader.int32(); expect(value).toBe(-123); }); it('uint32() reads 123', function () { let reader = new BinaryReader(WireDataPlain.uint32_123); let value = reader.uint32(); expect(value).toBe(123); }); it('float() reads 0.75', function () { let reader = new BinaryReader(WireDataPlain.float_0_75); let value = reader.float(); expect(value).toBe(0.75); }); it('float() reads -0.75', function () { let reader = new BinaryReader(WireDataPlain.float_minus_0_75); let value = reader.float(); expect(value).toBe(-0.75); }); it('double() reads 0.75', function () { let reader = new BinaryReader(WireDataPlain.double_0_75); let value = reader.double(); expect(value).toBe(0.75); }); it('double() reads -0.75', function () { let reader = new BinaryReader(WireDataPlain.double_minus_0_75); let value = reader.double(); expect(value).toBe(-0.75); }); it('fixed32() reads 123', function () { let reader = new BinaryReader(WireDataPlain.fixed32_123); let value = reader.fixed32(); expect(value).toBe(123); }); it('sfixed32() reads 123', function () { let reader = new BinaryReader(WireDataPlain.sfixed32_123); let value = reader.sfixed32(); expect(value).toBe(123); }); it('sfixed32() reads -123', function () { let reader = new BinaryReader(WireDataPlain.sfixed32_minus_123); let value = reader.sfixed32(); expect(value).toBe(-123); }); it('sint32() reads 123', function () { let reader = new BinaryReader(WireDataPlain.sint32_123); let value = reader.sint32(); expect(value).toBe(123); }); it('sint32() reads -123', function () { let reader = new BinaryReader(WireDataPlain.sint32_minus_123); let value = reader.sint32(); expect(value).toBe(-123); }); it('string() reads hello 🌍', function () { let reader = new BinaryReader(WireDataPlain.string_hello_world_emoji); let value = reader.string(); expect(value).toBe('hello 🌍'); }); it('bytes() reads de ad be ef', function () { let reader = new BinaryReader(WireDataPlain.bytes_deadbeef); let value = reader.bytes(); expect(value).toEqual(new Uint8Array([0xde, 0xad, 0xbe, 0xef])); }); });
the_stack
import { Component, ComponentSet, Attribute, serialize, deserialize, ensureComponentClass, ComponentMixin, assertIsComponentMixin } from '@layr/component'; import type {ComponentServerLike} from '@layr/component-server'; import {Microbatcher, Operation} from 'microbatcher'; import {getTypeOf, PlainObject} from 'core-helpers'; import {possiblyAsync} from 'possibly-async'; import debugModule from 'debug'; const debug = debugModule('layr:component-client'); // To display the debug log, set this environment: // DEBUG=layr:component-client DEBUG_DEPTH=5 import {isComponentClientInstance} from './utilities'; interface SendOperation extends Operation { params: Parameters<ComponentClient['_sendOne']>; resolve: (value: ReturnType<ComponentClient['_sendOne']>) => void; } export type ComponentClientOptions = { version?: number; mixins?: ComponentMixin[]; batchable?: boolean; }; /** * A base class allowing to access a root [`Component`](https://layrjs.com/docs/v2/reference/component) that is served by a [`ComponentServer`](https://layrjs.com/docs/v2/reference/component-server). * * Typically, instead of using this class, you would use a subclass such as [`ComponentHTTPClient`](https://layrjs.com/docs/v2/reference/component-http-client). */ export class ComponentClient { _componentServer: ComponentServerLike; _version: number | undefined; _mixins: ComponentMixin[] | undefined; _sendBatcher: Microbatcher<SendOperation> | undefined; /** * Creates a component client. * * @param componentServer The [`ComponentServer`](https://layrjs.com/docs/v2/reference/component-server) to connect to. * @param [options.version] A number specifying the expected version of the component server (default: `undefined`). If a version is specified, an error is thrown when a request is sent and the component server has a different version. The thrown error is a JavaScript `Error` instance with a `code` attribute set to `'COMPONENT_CLIENT_VERSION_DOES_NOT_MATCH_COMPONENT_SERVER_VERSION'`. * @param [options.mixins] An array of the component mixins (e.g., [`Storable`](https://layrjs.com/docs/v2/reference/storable)) to use when constructing the components exposed by the component server (default: `[]`). * * @returns A `ComponentClient` instance. * * @example * ``` * // JS * * import {Component, attribute, expose} from '﹫layr/component'; * import {ComponentClient} from '﹫layr/component-client'; * import {ComponentServer} from '﹫layr/component-server'; * * class Movie extends Component { * ﹫expose({get: true, set: true}) ﹫attribute('string') title; * } * * const server = new ComponentServer(Movie); * const client = new ComponentClient(server); * * const RemoteMovie = client.getComponent(); * ``` * * @example * ``` * // TS * * import {Component, attribute, expose} from '﹫layr/component'; * import {ComponentClient} from '﹫layr/component-client'; * import {ComponentServer} from '﹫layr/component-server'; * * class Movie extends Component { * ﹫expose({get: true, set: true}) ﹫attribute('string') title!: string; * } * * const server = new ComponentServer(Movie); * const client = new ComponentClient(server); * * const RemoteMovie = client.getComponent() as typeof Movie; * ``` * * @category Creation */ constructor(componentServer: ComponentServerLike, options: ComponentClientOptions = {}) { const {version, mixins, batchable = false} = options; if (typeof componentServer?.receive !== 'function') { throw new Error( `Expected a component server, but received a value of type '${getTypeOf(componentServer)}'` ); } if (mixins !== undefined) { for (const mixin of mixins) { assertIsComponentMixin(mixin); } } this._componentServer = componentServer; this._version = version; this._mixins = mixins; if (batchable) { this._sendBatcher = new Microbatcher(this._sendMany.bind(this)); } } _component!: typeof Component; /** * Gets the component that is served by the component server. * * @returns A [`Component`](https://layrjs.com/docs/v2/reference/component) class. * * @examplelink See [`constructor`'s example](https://layrjs.com/docs/v2/reference/component-client#constructor). * * @category Getting the Served Component * @possiblyasync */ getComponent() { if (this._component === undefined) { return possiblyAsync(this._createComponent(), (component) => { this._component = component; return component; }); } return this._component; } _createComponent() { return possiblyAsync(this._introspectComponentServer(), (introspectedComponentServer) => { const methodBuilder = (name: string) => this._createMethodProxy(name); return Component.unintrospect(introspectedComponentServer.component, { mixins: this._mixins, methodBuilder }); }); } _createMethodProxy(name: string) { const componentClient = this; return function (this: typeof Component | Component, ...args: any[]) { const query = { '<=': this, [`${name}=>`]: {'()': args} }; const rootComponent = ensureComponentClass(this); return componentClient.send(query, {rootComponent}); }; } _introspectedComponentServer!: PlainObject; _introspectComponentServer() { if (this._introspectedComponentServer === undefined) { const query = {'introspect=>': {'()': []}}; return possiblyAsync(this.send(query), (introspectedComponentServer) => { this._introspectedComponentServer = introspectedComponentServer; return introspectedComponentServer; }); } return this._introspectedComponentServer; } send(query: PlainObject, options: {rootComponent?: typeof Component} = {}): any { if (this._sendBatcher !== undefined) { return this._sendBatcher.batch(query, options); } return this._sendOne(query, options); } _sendOne(query: PlainObject, options: {rootComponent?: typeof Component}): any { const {rootComponent} = options; const {serializedQuery, serializedComponents} = this._serializeQuery(query); debugRequest({serializedQuery, serializedComponents}); return possiblyAsync( this._componentServer.receive({ query: serializedQuery, ...(serializedComponents && {components: serializedComponents}), version: this._version }), ({result: serializedResult, components: serializedComponents}) => { debugResponse({serializedResult, serializedComponents}); const errorHandler = function (error: Error) { throw error; }; return possiblyAsync( deserialize(serializedComponents, { rootComponent, deserializeFunctions: true, errorHandler, source: 'server' }), () => { return deserialize(serializedResult, { rootComponent, deserializeFunctions: true, errorHandler, source: 'server' }); } ); } ); } async _sendMany(operations: SendOperation[]) { if (operations.length === 1) { const operation = operations[0]; try { operation.resolve(await this._sendOne(...operation.params)); } catch (error) { operation.reject(error); } return; } const queries = {'||': operations.map(({params: [query]}) => query)}; const {serializedQuery, serializedComponents} = this._serializeQuery(queries); debugRequests({serializedQuery, serializedComponents}); const serializedResponse = await this._componentServer.receive({ query: serializedQuery, ...(serializedComponents && {components: serializedComponents}), version: this._version }); debugResponses({ serializedResult: serializedResponse.result, serializedComponents: serializedResponse.components }); const errorHandler = function (error: Error) { throw error; }; const firstRootComponent = operations[0].params[1].rootComponent; await deserialize(serializedResponse.components, { rootComponent: firstRootComponent, deserializeFunctions: true, errorHandler, source: 'server' }); for (let index = 0; index < operations.length; index++) { const operation = operations[index]; const serializedResult = (serializedResponse.result as unknown[])[index]; try { const result = await deserialize(serializedResult, { rootComponent: operation.params[1].rootComponent, deserializeFunctions: true, errorHandler, source: 'server' }); operation.resolve(result); } catch (error) { operation.reject(error); } } } _serializeQuery(query: PlainObject) { const componentDependencies: ComponentSet = new Set(); const attributeFilter = function (this: typeof Component | Component, attribute: Attribute) { // Exclude properties that cannot be set in the remote components const remoteComponent = this.getRemoteComponent(); if (remoteComponent === undefined) { return false; } const attributeName = attribute.getName(); const remoteAttribute = remoteComponent.hasAttribute(attributeName) ? remoteComponent.getAttribute(attributeName) : undefined; if (remoteAttribute === undefined) { return false; } return remoteAttribute.operationIsAllowed('set') as boolean; }; const serializedQuery: PlainObject = serialize(query, { componentDependencies, attributeFilter, target: 'server' }); let serializedComponentDependencies: PlainObject[] | undefined; const handledComponentDependencies: ComponentSet = new Set(); const serializeComponentDependencies = function (componentDependencies: ComponentSet) { if (componentDependencies.size === 0) { return; } const additionalComponentDependency: ComponentSet = new Set(); for (const componentDependency of componentDependencies.values()) { if (handledComponentDependencies.has(componentDependency)) { continue; } const serializedComponentDependency = componentDependency.serialize({ componentDependencies: additionalComponentDependency, ignoreEmptyComponents: true, attributeFilter, target: 'server' }); if (serializedComponentDependency !== undefined) { if (serializedComponentDependencies === undefined) { serializedComponentDependencies = []; } serializedComponentDependencies.push(serializedComponentDependency); } handledComponentDependencies.add(componentDependency); } serializeComponentDependencies(additionalComponentDependency); }; serializeComponentDependencies(componentDependencies); return {serializedQuery, serializedComponents: serializedComponentDependencies}; } static isComponentClient(value: any): value is ComponentClient { return isComponentClientInstance(value); } } function debugRequest({ serializedQuery, serializedComponents }: { serializedQuery: PlainObject; serializedComponents: PlainObject[] | undefined; }) { let message = 'Sending query: %o'; const values = [serializedQuery]; if (serializedComponents !== undefined) { message += ' (components: %o)'; values.push(serializedComponents); } debug(message, ...values); } function debugResponse({ serializedResult, serializedComponents }: { serializedResult: unknown; serializedComponents: PlainObject[] | undefined; }) { let message = 'Result received: %o'; const values = [serializedResult]; if (serializedComponents !== undefined) { message += ' (components: %o)'; values.push(serializedComponents); } debug(message, ...values); } function debugRequests({ serializedQuery, serializedComponents }: { serializedQuery: PlainObject; serializedComponents: PlainObject[] | undefined; }) { let message = 'Sending queries: %o'; const values = [serializedQuery]; if (serializedComponents !== undefined) { message += ' (components: %o)'; values.push(serializedComponents); } debug(message, ...values); } function debugResponses({ serializedResult, serializedComponents }: { serializedResult: unknown; serializedComponents: PlainObject[] | undefined; }) { let message = 'Results received: %o'; const values = [serializedResult]; if (serializedComponents !== undefined) { message += ' (components: %o)'; values.push(serializedComponents); } debug(message, ...values); }
the_stack
import "jest-extended"; import * as Hapi from "@hapi/hapi"; import * as Hoek from "@hapi/hoek"; import * as Teamwork from "@hapi/teamwork"; import { Client, plugin } from "@packages/core-p2p/src/hapi-nes"; import { stringifyNesMessage } from "@packages/core-p2p/src/hapi-nes/utils"; jest.setTimeout(60000); const createServerWithPlugin = async (pluginOptions = {}, serverOptions = {}, withPreResponseHandler = false) => { const server = Hapi.server(serverOptions); await server.register({ plugin: plugin, options: pluginOptions }); server.ext({ type: "onPostAuth", async method(request, h) { request.payload = (request.payload || Buffer.from("")).toString(); return h.continue; }, }); if (withPreResponseHandler) { server.ext({ type: "onPreResponse", method: async (request, h) => { try { if (request.response.source) { request.response.source = Buffer.from(request.response.source); } else { const errorMessage = request.response.output?.payload?.message ?? request.response.output?.payload?.error ?? "Error"; request.response.output.payload = Buffer.from(errorMessage, "utf-8"); } } catch (e) { request.response.statusCode = 500; // Internal server error (serializing failed) request.response.output = { statusCode: 500, payload: Buffer.from("Internal server error"), headers: {}, }; } return h.continue; }, }); } return server; }; describe("Client", () => { it("defaults options.ws.maxPayload to 102400 (node) && perMessageDeflate to false", () => { const client = new Client("http://localhost"); // @ts-ignore expect(client._settings.ws).toEqual({ maxPayload: 102400, perMessageDeflate: false }); }); it("allows setting options.ws.maxPayload (node)", () => { const client = new Client("http://localhost", { ws: { maxPayload: 100 } }); // @ts-ignore expect(client._settings.ws).toEqual({ maxPayload: 100, perMessageDeflate: false }); }); it("prevents setting options.ws.perMessageDeflate (node)", () => { const client = new Client("http://localhost", { ws: { perMessageDeflate: true } }); // @ts-ignore expect(client._settings.ws).toEqual({ maxPayload: 102400, perMessageDeflate: false }); }); it("does not reset maxPayload on socket after receiving ping message", async () => { const server = await createServerWithPlugin({ heartbeat: { interval: 20, timeout: 10 } }); await server.start(); const client = new Client("http://localhost:" + server.info.port); await client.connect({ reconnect: false }); client.onError = Hoek.ignore; client.setMaxPayload(204800); // setting here after the initial "hello" await Hoek.wait(30); // @ts-ignore expect(client._ws._receiver._maxPayload).toEqual(204800); await client.disconnect(); await server.stop(); }); describe("onError", () => { it("logs error to console by default", async () => { const server = await createServerWithPlugin(); await server.start(); const client = new Client("http://localhost:" + server.info.port); const team = new Teamwork.Team(); const orig = console.error; console.error = (err) => { expect(err).toBeDefined(); console.error = orig; client.disconnect(); team.attend(); }; await client.connect({ reconnect: false }); // @ts-ignore client._ws.emit("error", new Error("test")); await team.work; }); }); describe("connect()", () => { it("reconnects when server initially down", async () => { const server1 = await createServerWithPlugin(); await server1.start(); const port = server1.info.port; await server1.stop(); const client = new Client("http://localhost:" + port); client.onError = Hoek.ignore; const team = new Teamwork.Team({ meetings: 2 }); client.onConnect = () => { team.attend(); }; let reconnecting = false; client.onDisconnect = (willReconnect, log) => { reconnecting = willReconnect; team.attend(); }; await expect(client.connect({ delay: 10 })).rejects.toThrowError( "Connection terminated while waiting to connect", ); const server2 = await createServerWithPlugin({}, { port }); server2.route({ path: "/", method: "POST", handler: () => "ok" }); await server2.start(); await team.work; expect(reconnecting).toBeTrue(); const res = await client.request("/"); // @ts-ignore expect(res.payload).toEqual(Buffer.from("ok")); client.disconnect(); await server2.stop(); }); it("fails to connect", async () => { const client = new Client("http://0"); await expect(client.connect()).rejects.toThrowError("Connection terminated while waiting to connect"); await client.disconnect(); }); it("errors if already connected", async () => { const server = await createServerWithPlugin(); await server.start(); const client = new Client("http://localhost:" + server.info.port); await client.connect({ reconnect: false }); await expect(client.connect()).rejects.toThrowError("Already connected"); await client.disconnect(); await server.stop(); }); it("errors if set to reconnect", async () => { const server = await createServerWithPlugin(); await server.start(); const client = new Client("http://localhost:" + server.info.port); await client.connect(); await expect(client.connect()).rejects.toThrowError("Cannot connect while client attempts to reconnect"); await client.disconnect(); await server.stop(); }); }); describe("_connect()", () => { it("handles unknown error code", async () => { const server = await createServerWithPlugin(); await server.start(); const client = new Client("http://localhost:" + server.info.port); await client.connect(); const team = new Teamwork.Team(); client.onError = Hoek.ignore; client.onDisconnect = (willReconnect, log) => { expect(log.explanation).toEqual("Unknown"); client.disconnect(); team.attend(); }; // @ts-ignore client._ws.onclose({ code: 9999, reason: "bug", wasClean: false }); await team.work; await server.stop(); }); }); describe("disconnect()", () => { it("ignores when client not connected", () => { const client = new Client(undefined); client.disconnect(); }); it("ignores when client is disconnecting", async () => { const server = await createServerWithPlugin(); await server.start(); const client = new Client("http://localhost:" + server.info.port); await client.connect(); await client.disconnect(); await Hoek.wait(5); await client.disconnect(); await server.stop(); }); it("avoids closing a socket in closing state", async () => { const server = await createServerWithPlugin(); await server.start(); const client = new Client("http://localhost:" + server.info.port); await client.connect(); // @ts-ignore client._ws.close(); await client.disconnect(); await server.stop(); }); // it("closes socket while connecting", async () => { // }); it("disconnects once", async () => { const server = await createServerWithPlugin(); await server.start(); const client = new Client("http://localhost:" + server.info.port); await client.connect(); let disconnected = 0; client.onDisconnect = (willReconnect, log) => ++disconnected; client.disconnect(); client.disconnect(); await client.disconnect(); await Hoek.wait(50); expect(disconnected).toEqual(1); await server.stop(); }); it("logs manual disconnection request", async () => { const server = await createServerWithPlugin(); await server.start(); const client = new Client("http://localhost:" + server.info.port); await client.connect(); const team = new Teamwork.Team(); client.onDisconnect = (willReconnect, log) => { expect(log.wasRequested).toBeTrue(); team.attend(); }; client.disconnect(); await team.work; await server.stop(); }); it("logs error disconnection request as not requested", async () => { const server = await createServerWithPlugin(); await server.start(); const client = new Client("http://localhost:" + server.info.port); client.onError = Hoek.ignore; await client.connect(); const team = new Teamwork.Team(); client.onDisconnect = (willReconnect, log) => { expect(log.wasRequested).toBeFalse(); team.attend(); }; // @ts-ignore client._ws.close(); await team.work; await server.stop(); }); it("logs error disconnection request as not requested after manual disconnect while already disconnected", async () => { const server = await createServerWithPlugin(); await server.start(); const client = new Client("http://localhost:" + server.info.port); client.onError = Hoek.ignore; client.disconnect(); await client.connect(); const team = new Teamwork.Team(); client.onDisconnect = (willReconnect, log) => { expect(log.wasRequested).toBeFalse(); team.attend(); }; // @ts-ignore client._ws.close(); await team.work; await server.stop(); }); it("allows closing from inside request callback", async () => { const server = await createServerWithPlugin(); server.route({ method: "POST", path: "/", handler: () => "hello", }); await server.start(); const client = new Client("http://localhost:" + server.info.port); await client.connect(); await client.request("/"); client.disconnect(); await Hoek.wait(100); await server.stop(); }); }); describe("_cleanup()", () => { it("ignores when client not connected", () => { const client = new Client(undefined); // @ts-ignore client._cleanup(); }); }); describe("_reconnect()", () => { it("reconnects automatically", async () => { const server = await createServerWithPlugin(); await server.start(); const client = new Client("http://localhost:" + server.info.port); let e = 0; client.onError = (err) => { expect(err).toBeDefined(); ++e; }; const team = new Teamwork.Team(); let c = 0; client.onConnect = () => { ++c; if (c === 2) { expect(e).toEqual(0); team.attend(); } }; expect(c).toEqual(0); expect(e).toEqual(0); await client.connect({ delay: 10 }); expect(c).toEqual(1); expect(e).toEqual(0); // @ts-ignore client._ws.close(); await team.work; await client.disconnect(); await server.stop(); }); it("aborts reconnecting", async () => { const server = await createServerWithPlugin(); await server.start(); const client = new Client("http://localhost:" + server.info.port); client.onError = Hoek.ignore; let c = 0; client.onConnect = () => ++c; await client.connect({ delay: 100 }); // @ts-ignore client._ws.close(); await Hoek.wait(50); await client.disconnect(); expect(c).toEqual(1); await server.stop(); }); it("does not reconnect automatically", async () => { const server = await createServerWithPlugin(); await server.start(); const client = new Client("http://localhost:" + server.info.port); let e = 0; client.onError = (err) => { expect(err).toBeDefined(); ++e; }; let c = 0; client.onConnect = () => ++c; let r = ""; client.onDisconnect = (willReconnect, log) => { r += willReconnect ? "t" : "f"; }; expect(c).toEqual(0); expect(e).toEqual(0); await client.connect({ reconnect: false, delay: 10 }); expect(c).toEqual(1); expect(e).toEqual(0); // @ts-ignore client._ws.close(); await Hoek.wait(15); expect(c).toEqual(1); expect(r).toEqual("f"); await client.disconnect(); await server.stop(); }); it("overrides max delay", async () => { const server = await createServerWithPlugin(); await server.start(); const client = new Client("http://localhost:" + server.info.port); let c = 0; const now = Date.now(); const team = new Teamwork.Team(); client.onConnect = () => { ++c; if (c < 6) { // @ts-ignore client._ws.close(); return; } expect(Date.now() - now).toBeLessThan(150); team.attend(); }; await client.connect({ delay: 10, maxDelay: 11 }); await team.work; await client.disconnect(); await server.stop(); }); it("reconnects automatically (with errors)", async () => { const server = await createServerWithPlugin(); await server.start(); const url = "http://localhost:" + server.info.port; const client = new Client(url); let e = 0; client.onError = (err) => { expect(err).toBeDefined(); expect(err.message).toEqual("Connection terminated while waiting to connect"); expect(err.type).toEqual("ws"); expect(err.isNes).toEqual(true); ++e; // @ts-ignore client._url = "http://localhost:" + server.info.port; }; let r = ""; client.onDisconnect = (willReconnect, log) => { r += willReconnect ? "t" : "f"; }; const team = new Teamwork.Team(); let c = 0; client.onConnect = () => { ++c; if (c < 5) { // @ts-ignore client._ws.close(); if (c === 3) { // @ts-ignore client._url = "http://0"; } return; } expect(e).toEqual(1); expect(r).toEqual("ttttt"); team.attend(); }; expect(e).toEqual(0); await client.connect({ delay: 10, maxDelay: 15 }); await team.work; await client.disconnect(); await server.stop(); }); it("errors on pending request when closed", async () => { const server = await createServerWithPlugin(); server.route({ method: "POST", path: "/", handler: async () => { await Hoek.wait(10); return "hello"; }, }); await server.start(); const client = new Client("http://localhost:" + server.info.port); await client.connect(); const request = client.request("/"); await client.disconnect(); await expect(request).rejects.toThrowError("Request failed - server disconnected"); await server.stop(); }); it("times out", async () => { const server = await createServerWithPlugin(); await server.start(); const client = new Client("http://localhost:" + server.info.port); // @ts-ignore const orig = client._connect; // @ts-ignore client._connect = (...args) => { orig.apply(client, args); // @ts-ignore client._ws.onopen = null; }; let c = 0; client.onConnect = () => ++c; let e = 0; client.onError = async (err) => { ++e; expect(err).toBeDefined(); expect(err.message).toEqual("Connection timed out"); expect(err.type).toEqual("timeout"); expect(err.isNes).toEqual(true); if (e < 4) { return; } expect(c).toEqual(0); await client.disconnect(); await server.stop({ timeout: 1 }); }; await expect(client.connect({ delay: 50, maxDelay: 50, timeout: 50 })).rejects.toThrowError( "Connection timed out", ); }); it("limits retries", async () => { const server = await createServerWithPlugin(); await server.start(); const client = new Client("http://localhost:" + server.info.port); let c = 0; client.onConnect = () => { ++c; // @ts-ignore client._ws.close(); }; let r = ""; client.onDisconnect = (willReconnect, log) => { r += willReconnect ? "t" : "f"; }; await client.connect({ delay: 5, maxDelay: 10, retries: 2 }); await Hoek.wait(100); expect(c).toEqual(3); expect(r).toEqual("ttf"); await client.disconnect(); await server.stop(); }); it("aborts reconnect if disconnect is called in between attempts", async () => { const server = await createServerWithPlugin(); await server.start(); const client = new Client("http://localhost:" + server.info.port); const team = new Teamwork.Team(); let c = 0; client.onConnect = async () => { ++c; // @ts-ignore client._ws.close(); if (c === 1) { setTimeout(() => client.disconnect(), 5); await Hoek.wait(15); expect(c).toEqual(1); team.attend(); } }; await client.connect({ delay: 10 }); await team.work; await server.stop(); }); }); describe("request()", () => { it("defaults to POST", async () => { const server = await createServerWithPlugin({ headers: "*" }); server.route({ method: "POST", path: "/", handler: () => "hello", }); await server.start(); const client = new Client("http://localhost:" + server.info.port); await client.connect(); // @ts-ignore const { payload, statusCode } = await client.request({ path: "/" }); expect(payload).toEqual(Buffer.from("hello")); expect(statusCode).toEqual(200); await client.disconnect(); await server.stop(); }); it("errors when disconnected", async () => { const client = new Client(undefined); await expect(client.request("/")).rejects.toThrowError("Failed to send message - server disconnected"); }); it("errors on invalid payload", async () => { const server = await createServerWithPlugin(); server.route({ method: "POST", path: "/", handler: () => "hello", }); await server.start(); const client = new Client("http://localhost:" + server.info.port); await client.connect(); const a = { b: 1 }; await expect(client.request({ method: "POST", path: "/", payload: a })).rejects.toThrowError( /The first argument must be.*/, ); await client.disconnect(); await server.stop(); }); it("errors on invalid data", async () => { const server = await createServerWithPlugin(); server.route({ method: "POST", path: "/", handler: () => "hello", }); await server.start(); const client = new Client("http://localhost:" + server.info.port); await client.connect(); // @ts-ignore client._ws.send = () => { throw new Error("boom"); }; await expect(client.request({ method: "POST", path: "/", payload: "a" })).rejects.toThrowError("boom"); await client.disconnect(); await server.stop(); }); describe("empty response handling", () => { [ { testName: "handles empty string, no content-type", handler: (request, h) => h.response("").code(200), expectedPayload: Buffer.alloc(0), }, { testName: "handles null, no content-type", handler: () => null, expectedPayload: Buffer.alloc(0), }, { testName: "handles null, application/json", handler: (request, h) => h.response(null).type("application/json"), expectedPayload: Buffer.alloc(0), }, { testName: "handles empty string, text/plain", handler: (request, h) => h.response("").type("text/plain").code(200), expectedPayload: Buffer.alloc(0), }, { testName: "handles null, text/plain", handler: (request, h) => h.response(null).type("text/plain"), expectedPayload: Buffer.alloc(0), }, ].forEach(({ testName, handler, expectedPayload }) => { it(testName, async () => { const server = await createServerWithPlugin({ headers: "*" }); server.route({ method: "POST", path: "/", handler, }); await server.start(); const client = new Client("http://localhost:" + server.info.port); await client.connect(); // @ts-ignore const { payload } = await client.request({ path: "/" }); expect(payload).toEqual(expectedPayload); await client.disconnect(); await server.stop(); }); }); }); describe("_send()", () => { it("catches send error without tracking", async () => { const server = await createServerWithPlugin(); await server.start(); const client = new Client("http://localhost:" + server.info.port); await client.connect(); // @ts-ignore client._ws.send = () => { throw new Error("failed"); }; // @ts-ignore await expect(client._send({}, false)).rejects.toThrowError("failed"); await client.disconnect(); await server.stop(); }); }); describe("_onMessage", () => { it("ignores invalid incoming message", async () => { const server = await createServerWithPlugin({}, {}, true); server.route({ method: "POST", path: "/", handler: async (request) => { request.server.plugins.nes._listener._sockets._forEach((socket) => { socket._ws.send(Buffer.from("{")); }); await Hoek.wait(10); return "hello"; }, }); await server.start(); const client = new Client("http://localhost:" + server.info.port); let logged; client.onError = (err) => { logged = err; }; await client.connect(); await client.request("/"); expect(logged.message).toMatch(/Nes message is below minimum length/); expect(logged.type).toEqual("protocol"); expect(logged.isNes).toEqual(true); await client.disconnect(); await server.stop(); }); it("ignores incoming message with unknown id", async () => { const server = await createServerWithPlugin({}, {}, true); server.route({ method: "POST", path: "/", handler: async (request) => { request.server.plugins.nes._listener._sockets._forEach((socket) => { socket._ws.send( stringifyNesMessage({ id: 100, type: "request", statusCode: 200, payload: Buffer.from("hello"), path: "/", version: "1", socket: "socketid", heartbeat: { interval: 10000, timeout: 5000, }, }), ); }); await Hoek.wait(10); return "hello"; }, }); await server.start(); const client = new Client("http://localhost:" + server.info.port); let logged; client.onError = (err) => { logged = err; }; await client.connect(); await client.request("/"); expect(logged.message).toEqual("Received response for unknown request"); expect(logged.type).toEqual("protocol"); expect(logged.isNes).toEqual(true); await client.disconnect(); await server.stop(); }); it("ignores incoming message with undefined type", async () => { const server = await createServerWithPlugin({}, {}, true); server.route({ method: "POST", path: "/", handler: async (request) => { request.server.plugins.nes._listener._sockets._forEach((socket) => { socket._ws.send( stringifyNesMessage({ id: 2, type: "undefined", statusCode: 200, payload: Buffer.from("hello"), path: "/", version: "1", socket: "socketid", heartbeat: { interval: 10000, timeout: 5000, }, }), ); }); await Hoek.wait(10); return "hello"; }, }); await server.start(); const client = new Client("http://localhost:" + server.info.port); const team = new Teamwork.Team({ meetings: 2 }); const logged: any[] = []; client.onError = (err) => { logged.push(err); team.attend(); }; await client.connect(); await expect(client.request("/")).rejects.toThrowError("Received invalid response"); await team.work; expect(logged[0].message).toEqual("Received unknown response type: undefined"); expect(logged[0].type).toEqual("protocol"); expect(logged[0].isNes).toEqual(true); expect(logged[1].message).toEqual("Received response for unknown request"); expect(logged[1].type).toEqual("protocol"); expect(logged[1].isNes).toEqual(true); await client.disconnect(); await server.stop(); }); it("logs incoming message after timeout", async () => { const server = await createServerWithPlugin({}, {}, true); server.route({ method: "POST", path: "/", handler: async (request) => { await Hoek.wait(200); return "hello"; }, }); await server.start(); const client = new Client("http://localhost:" + server.info.port, { timeout: 20 }); let logged; client.onError = (err) => { logged = err; }; await client.connect(); await expect(client.request("/")).rejects.toThrowError("Request timed out"); await new Promise((resolve) => { setTimeout(() => { resolve(); }, 300); }); // Message received after timeout expect(logged.message).toEqual("Received response for unknown request"); expect(logged.type).toEqual("protocol"); expect(logged.isNes).toEqual(true); await client.disconnect(); await server.stop(); }); }); describe("_beat()", () => { it("disconnects when server fails to ping", async () => { const server = await createServerWithPlugin({ heartbeat: { interval: 20, timeout: 10 } }); await server.start(); const client = new Client("http://localhost:" + server.info.port); client.onError = Hoek.ignore; const team = new Teamwork.Team({ meetings: 2 }); client.onHeartbeatTimeout = (willReconnect) => { expect(willReconnect).toEqual(true); team.attend(); }; client.onDisconnect = (willReconnect, log) => { expect(willReconnect).toEqual(true); team.attend(); }; await client.connect(); clearTimeout(server.plugins.nes._listener._heartbeat); await team.work; await client.disconnect(); await server.stop(); }); it("disconnects when server fails to ping (after a few pings)", async () => { const server = await createServerWithPlugin({ heartbeat: { interval: 20, timeout: 10 } }); await server.start(); const client = new Client("http://localhost:" + server.info.port); client.onError = Hoek.ignore; const team = new Teamwork.Team(); client.onDisconnect = (willReconnect, log) => { team.attend(); }; await client.connect(); await Hoek.wait(50); clearTimeout(server.plugins.nes._listener._heartbeat); await team.work; await client.disconnect(); await server.stop(); }); }); describe("ping / pong", () => { it.each([["ping"], ["pong"]])("terminates when receiving a ws.%s", async (method) => { const server = await createServerWithPlugin({}, {}, true); server.route({ method: "POST", path: "/", handler: async (request) => { request.server.plugins.nes._listener._sockets._forEach((socket) => { setTimeout(() => socket._ws[method](), 100); }); return "hello"; }, }); await server.start(); const client = new Client("http://localhost:" + server.info.port); await client.connect(); await client.request("/"); await Hoek.wait(500); //@ts-ignore expect(client._ws).toBeNull(); // null because _cleanup() in reconnect() method await client.disconnect(); await server.stop(); }); }); }); });
the_stack
import { Injectable, Optional } from '@angular/core'; import { Router, Params, NavigationStart, NavigationEnd } from '@angular/router'; import { XhrFactory } from '@angular/common'; import { HttpBackend, HttpErrorResponse, HttpEvent, HttpRequest, HttpResponse, HttpXhrBackend, HttpHeaders } from '@angular/common/http'; import { Observable, of, throwError } from 'rxjs'; import { delay } from 'rxjs/operators'; import { pickAllPropertiesAsGetters } from './pick-properties'; import { ApiMockConfig, ApiMockService, CacheData, ApiMockRootRoute, ApiMockRoute, PartialRoutes, RouteDryMatch, ChainParam, HttpMethod, ObjectAny, ResponseOptions, ResponseOptionsLog, MockData, isFormData, ApiMockDataCallbackOptions, ApiMockResponseCallbackOptions, } from './types'; import { Status, getStatusText } from './http-status-codes'; @Injectable() export class HttpBackendService implements HttpBackend { protected isInited: boolean; protected cachedData: CacheData = {}; protected routes: ApiMockRoute[] = []; /** * Root route paths with host, but without restId. Has result of transformation: * - `part1/part2/:paramName` -> `part1/part2` * - or `https://example.com/part1/part2/:paramName` -> `https://example.com/part1/part2` * * Array of paths revert sorted by length. */ protected rootRoutes: PartialRoutes; constructor( protected apiMockService: ApiMockService, protected config: ApiMockConfig, protected xhrFactory: XhrFactory, @Optional() protected router: Router ) {} protected init() { // Merge with default configs. this.config = new ApiMockConfig(this.config); this.routes = this.apiMockService.getRoutes().filter((r) => r); this.routes.forEach((route) => this.checkRoute(route)); this.checkRootDuplicates(this.routes); this.rootRoutes = this.getRootPaths(this.routes); if (this.config.showLog && this.config.clearPrevLog && this.router) { let isLoadedApp = false; this.router.events.subscribe((event) => { if (isLoadedApp && event instanceof NavigationStart) { console.clear(); } else if (event instanceof NavigationEnd) { isLoadedApp = true; } }); } this.isInited = true; } protected checkRoute(route: ApiMockRootRoute | ApiMockRoute, parentPath?: string) { const isLastRoute = !(route.children && route.children.length); const path = route.path; const host = (route as ApiMockRootRoute).host; /** * Path with a primary key, like `one/two/:id`. */ const pathWithPk = /^(?:[\w-]+\/)+:\w+$/; const childPath = [parentPath, route.path].filter((s) => s).join(' -> '); // Nested routes should to have route.dataCallback and primary keys. if (!isLastRoute && (!route.dataCallback || !pathWithPk.test(path))) { throw new Error( `ApiMockModule detected wrong nested routes with path "${childPath}". With these routes you should to use a primary key in nested route path, for example "api/posts/:postId/comments", where ":postId" is a primary key of collection "api/posts". Also you should to have corresponding route.dataCallback.` ); } // route.dataCallback should to have corresponding a primary key, and vice versa. if ((route.dataCallback && !pathWithPk.test(path)) || (pathWithPk.test(path) && !route.dataCallback)) { throw new Error( `ApiMockModule detected wrong route with path "${childPath}". If you have route.dataCallback, you should to have corresponding a primary key, and vice versa. Also you can remove route.dataCallback if you no need any data from this route.` ); } // route.dataCallback should to have corresponding a primary key. if (path && path.slice(-1) == '/') { throw new Error( `ApiMockModule detected wrong route with path "${childPath}". route.path should not to have trailing slash.` ); } if (route.dataCallback && typeof route.dataCallback != 'function') { throw new Error(`Route dataCallback with path "${path}" is not a function`); } if (route.responseCallback && typeof route.responseCallback != 'function') { throw new Error(`Route responseCallback with path "${path}" is not a function`); } // Checking a path.host if (host && (typeof host != 'string' || host.slice(-1) == '/')) { throw new Error( `ApiMockModule detected wrong host "${host}". Any host must have a string type, and should not end with trailing slash.` ); } if (!isLastRoute) { route.children.forEach((child) => this.checkRoute(child, childPath)); } } protected checkRootDuplicates(routes: (ApiMockRootRoute | ApiMockRoute)[]) { const existingRoutes: string[] = []; const incomingRoutes = routes.map((route) => { const rootPath = route.path.split(':')[0]; return [(route as ApiMockRootRoute).host, rootPath].filter((s) => s).join(' -> '); }); incomingRoutes.forEach((incomingRoute) => { if (existingRoutes.includes(incomingRoute)) { throw new Error(`ApiMockModule detected duplicate route with path: '${incomingRoute}'`); } existingRoutes.push(incomingRoute); }); } protected getRootPaths(routes: (ApiMockRootRoute | ApiMockRoute)[]): PartialRoutes { const rootRoutes = routes.map((route, index) => { // Transformation: `https:// example.com/part1/part2/:paramName` -> `https://example.com/part1/part2` const part = route.path.split('/:')[0]; const path = [(route as ApiMockRootRoute).host, part].filter((s) => s).join('/'); const length = path.length; return { path, length, index }; }); // Revert sorting by path length. return rootRoutes.sort((a, b) => b.length - a.length); } handle(req: HttpRequest<any>): Observable<HttpEvent<any>> { try { return this.handleReq(req); } catch (err) { this.logErrorResponse(req, 'Error 500: Internal Server Error;', err); const internalErr = this.makeError(req, Status.INTERNAL_SERVER_ERROR, err.message); return throwError(internalErr); } } /** * Handles requests. */ protected handleReq(req: HttpRequest<any>): Observable<HttpEvent<any>> { if (!this.isInited) { this.init(); } const normalizedUrl = req.url.charAt(0) == '/' ? req.url.slice(1) : req.url; const routeIndex = this.findRouteIndex(this.rootRoutes, normalizedUrl); if (routeIndex == -1) { return this.send404Error(req); } const groupRouteDryMatch = this.getRouteDryMatch(normalizedUrl, this.routes[routeIndex]); if (groupRouteDryMatch.length) { for (const routeDryMatch of groupRouteDryMatch) { const chainParams = this.getChainParams(routeDryMatch); if (chainParams) { return this.sendResponse(req, chainParams); } } } return this.send404Error(req); } protected findRouteIndex(rootRoutes: PartialRoutes, url: string): number { for (const rootRoute of rootRoutes) { // We have `rootRoute.length + 1` to avoid such case: // (url) `posts-other/123` == (route) `posts/123` const partUrl = url.substr(0, rootRoute.length + 1); if (partUrl == rootRoute.path || partUrl == `${rootRoute.path}/`) { return rootRoute.index; } } return -1; } /** * This method should accepts an URL that matched to a route path by a root segment, for example: * - `root-segment/segment` and `root-segment/:routeId` * - `root-segment/segment` and `root-segment/other/:routeId`. * * Then this method splites them by `/` and compares number parts of `splitedUrl` with number parts of `splitedRoute` * and if they are equal, returns that route with some metadata. * * @param normalizedUrl If we have URL without host, here should be url with removed slash from the start. * @param rootRoute Root route from `this.routes` that matched to a URL by root path (`rootRoute.host` + `rootRoute.path`). */ protected getRouteDryMatch(normalizedUrl: string, rootRoute: ApiMockRootRoute): RouteDryMatch[] { const splitedUrl = normalizedUrl.split('/'); /** * `['posts', '123', 'comments', '456']` -> 4 parts of a URL. */ const countPartOfUrl = splitedUrl.length; const routeDryMatch: RouteDryMatch[] = []; const host = (rootRoute as ApiMockRootRoute).host || ''; setRouteDryMatch(rootRoute, host); return routeDryMatch; function setRouteDryMatch( route: ApiMockRoute, pathOfRoute?: string, routes?: ApiMockRoute[] ): RouteDryMatch | void { routes = (routes || []).slice(); routes.push(route); pathOfRoute = [pathOfRoute, route.path].filter((s) => s).join('/'); const splitedRoute = pathOfRoute.split('/'); let hasLastRestId: boolean; let lastPrimaryKey: string; /** * `['posts', ':postId', 'comments', ':commentId']` -> 4 parts of a route. */ const countPartOfRoute = splitedRoute.length; if (countPartOfUrl > countPartOfRoute) { (route.children || []).forEach((child) => setRouteDryMatch(child, pathOfRoute, routes)); return; } else if (countPartOfUrl < countPartOfRoute - 1) { // URL not matched to defined route path. return; } else if (countPartOfUrl == countPartOfRoute - 1) { const lastElement = splitedRoute.pop(); if (lastElement.charAt(0) == ':') { lastPrimaryKey = lastElement.slice(1); } else { // URL not matched to defined route path. return; } } else { // countPartOfUrl == countPartOfRoute const lastElement = splitedRoute[splitedRoute.length - 1]; if (lastElement.charAt(0) == ':') { hasLastRestId = true; lastPrimaryKey = lastElement.slice(1); } } routeDryMatch.push({ splitedUrl, splitedRoute, hasLastRestId, lastPrimaryKey, routes }); } } /** * Takes result of dry matching an URL to a route path, * so length of `splitedUrl` is always must to be equal to length of `splitedRoute`. * * This method checks that concated `splitedUrl` is matched to concated `splitedRoute`; */ protected getChainParams({ splitedUrl, splitedRoute, hasLastRestId, lastPrimaryKey, routes, }: RouteDryMatch): ChainParam[] | void { const chainParams: ChainParam[] = []; const partsOfUrl: string[] = []; const partsOfRoute: string[] = []; /** * Here `splitedRoute` like this: `['posts', ':postId', 'comments', ':commentId']`. */ splitedRoute.forEach((part, i) => { if (part.charAt(0) == ':') { const restId = splitedUrl[i] || undefined; const primaryKey = part.slice(1); /** * cacheKey should be without a restId at the end of URL, e.g. `posts` or `posts/123/comments`, * but not `posts/123` or `posts/123/comments/456`. */ const cacheKey = splitedUrl.slice(0, i).join('/'); const route = routes[chainParams.length]; chainParams.push({ cacheKey, primaryKey, restId, route }); } else { /** * Have result of transformations like this: * - `['posts', '123']` -> `['posts']` * - or `['posts', '123', 'comments', '456']` -> `['posts', 'comments']`. */ partsOfUrl.push(splitedUrl[i]); /** * Have result of transformations like this: * - `['posts', ':postId']` -> `['posts']` * - or `['posts', ':postId', 'comments', ':commentId']` -> `['posts', 'comments']`. */ partsOfRoute.push(part); } }); if (!hasLastRestId) { const lastRoute = routes[routes.length - 1]; chainParams.push({ cacheKey: splitedUrl.join('/'), primaryKey: lastPrimaryKey, route: lastRoute }); } if (partsOfRoute.join('/') == partsOfUrl.join('/')) { // Signature of a route path is matched to an URL. return chainParams; } } protected getQueryParams(req: HttpRequest<any>) { const keys = req.params.keys(); if (!keys.length) { return undefined; } const queryParams: ObjectAny = {}; keys.forEach((key) => { let values: string | string[] = req.params.getAll(key); values = values.length == 1 ? values[0] : values; queryParams[key] = values; }); return queryParams; } /** * This function: * - calls `dataCallback()` from apropriate route; * - calls `responseCallback()` from matched route and returns a result. */ protected sendResponse(req: HttpRequest<any>, chainParams: ChainParam[]): Observable<HttpResponse<any>> { const queryParams = this.getQueryParams(req); const httpMethod = req.method as HttpMethod; /** Last chain param */ const chainParam = chainParams[chainParams.length - 1]; const parents = this.getParents(req, chainParams); /** * Here we may to have "Error 404: item not found". */ if (parents instanceof HttpErrorResponse) { return throwError(parents); } let responseOptions = {} as ResponseOptions; if (chainParam.route.dataCallback) { const mockData = this.cacheDataWithGetMethod(chainParam, parents, queryParams, req.body, req.headers); responseOptions = this.callRequestMethod(req, chainParam, mockData); if (responseOptions instanceof HttpErrorResponse) { return throwError(responseOptions); } if (httpMethod != 'GET') { const opts: ApiMockDataCallbackOptions = { items: mockData.writeableData, itemId: chainParam.restId, httpMethod, parents, queryParams, reqBody: req.body, reqHeaders: this.transformHeaders(req.headers), }; const writeableData = chainParam.route.dataCallback(opts); this.cachedData[chainParam.cacheKey] = { writeableData, readonlyData: [] }; this.bindReadonlyData(chainParam, writeableData); if (this.config.cacheFromLocalStorage) { this.setToLocalStorage(chainParam.cacheKey); } } } return this.getResponse(req, chainParam, parents, queryParams, responseOptions); } /** * If cached data no exists, calls `dataCallback()` with `GET` HTTP method, * cache the result and returns it. */ protected cacheDataWithGetMethod( chainParam: ChainParam, parents?: ObjectAny[], queryParams?: Params, body?: any, headers?: HttpHeaders ) { if (this.config.cacheFromLocalStorage && !chainParam.route.ignoreDataFromLocalStorage) { this.applyDataFromLocalStorage(chainParam); } if (!this.cachedData[chainParam.cacheKey]) { const opts: ApiMockDataCallbackOptions = { items: [], itemId: chainParam.restId, httpMethod: 'GET', parents, queryParams, reqBody: body, reqHeaders: this.transformHeaders(headers), }; const writeableData = chainParam.route.dataCallback(opts); if (!Array.isArray(writeableData)) { throw new TypeError('route.dataCallback() should returns an array'); } this.cachedData[chainParam.cacheKey] = { writeableData, readonlyData: [] }; this.bindReadonlyData(chainParam, writeableData); if (this.config.cacheFromLocalStorage) { this.setToLocalStorage(chainParam.cacheKey); } } return this.cachedData[chainParam.cacheKey]; } protected applyDataFromLocalStorage(chainParam: ChainParam): void { try { const cachedData: CacheData = JSON.parse(localStorage.getItem(this.config.localStorageKey)); const cacheKey = chainParam.cacheKey; if (cachedData && cachedData[cacheKey]) { const mockData = (this.cachedData[cacheKey] = cachedData[cacheKey]); this.bindReadonlyData(chainParam, mockData.writeableData); } } catch (err) { localStorage.removeItem(this.config.localStorageKey); if (this.config.showLog) { console.log(err); console.log(`%cRemoved localStorage data with key "${this.config.localStorageKey}"`, `color: brown;`); } } } protected setToLocalStorage(cacheKey: string): void { try { const cachedData = JSON.parse(localStorage.getItem(this.config.localStorageKey)) || {}; cachedData[cacheKey] = this.clone(this.cachedData[cacheKey]); delete cachedData[cacheKey].readonlyData; localStorage.setItem(this.config.localStorageKey, JSON.stringify(cachedData)); } catch (err) { localStorage.removeItem(this.config.localStorageKey); if (this.config.showLog) { console.log(err); console.log(`%cRemoved localStorage data with key "${this.config.localStorageKey}"`, `color: brown;`); } } } protected getParents(req: HttpRequest<any>, chainParams: ChainParam[]): ObjectAny[] | HttpErrorResponse { const queryParams = this.getQueryParams(req); const parents: ObjectAny[] = []; // for() without last chainParam. for (let i = 0; i < chainParams.length - 1; i++) { const chainParam = chainParams[i]; const currParents = parents.length ? parents : undefined; const mockData = this.cacheDataWithGetMethod(chainParam, currParents, queryParams, req.body, req.headers); const primaryKey = chainParam.primaryKey; const restId = chainParam.restId; const item = mockData.writeableData.find((obj) => obj[primaryKey] && obj[primaryKey] == restId); if (!item) { const message = `Error 404: item.${primaryKey}=${restId} not found, searched in:`; this.logErrorResponse(req, message, mockData.writeableData); return this.makeError(req, Status.NOT_FOUND, 'item not found'); } parents.push(item); } return parents.length ? parents : undefined; } protected callRequestMethod( req: HttpRequest<any>, chainParam: ChainParam, mockData: MockData ): ResponseOptions | HttpErrorResponse { const httpMethod = req.method as HttpMethod; const headers = new HttpHeaders({ 'Content-Type': 'application/json' }); switch (httpMethod) { case 'GET': return this.get(req, headers, chainParam, mockData); case 'POST': return this.post(req, headers, chainParam, mockData.writeableData); case 'PUT': case 'PATCH': return this.putOrPatch(req, headers, chainParam, mockData.writeableData); case 'DELETE': return this.delete(req, headers, chainParam, mockData.writeableData); default: const errMsg = 'Error 405: Method not allowed'; this.logErrorResponse(req, errMsg); return this.makeError(req, Status.METHOD_NOT_ALLOWED, errMsg); } } protected get( req: HttpRequest<any>, headers: HttpHeaders, chainParam: ChainParam, mockData: MockData ): ResponseOptions | HttpErrorResponse { const primaryKey = chainParam.primaryKey; const restId = chainParam.restId; let body: ObjectAny[] = []; if (restId !== undefined) { const item = mockData.writeableData.find((obj) => obj[primaryKey] && obj[primaryKey] == restId); if (!item) { const message = `Error 404: item.${primaryKey}=${restId} not found, searched in:`; this.logErrorResponse(req, message, mockData.writeableData); return this.makeError(req, Status.NOT_FOUND, 'item not found'); } body = [item]; } else { body = mockData.readonlyData; } return { status: Status.OK, headers, body }; } /** * Create entity, but can update an existing entity too * if `config.postUpdate409 = false` (by default). */ protected post( req: HttpRequest<any>, headers: HttpHeaders, chainParam: ChainParam, writeableData: ObjectAny[] ): ResponseOptions | HttpErrorResponse { const item: ObjectAny = this.clone(req.body || {}); const { primaryKey, restId } = chainParam; const resourceUrl = restId ? req.url.split('/').slice(0, -1).join('/') : req.url; if (restId != undefined) { const errMsg = `Error 405: Method not allowed; POST forbidder on this URI, try on "${resourceUrl}"`; this.logErrorResponse(req, errMsg); return this.makeError(req, Status.METHOD_NOT_ALLOWED, errMsg); } if (!primaryKey) { const errMsg = `Error 400: Bad Request; POST forbidder on URI without primary key in the route`; this.logErrorResponse(req, errMsg); return this.makeError(req, Status.BAD_REQUEST, errMsg); } if (item[primaryKey] === undefined) { item[primaryKey] = this.genId(writeableData, primaryKey); } const id = item[primaryKey]; const itemIndex = writeableData.findIndex((itm: any) => itm[primaryKey] == id); if (itemIndex == -1) { writeableData.push(item); const clonedHeaders = headers.set('Location', `${resourceUrl}/${id}`); return { headers: clonedHeaders, body: item, status: Status.CREATED }; } else if (this.config.postUpdate409) { const errMsg = `Error 409: Conflict; item.${primaryKey}=${id} exists and may not be updated with POST; use PUT instead.`; this.logErrorResponse(req, errMsg); return this.makeError(req, Status.CONFLICT, errMsg); } else { writeableData[itemIndex] = item; return this.config.postUpdate204 ? { headers, status: Status.NO_CONTENT } // successful; no content : { headers, body: item, status: Status.OK }; // successful; return entity } } protected putOrPatch( req: HttpRequest<any>, headers: HttpHeaders, chainParam: ChainParam, writeableData: ObjectAny[] ): ResponseOptions | HttpErrorResponse { const update204 = req.method == 'PUT' ? this.config.putUpdate204 : this.config.patchUpdate204; const item: ObjectAny = this.clone(req.body || {}); const { primaryKey, restId } = chainParam; if (!primaryKey) { const errMsg = `Error 400: Bad Request; ${req.method} forbidder on URI without primary key in the route`; this.logErrorResponse(req, errMsg); return this.makeError(req, Status.BAD_REQUEST, errMsg); } if (item[primaryKey] == undefined) { item[primaryKey] = restId; } if (restId == undefined) { const errMsg = `Error 405: Method not allowed; ${req.method} forbidder on this URI, try on "${req.url}/:${primaryKey}"`; this.logErrorResponse(req, errMsg); return this.makeError(req, Status.METHOD_NOT_ALLOWED, errMsg); } if (restId != item[primaryKey]) { const errMsg = `Error 400: Bad request; request with resource ID ` + `"${restId}" does not match item.${primaryKey}=${item[primaryKey]}`; this.logErrorResponse(req, errMsg); return this.makeError(req, Status.BAD_REQUEST, errMsg); } const itemIndex = writeableData.findIndex((itm: any) => itm[primaryKey] == restId); if (itemIndex != -1) { if (req.method == 'PUT') { const keysFromNewItem = Object.keys(item); Object.keys(writeableData[itemIndex]).forEach((k) => { if (!keysFromNewItem.includes(k)) { delete writeableData[itemIndex][k]; } }); } Object.assign(writeableData[itemIndex], item); return update204 ? { headers, status: Status.NO_CONTENT } // successful; no content : { headers, body: item, status: Status.OK }; // successful; return entity } else if (this.config.putUpdate404 || req.method == 'PATCH') { const errMsg = `Error 404: Not found; item.${primaryKey}=${restId} ` + `not found and may not be created with ${req.method}; use POST instead.`; this.logErrorResponse(req, errMsg); return this.makeError(req, Status.NOT_FOUND, errMsg); } else { // create new item for id that not found writeableData.push(item); return { headers, body: item, status: Status.CREATED }; } } protected delete( req: HttpRequest<any>, headers: HttpHeaders, chainParam: ChainParam, writeableData: ObjectAny[] ): ResponseOptions | HttpErrorResponse { const { primaryKey, restId: id } = chainParam; if (!primaryKey) { const errMsg = `Error 400: Bad Request; DELETE forbidder on URI without primary key in the route`; this.logErrorResponse(req, errMsg); return this.makeError(req, Status.BAD_REQUEST, errMsg); } let itemIndex = -1; if (id != undefined) { itemIndex = writeableData.findIndex((itemLocal: any) => itemLocal[primaryKey] == id); } if (id == undefined || (itemIndex == -1 && this.config.deleteNotFound404)) { let errMsg = 'Error 404: Not found; '; errMsg += id ? `item.${primaryKey}=${id} not found` : `missing "${primaryKey}" field`; this.logErrorResponse(req, errMsg); return this.makeError(req, Status.NOT_FOUND, errMsg); } if (itemIndex != -1) { writeableData.splice(itemIndex, 1); } return { headers, status: Status.NO_CONTENT }; } protected getResponse( req: HttpRequest<any>, chainParam: ChainParam, parents: ObjectAny[], queryParams: Params, responseOptions: ResponseOptions = {} as any ): Observable<HttpResponse<any>> { /** The body should be always an array. */ let body: any[] = []; const anyBody: any = responseOptions.body; if (anyBody !== undefined) { body = Array.isArray(anyBody) ? anyBody : [anyBody]; } const restId = chainParam.restId; const httpMethod = req.method as HttpMethod; const clonedBody: any[] = this.clone(body); /** * Response or value of a body for response. */ let resOrBody = clonedBody; if (chainParam.route.responseCallback) { const opts: ApiMockResponseCallbackOptions = { items: clonedBody, itemId: restId, httpMethod, parents: this.clone(parents), queryParams, reqBody: this.clone(req.body), reqHeaders: this.transformHeaders(req.headers), resBody: responseOptions.body, }; resOrBody = chainParam.route.responseCallback(opts); } let observable: Observable<HttpResponse<any>>; if (resOrBody instanceof HttpErrorResponse) { this.logErrorResponse(req, resOrBody); observable = throwError(resOrBody); } else if (resOrBody instanceof HttpResponse) { observable = of(resOrBody); } else { responseOptions.status = responseOptions.status || Status.OK; responseOptions.body = resOrBody; observable = of(new HttpResponse(responseOptions)); let logHeaders: ObjectAny = {}; if (responseOptions.headers instanceof HttpHeaders) { logHeaders = this.transformHeaders(responseOptions.headers); } else if (responseOptions.headers) { logHeaders = responseOptions.headers; } const resLog: ResponseOptionsLog = { headers: logHeaders, status: responseOptions.status, body: resOrBody, }; this.logSuccessResponse(req, resLog); } return observable.pipe(delay(this.config.delay)); } /** * Generator of the next available id for item in this collection. * * @param writeableData - collection of items * @param primaryKey - a primaryKey of the collection */ protected genId(writeableData: ObjectAny[], primaryKey: string): number { const maxId = writeableData.reduce((prevId: number, item: ObjectAny) => { const currId = typeof item[primaryKey] == 'number' ? item[primaryKey] : prevId; return Math.max(prevId, currId); }, 0); return maxId + 1; } protected send404Error(req: HttpRequest<any>) { if (this.config.passThruUnknownUrl) { return new HttpXhrBackend(this.xhrFactory).handle(req); } const errMsg = 'Error 404: Not found'; this.logErrorResponse(req, errMsg); const err = this.makeError(req, Status.NOT_FOUND, errMsg); return throwError(err); } protected logRequest(req: HttpRequest<any>) { let logHeaders: ObjectAny; let queryParams: ObjectAny; let body: any; try { logHeaders = this.transformHeaders(req.headers); queryParams = this.getQueryParams(req); if (isFormData(req.body)) { body = []; req.body.forEach((value, key) => body.push({ [key]: value })); } else { body = req.body; } } catch (err) { logHeaders = { parseError: err.message || 'error' }; queryParams = { parseError: err.message || 'error' }; } let log: { headers?: ObjectAny; queryParams?: ObjectAny; body?: ObjectAny; } = {}; if (logHeaders !== undefined) { log.headers = logHeaders; } if (queryParams !== undefined) { log.queryParams = queryParams; } if (body !== undefined) { log.body = body; } if (JSON.stringify(log) == '{}') { log = '' as any; } console.log(`%creq: ${req.method} ${req.url}`, 'color: green;', log); // returns for tests only return log; } protected logResponse(res: ResponseOptionsLog) { if (res.headers && !Object.keys(res.headers).length) { delete res.headers; } if (res.body && !Object.keys(res.body).length) { delete res.body; } console.log('%cres:', `color: blue;`, res); } protected logSuccessResponse(req: HttpRequest<any>, res: ResponseOptionsLog) { if (!this.config.showLog) { return; } this.logRequest(req); this.logResponse(res); } protected logErrorResponse(req: HttpRequest<any>, ...consoleArgs: any[]) { if (!this.config.showLog) { return; } this.logRequest(req); console.log('%cres:', `color: brown;`, ...consoleArgs); } protected transformHeaders(headers: HttpHeaders) { if (!headers || !headers.keys().length) { return undefined; } const logHeaders: ObjectAny = {}; headers.keys().forEach((header) => { let values: string | string[] = headers.getAll(header); values = values.length == 1 ? values[0] : values; logHeaders[header] = values; }); return logHeaders; } protected clone(data: any) { return data === undefined ? undefined : JSON.parse(JSON.stringify(data)); } protected makeError(req: HttpRequest<any>, status: Status, errMsg: string) { return new HttpErrorResponse({ url: req.urlWithParams, status, statusText: getStatusText(status), headers: new HttpHeaders({ 'Content-Type': 'application/json' }), error: errMsg, }); } /** * Setting readonly data to `this.cachedData[cacheKey].readonlyData` */ protected bindReadonlyData(chainParam: ChainParam, writeableData: ObjectAny[]) { let readonlyData: ObjectAny[]; const pickObj = chainParam.route.propertiesForList; if (pickObj) { readonlyData = writeableData.map((d) => pickAllPropertiesAsGetters(this.clone(pickObj), d)); } else { readonlyData = writeableData.map((d) => pickAllPropertiesAsGetters(d)); } this.cachedData[chainParam.cacheKey].readonlyData = readonlyData; } }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [codepipeline](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awscodepipeline.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Codepipeline extends PolicyStatement { public servicePrefix = 'codepipeline'; /** * Statement provider for service [codepipeline](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awscodepipeline.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 view information about a specified job and whether that job has been received by the job worker * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_AcknowledgeJob.html */ public toAcknowledgeJob() { return this.to('AcknowledgeJob'); } /** * Grants permission to confirm that a job worker has received the specified job (partner actions only) * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_AcknowledgeThirdPartyJob.html */ public toAcknowledgeThirdPartyJob() { return this.to('AcknowledgeThirdPartyJob'); } /** * Grants permission to create a custom action that you can use in the pipelines associated with your AWS account * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_CreateCustomActionType.html */ public toCreateCustomActionType() { return this.to('CreateCustomActionType'); } /** * Grants permission to create a uniquely named pipeline * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_CreatePipeline.html */ public toCreatePipeline() { return this.to('CreatePipeline'); } /** * Grants permission to delete a custom action * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_DeleteCustomActionType.html */ public toDeleteCustomActionType() { return this.to('DeleteCustomActionType'); } /** * Grants permission to delete a specified pipeline * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_DeletePipeline.html */ public toDeletePipeline() { return this.to('DeletePipeline'); } /** * Grants permission to delete a specified webhook * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_DeleteWebhook.html */ public toDeleteWebhook() { return this.to('DeleteWebhook'); } /** * Grants permission to remove the registration of a webhook with the third party specified in its configuration * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_DeregisterWebhookWithThirdParty.html */ public toDeregisterWebhookWithThirdParty() { return this.to('DeregisterWebhookWithThirdParty'); } /** * Grants permission to prevent revisions from transitioning to the next stage in a pipeline * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_DisableStageTransition.html */ public toDisableStageTransition() { return this.to('DisableStageTransition'); } /** * Grants permission to allow revisions to transition to the next stage in a pipeline * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_EnableStageTransition.html */ public toEnableStageTransition() { return this.to('EnableStageTransition'); } /** * Grants permission to view information about an action type * * Access Level: Read * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_GetActionType.html */ public toGetActionType() { return this.to('GetActionType'); } /** * Grants permission to view information about a job (custom actions only) * * Access Level: Read * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_GetJobDetails.html */ public toGetJobDetails() { return this.to('GetJobDetails'); } /** * Grants permission to retrieve information about a pipeline structure * * Access Level: Read * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_GetPipeline.html */ public toGetPipeline() { return this.to('GetPipeline'); } /** * Grants permission to view information about an execution of a pipeline, including details about artifacts, the pipeline execution ID, and the name, version, and status of the pipeline * * Access Level: Read * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_GetPipelineExecution.html */ public toGetPipelineExecution() { return this.to('GetPipelineExecution'); } /** * Grants permission to view information about the current state of the stages and actions of a pipeline * * Access Level: Read * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_GetPipelineState.html */ public toGetPipelineState() { return this.to('GetPipelineState'); } /** * Grants permission to view the details of a job for a third-party action (partner actions only) * * Access Level: Read * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_GetThirdPartyJobDetails.html */ public toGetThirdPartyJobDetails() { return this.to('GetThirdPartyJobDetails'); } /** * Grants permission to list the action executions that have occurred in a pipeline * * Access Level: Read * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_ListActionExecutions.html */ public toListActionExecutions() { return this.to('ListActionExecutions'); } /** * Grants permission to list a summary of all the action types available for pipelines in your account * * Access Level: Read * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_ListActionTypes.html */ public toListActionTypes() { return this.to('ListActionTypes'); } /** * Grants permission to list a summary of the most recent executions for a pipeline * * Access Level: List * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_ListPipelineExecutions.html */ public toListPipelineExecutions() { return this.to('ListPipelineExecutions'); } /** * Grants permission to list a summary of all the pipelines associated with your AWS account * * Access Level: List * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_ListPipelines.html */ public toListPipelines() { return this.to('ListPipelines'); } /** * Grants permission to list tags for a CodePipeline resource * * Access Level: Read * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to list all of the webhooks associated with your AWS account * * Access Level: List * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_ListWebhooks.html */ public toListWebhooks() { return this.to('ListWebhooks'); } /** * Grants permission to view information about any jobs for CodePipeline to act on * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PollForJobs.html */ public toPollForJobs() { return this.to('PollForJobs'); } /** * Grants permission to determine whether there are any third-party jobs for a job worker to act on (partner actions only) * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PollForThirdPartyJobs.html */ public toPollForThirdPartyJobs() { return this.to('PollForThirdPartyJobs'); } /** * Grants permission to edit actions in a pipeline * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PutActionRevision.html */ public toPutActionRevision() { return this.to('PutActionRevision'); } /** * Grants permission to provide a response (Approved or Rejected) to a manual approval request in CodePipeline * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PutApprovalResult.html */ public toPutApprovalResult() { return this.to('PutApprovalResult'); } /** * Grants permission to represent the failure of a job as returned to the pipeline by a job worker (custom actions only) * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PutJobFailureResult.html */ public toPutJobFailureResult() { return this.to('PutJobFailureResult'); } /** * Grants permission to represent the success of a job as returned to the pipeline by a job worker (custom actions only) * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PutJobSuccessResult.html */ public toPutJobSuccessResult() { return this.to('PutJobSuccessResult'); } /** * Grants permission to represent the failure of a third-party job as returned to the pipeline by a job worker (partner actions only) * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PutThirdPartyJobFailureResult.html */ public toPutThirdPartyJobFailureResult() { return this.to('PutThirdPartyJobFailureResult'); } /** * Grants permission to represent the success of a third-party job as returned to the pipeline by a job worker (partner actions only) * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PutThirdPartyJobSuccessResult.html */ public toPutThirdPartyJobSuccessResult() { return this.to('PutThirdPartyJobSuccessResult'); } /** * Grants permission to create or update a webhook * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PutWebhook.html */ public toPutWebhook() { return this.to('PutWebhook'); } /** * Grants permission to register a webhook with the third party specified in its configuration * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_RegisterWebhookWithThirdParty.html */ public toRegisterWebhookWithThirdParty() { return this.to('RegisterWebhookWithThirdParty'); } /** * Grants permission to resume the pipeline execution by retrying the last failed actions in a stage * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_RetryStageExecution.html */ public toRetryStageExecution() { return this.to('RetryStageExecution'); } /** * Grants permission to run the most recent revision through the pipeline * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_StartPipelineExecution.html */ public toStartPipelineExecution() { return this.to('StartPipelineExecution'); } /** * Grants permission to stop an in-progress pipeline execution * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_StopPipelineExecution.html */ public toStopPipelineExecution() { return this.to('StopPipelineExecution'); } /** * Grants permission to tag a CodePipeline resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to remove a tag from a CodePipeline resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update an action type * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_UpdateActionType.html */ public toUpdateActionType() { return this.to('UpdateActionType'); } /** * Grants permission to update a pipeline with changes to the structure of the pipeline * * Access Level: Write * * https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_UpdatePipeline.html */ public toUpdatePipeline() { return this.to('UpdatePipeline'); } protected accessLevelList: AccessLevelList = { "Write": [ "AcknowledgeJob", "AcknowledgeThirdPartyJob", "CreateCustomActionType", "CreatePipeline", "DeleteCustomActionType", "DeletePipeline", "DeleteWebhook", "DeregisterWebhookWithThirdParty", "DisableStageTransition", "EnableStageTransition", "PollForJobs", "PollForThirdPartyJobs", "PutActionRevision", "PutApprovalResult", "PutJobFailureResult", "PutJobSuccessResult", "PutThirdPartyJobFailureResult", "PutThirdPartyJobSuccessResult", "PutWebhook", "RegisterWebhookWithThirdParty", "RetryStageExecution", "StartPipelineExecution", "StopPipelineExecution", "UpdateActionType", "UpdatePipeline" ], "Read": [ "GetActionType", "GetJobDetails", "GetPipeline", "GetPipelineExecution", "GetPipelineState", "GetThirdPartyJobDetails", "ListActionExecutions", "ListActionTypes", "ListTagsForResource" ], "List": [ "ListPipelineExecutions", "ListPipelines", "ListWebhooks" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type action to the statement * * https://docs.aws.amazon.com/codepipeline/latest/userguide/iam-access-control-identity-based.html#ACP_ARN_Format * * @param pipelineName - Identifier for the pipelineName. * @param stageName - Identifier for the stageName. * @param actionName - Identifier for the actionName. * @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 onAction(pipelineName: string, stageName: string, actionName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}/${ActionName}'; arn = arn.replace('${PipelineName}', pipelineName); arn = arn.replace('${StageName}', stageName); arn = arn.replace('${ActionName}', actionName); 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 actiontype to the statement * * https://docs.aws.amazon.com/codepipeline/latest/userguide/iam-access-control-identity-based.html#ACP_ARN_Format * * @param owner - Identifier for the owner. * @param category - Identifier for the category. * @param provider - Identifier for the provider. * @param version - Identifier for the version. * @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 onActiontype(owner: string, category: string, provider: string, version: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:codepipeline:${Region}:${Account}:actiontype:${Owner}/${Category}/${Provider}/${Version}'; arn = arn.replace('${Owner}', owner); arn = arn.replace('${Category}', category); arn = arn.replace('${Provider}', provider); arn = arn.replace('${Version}', version); 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 pipeline to the statement * * https://docs.aws.amazon.com/codepipeline/latest/userguide/iam-access-control-identity-based.html#ACP_ARN_Format * * @param pipelineName - Identifier for the pipelineName. * @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 onPipeline(pipelineName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}'; arn = arn.replace('${PipelineName}', pipelineName); 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 stage to the statement * * https://docs.aws.amazon.com/codepipeline/latest/userguide/iam-access-control-identity-based.html#ACP_ARN_Format * * @param pipelineName - Identifier for the pipelineName. * @param stageName - Identifier for the stageName. * @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 onStage(pipelineName: string, stageName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}'; arn = arn.replace('${PipelineName}', pipelineName); arn = arn.replace('${StageName}', stageName); 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 webhook to the statement * * https://docs.aws.amazon.com/codepipeline/latest/userguide/iam-access-control-identity-based.html#ACP_ARN_Format * * @param webhookName - Identifier for the webhookName. * @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 onWebhook(webhookName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:codepipeline:${Region}:${Account}:webhook:${WebhookName}'; arn = arn.replace('${WebhookName}', webhookName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import { Mutable, Class, Arrays, FromAny, AnyTiming, Timing, Creatable, InitType, Initable, ObserverType, } from "@swim/util"; import { Affinity, Fastener, MemberPropertyInitMap, Property, Animator, Provider, ComponentFlags, ComponentInit, Component, } from "@swim/component"; import { AnyConstraintExpression, ConstraintExpression, ConstraintVariable, ConstraintProperty, ConstraintRelation, AnyConstraintStrength, ConstraintStrength, Constraint, ConstraintScope, ConstraintContext, } from "@swim/constraint"; import {R2Box, Transform} from "@swim/math"; import { Look, Feel, Mood, MoodVectorUpdates, MoodVector, MoodMatrix, ThemeMatrix, ThemeContext, ThemeAnimator, } from "@swim/theme"; import type {ViewportIdiom} from "../viewport/ViewportIdiom"; import type {Viewport} from "../viewport/Viewport"; import {ViewportService} from "../viewport/ViewportService"; import {ViewportProvider} from "../viewport/ViewportProvider"; import {DisplayService} from "../display/DisplayService"; import {DisplayProvider} from "../display/DisplayProvider"; import {LayoutService} from "../layout/LayoutService"; import {LayoutProvider} from "../layout/LayoutProvider"; import {ThemeService} from "../theme/ThemeService"; import {ThemeProvider} from "../theme/ThemeProvider"; import {ModalService} from "../modal/ModalService"; import {ModalProvider} from "../modal/ModalProvider"; import {Gesture} from "../gesture/Gesture"; import {ViewContext} from "./ViewContext"; import type { ViewObserver, ViewWillInsertChild, ViewDidInsertChild, ViewWillRemoveChild, ViewDidRemoveChild, ViewWillResize, ViewDidResize, ViewWillScroll, ViewDidScroll, ViewWillChange, ViewDidChange, ViewWillAnimate, ViewDidAnimate, ViewWillProject, ViewDidProject, ViewWillLayout, ViewDidLayout, ViewWillRender, ViewDidRender, ViewWillRasterize, ViewDidRasterize, ViewWillComposite, ViewDidComposite, ViewObserverCache, } from "./ViewObserver"; import {ViewRelation} from "./"; // forward import /** @public */ export type ViewContextType<V extends View> = V extends {readonly contextType?: Class<infer T>} ? T : never; /** @public */ export type ViewFlags = ComponentFlags; /** @public */ export type AnyView<V extends View = View> = V | ViewFactory<V> | InitType<V>; /** @public */ export interface ViewInit extends ComponentInit { type?: Creatable<View>; key?: string; children?: AnyView[]; mood?: MoodVector; moodModifier?: MoodMatrix; theme?: ThemeMatrix; themeModifier?: MoodMatrix; } /** @public */ export interface ViewFactory<V extends View = View, U = AnyView<V>> extends Creatable<V>, FromAny<V, U> { fromInit(init: InitType<V>): V; } /** @public */ export interface ViewClass<V extends View = View, U = AnyView<V>> extends Function, ViewFactory<V, U> { readonly prototype: V; } /** @public */ export interface ViewConstructor<V extends View = View, U = AnyView<V>> extends ViewClass<V, U> { new(): V; } /** @public */ export type ViewCreator<F extends (abstract new (...args: any) => V) & Creatable<InstanceType<F>>, V extends View = View> = (abstract new (...args: any) => InstanceType<F>) & Creatable<InstanceType<F>>; /** @public */ export class View extends Component<View> implements Initable<ViewInit>, ConstraintScope, ConstraintContext, ThemeContext { constructor() { super(); this.observerCache = {}; this.constraints = Arrays.empty; this.constraintVariables = Arrays.empty; } override get componentType(): Class<View> { return View; } override readonly observerType?: Class<ViewObserver>; readonly contextType?: Class<ViewContext>; /** @internal */ override attachParent(parent: View, nextSibling: View | null): void { // assert(this.parent === null); this.willAttachParent(parent); (this as Mutable<this>).parent = parent; let previousSibling: View | null; if (nextSibling !== null) { previousSibling = nextSibling.previousSibling; this.setNextSibling(nextSibling); nextSibling.setPreviousSibling(this); } else { previousSibling = parent.lastChild; parent.setLastChild(this); } if (previousSibling !== null) { previousSibling.setNextSibling(this); this.setPreviousSibling(previousSibling); } else { parent.setFirstChild(this); } if (parent.mounted) { if (parent.culled) { this.cascadeCull(); } this.cascadeMount(); } this.onAttachParent(parent); this.didAttachParent(parent); } protected override willAttachParent(parent: View): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewWillAttachParent !== void 0) { observer.viewWillAttachParent(parent, this); } } } protected override onAttachParent(parent: View): void { // hook } protected override didAttachParent(parent: View): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewDidAttachParent !== void 0) { observer.viewDidAttachParent(parent, this); } } } protected override willDetachParent(parent: View): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewWillDetachParent !== void 0) { observer.viewWillDetachParent(parent, this); } } } protected override onDetachParent(parent: View): void { // hook } protected override didDetachParent(parent: View): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewDidDetachParent !== void 0) { observer.viewDidDetachParent(parent, this); } } } override setChild<V extends View>(key: string, newChild: V): View | null; override setChild<F extends ViewCreator<F>>(key: string, factory: F): View | null; override setChild(key: string, newChild: AnyView | null): View | null; override setChild(key: string, newChild: AnyView | null): View | null { if (newChild !== null) { newChild = View.fromAny(newChild); } return super.setChild(key, newChild) as View | null; } override appendChild<V extends View>(child: V, key?: string): V; override appendChild<F extends ViewCreator<F>>(factory: F, key?: string): InstanceType<F>; override appendChild(child: AnyView, key?: string): View; override appendChild(child: AnyView, key?: string): View { child = View.fromAny(child); return super.appendChild(child, key); } override prependChild<V extends View>(child: V, key?: string): V; override prependChild<F extends ViewCreator<F>>(factory: F, key?: string): InstanceType<F>; override prependChild(child: AnyView, key?: string): View; override prependChild(child: AnyView, key?: string): View { child = View.fromAny(child); return super.prependChild(child, key); } override insertChild<V extends View>(child: V, target: View | null, key?: string): V; override insertChild<F extends ViewCreator<F>>(factory: F, target: View | null, key?: string): InstanceType<F>; override insertChild(child: AnyView, target: View | null, key?: string): View; override insertChild(child: AnyView, target: View | null, key?: string): View { child = View.fromAny(child); return super.insertChild(child, target, key); } override replaceChild<V extends View>(newChild: View, oldChild: V): V; override replaceChild<V extends View>(newChild: AnyView, oldChild: V): V; override replaceChild(newChild: AnyView, oldChild: View): View { newChild = View.fromAny(newChild); return super.replaceChild(newChild, oldChild); } protected override willInsertChild(child: View, target: View | null): void { super.willInsertChild(child, target); const observers = this.observerCache.viewWillInsertChildObservers; if (observers !== void 0) { for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; observer.viewWillInsertChild(child, target, this); } } } protected override onInsertChild(child: View, target: View | null): void { super.onInsertChild(child, target); } protected override didInsertChild(child: View, target: View | null): void { const observers = this.observerCache.viewDidInsertChildObservers; if (observers !== void 0) { for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; observer.viewDidInsertChild(child, target, this); } } super.didInsertChild(child, target); } /** @internal */ override cascadeInsert(updateFlags?: ViewFlags, viewContext?: ViewContext): void { if ((this.flags & View.MountedFlag) !== 0) { if (updateFlags === void 0) { updateFlags = 0; } updateFlags |= this.flags & View.UpdateMask; if ((updateFlags & View.ProcessMask) !== 0) { if (viewContext === void 0) { viewContext = this.superViewContext; } this.cascadeProcess(updateFlags, viewContext); } } } protected override willRemoveChild(child: View): void { super.willRemoveChild(child); const observers = this.observerCache.viewWillRemoveChildObservers; if (observers !== void 0) { for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; observer.viewWillRemoveChild(child, this); } } } protected override onRemoveChild(child: View): void { super.onRemoveChild(child); } protected override didRemoveChild(child: View): void { const observers = this.observerCache.viewDidRemoveChildObservers; if (observers !== void 0) { for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; observer.viewDidRemoveChild(child, this); } } super.didRemoveChild(child); } /** @internal */ override mount(): void { throw new Error(); } protected override willMount(): void { super.willMount(); const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewWillMount !== void 0) { observer.viewWillMount(this); } } } protected override onMount(): void { // subsume super this.requestUpdate(this, this.flags & View.UpdateMask, false); this.requireUpdate(this.mountFlags); if (!this.culled && this.decoherent !== null && this.decoherent.length !== 0) { this.requireUpdate(View.NeedsChange | View.NeedsAnimate); } this.mountFasteners(); this.mountTheme(); this.updateTheme(false); } protected override didMount(): void { this.activateLayout(); const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewDidMount !== void 0) { observer.viewDidMount(this); } } super.didMount(); } /** @internal */ override unmount(): void { throw new Error(); } protected override willUnmount(): void { super.willUnmount(); const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewWillUnmount !== void 0) { observer.viewWillUnmount(this); } } this.deactivateLayout(); } protected override didUnmount(): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewDidUnmount !== void 0) { observer.viewDidUnmount(this); } } super.didUnmount(); } get culled(): boolean { return (this.flags & View.CulledMask) !== 0; } setCulled(culled: boolean): void { const flags = this.flags; if (culled && (flags & View.CulledFlag) === 0) { if ((flags & View.CullFlag) === 0) { this.willCull(); this.setFlags(flags | View.CulledFlag); this.onCull(); this.cullChildren(); this.didCull(); } else { this.setFlags(flags | View.CulledFlag); } } else if (!culled && (flags & View.CulledFlag) !== 0) { if ((flags & View.CullFlag) === 0) { this.willUncull(); this.setFlags(flags & ~View.CulledFlag); this.uncullChildren(); this.onUncull(); this.didUncull(); } else { this.setFlags(flags & ~View.CulledFlag); } } } /** @internal */ cascadeCull(): void { if ((this.flags & View.CullFlag) === 0) { if ((this.flags & View.CulledFlag) === 0) { this.willCull(); this.setFlags(this.flags | View.CullFlag); this.onCull(); this.cullChildren(); this.didCull(); } else { this.setFlags(this.flags | View.CullFlag); } } } protected willCull(): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewWillCull !== void 0) { observer.viewWillCull(this); } } } protected onCull(): void { // hook } protected didCull(): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewDidCull !== void 0) { observer.viewDidCull(this); } } } /** @internal */ protected cullChildren(): void { let child = this.firstChild; while (child !== null) { const next = child.nextSibling; child.cascadeCull(); if (next !== null && next.parent !== this) { throw new Error("inconsistent cull"); } child = next; } } /** @internal */ cascadeUncull(): void { if ((this.flags & View.CullFlag) !== 0) { if ((this.flags & View.CulledFlag) === 0) { this.willUncull(); this.setFlags(this.flags & ~View.CullFlag); this.uncullChildren(); this.onUncull(); this.didUncull(); } else { this.setFlags(this.flags & ~View.CullFlag); } } } get uncullFlags(): ViewFlags { return (this.constructor as typeof View).UncullFlags; } protected willUncull(): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewWillUncull !== void 0) { observer.viewWillUncull(this); } } } protected onUncull(): void { this.requestUpdate(this, this.flags & View.UpdateMask, false); this.requireUpdate(this.uncullFlags); if (this.decoherent !== null && this.decoherent.length !== 0) { this.requireUpdate(View.NeedsChange | View.NeedsAnimate); } if (this.mood.inherited) { this.mood.decohere(); } if (this.theme.inherited) { this.theme.decohere(); } } protected didUncull(): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewDidUncull !== void 0) { observer.viewDidUncull(this); } } } /** @internal */ protected uncullChildren(): void { let child = this.firstChild; while (child !== null) { const next = child.nextSibling; child.cascadeUncull(); if (next !== null && next.parent !== this) { throw new Error("inconsistent uncull"); } child = next; } } /** * Returns `true` if this view is ineligible for rendering and hit testing, * and should be excluded from its parent's layout and hit bounds. */ get hidden(): boolean { return (this.flags & View.HiddenMask) !== 0; } /** * Makes this view ineligible for rendering and hit testing, and excludes * this view from its parent's layout and hit bounds, when `hidden` is `true`. * Makes this view eligible for rendering and hit testing, and includes this * view in its parent's layout and hit bounds, when `hidden` is `false`. */ setHidden(hidden: boolean): void { const flags = this.flags; if (hidden && (flags & View.HiddenFlag) === 0) { this.setFlags(flags | View.HiddenFlag); if ((flags & View.HideFlag) === 0) { this.willHide(); this.onHide(); this.hideChildren(); this.didHide(); } } else if (!hidden && (flags & View.HiddenFlag) !== 0) { this.setFlags(flags & ~View.HiddenFlag); if ((flags & View.HideFlag) === 0) { this.willUnhide(); this.unhideChildren(); this.onUnhide(); this.didUnhide(); } } } /** @internal */ cascadeHide(): void { if ((this.flags & View.HideFlag) === 0) { if ((this.flags & View.HiddenFlag) === 0) { this.willHide(); this.setFlags(this.flags | View.HideFlag); this.onHide(); this.hideChildren(); this.didHide(); } else { this.setFlags(this.flags | View.HideFlag); } } } protected willHide(): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewWillHide !== void 0) { observer.viewWillHide(this); } } } protected onHide(): void { // hook } protected didHide(): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewDidHide !== void 0) { observer.viewDidHide(this); } } } /** @internal */ protected hideChildren(): void { let child = this.firstChild; while (child !== null) { const next = child.nextSibling; child.cascadeHide(); if (next !== null && next.parent !== this) { throw new Error("inconsistent hide"); } child = next; } } cascadeUnhide(): void { if ((this.flags & View.HideFlag) !== 0) { if ((this.flags & View.HiddenFlag) === 0) { this.willUnhide(); this.setFlags(this.flags & ~View.HideFlag); this.unhideChildren(); this.onUnhide(); this.didUnhide(); } else { this.setFlags(this.flags & ~View.HideFlag); } } } get unhideFlags(): ViewFlags { return (this.constructor as typeof View).UnhideFlags; } protected willUnhide(): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewWillUnhide !== void 0) { observer.viewWillUnhide(this); } } } protected onUnhide(): void { this.requestUpdate(this, this.flags & View.UpdateMask, false); this.requireUpdate(this.uncullFlags); } protected didUnhide(): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewDidUnhide !== void 0) { observer.viewDidUnhide(this); } } } /** @internal */ protected unhideChildren(): void { let child = this.firstChild; while (child !== null) { const next = child.nextSibling; child.cascadeUnhide(); if (next !== null && next.parent !== this) { throw new Error("inconsistent unhide"); } child = next; } } get unbounded(): boolean { return (this.flags & View.UnboundedFlag) !== 0; } setUnbounded(unboundedFlag: boolean): void { if (unboundedFlag !== ((this.flags & View.UnboundedFlag) !== 0)) { this.willSetUnbounded(unboundedFlag); if (unboundedFlag) { this.setFlags(this.flags | View.UnboundedFlag); } else { this.setFlags(this.flags & ~View.UnboundedFlag); } this.onSetUnbounded(unboundedFlag); this.didSetUnbounded(unboundedFlag); } } protected willSetUnbounded(unboundedFlag: boolean): void { // hook } protected onSetUnbounded(unboundedFlag: boolean): void { // hook } protected didSetUnbounded(unboundedFlag: boolean): void { // hook } get intangible(): boolean { return (this.flags & View.IntangibleFlag) !== 0; } setIntangible(intangible: boolean): void { if (intangible !== ((this.flags & View.IntangibleFlag) !== 0)) { this.willSetIntangible(intangible); if (intangible) { this.setFlags(this.flags | View.IntangibleFlag); } else { this.setFlags(this.flags & ~View.IntangibleFlag); } this.onSetIntangible(intangible); this.didSetIntangible(intangible); } } protected willSetIntangible(intangible: boolean): void { // hook } protected onSetIntangible(intangible: boolean): void { // hook } protected didSetIntangible(intangible: boolean): void { // hook } override requireUpdate(updateFlags: ViewFlags, immediate: boolean = false): void { const flags = this.flags; const deltaUpdateFlags = updateFlags & ~flags & View.UpdateMask; if (deltaUpdateFlags !== 0) { this.setFlags(flags | deltaUpdateFlags); this.requestUpdate(this, deltaUpdateFlags, immediate); } } protected needsUpdate(updateFlags: ViewFlags, immediate: boolean): ViewFlags { return updateFlags; } requestUpdate(target: View, updateFlags: ViewFlags, immediate: boolean): void { if ((this.flags & View.CulledMask) !== View.CulledFlag) { // if not culled root updateFlags = this.needsUpdate(updateFlags, immediate); let deltaUpdateFlags = this.flags & ~updateFlags & View.UpdateMask; if ((updateFlags & View.ProcessMask) !== 0) { deltaUpdateFlags |= View.NeedsProcess; } if ((updateFlags & View.DisplayMask) !== 0) { deltaUpdateFlags |= View.NeedsDisplay; } if (deltaUpdateFlags !== 0 || immediate) { this.setFlags(this.flags | deltaUpdateFlags); const parent = this.parent; if (parent !== null) { parent.requestUpdate(target, updateFlags, immediate); } else if (this.mounted) { const displayService = this.displayProvider.service; if (displayService !== void 0 && displayService !== null) { displayService.requestUpdate(target, updateFlags, immediate); } } } } } get updating(): boolean { return (this.flags & View.UpdatingMask) !== 0; } get processing(): boolean { return (this.flags & View.ProcessingFlag) !== 0; } protected needsProcess(processFlags: ViewFlags, viewContext: ViewContextType<this>): ViewFlags { return processFlags; } cascadeProcess(processFlags: ViewFlags, baseViewContext: ViewContext): void { const viewContext = this.extendViewContext(baseViewContext); const outerViewContext = ViewContext.current; try { ViewContext.current = viewContext; processFlags &= ~View.NeedsProcess; processFlags |= this.flags & View.UpdateMask; processFlags = this.needsProcess(processFlags, viewContext); if ((processFlags & View.ProcessMask) !== 0) { let cascadeFlags = processFlags; this.setFlags(this.flags & ~View.NeedsProcess | (View.ProcessingFlag | View.ContextualFlag)); this.willProcess(cascadeFlags, viewContext); if (((this.flags | processFlags) & View.NeedsResize) !== 0) { cascadeFlags |= View.NeedsResize; this.setFlags(this.flags & ~View.NeedsResize); this.willResize(viewContext); } if (((this.flags | processFlags) & View.NeedsScroll) !== 0) { cascadeFlags |= View.NeedsScroll; this.setFlags(this.flags & ~View.NeedsScroll); this.willScroll(viewContext); } if (((this.flags | processFlags) & View.NeedsChange) !== 0) { cascadeFlags |= View.NeedsChange; this.setFlags(this.flags & ~View.NeedsChange); this.willChange(viewContext); } if (((this.flags | processFlags) & View.NeedsAnimate) !== 0) { cascadeFlags |= View.NeedsAnimate; this.setFlags(this.flags & ~View.NeedsAnimate); this.willAnimate(viewContext); } if (((this.flags | processFlags) & View.NeedsProject) !== 0) { cascadeFlags |= View.NeedsProject; this.setFlags(this.flags & ~View.NeedsProject); this.willProject(viewContext); } this.onProcess(cascadeFlags, viewContext); if ((cascadeFlags & View.NeedsResize) !== 0) { this.onResize(viewContext); } if ((cascadeFlags & View.NeedsScroll) !== 0) { this.onScroll(viewContext); } if ((cascadeFlags & View.NeedsChange) !== 0) { this.onChange(viewContext); } if ((cascadeFlags & View.NeedsAnimate) !== 0) { this.onAnimate(viewContext); } if ((cascadeFlags & View.NeedsProject) !== 0) { this.onProject(viewContext); } if ((cascadeFlags & View.ProcessMask) !== 0) { this.setFlags(this.flags & ~View.ContextualFlag); this.processChildren(cascadeFlags, viewContext, this.processChild); this.setFlags(this.flags | View.ContextualFlag); } if ((cascadeFlags & View.NeedsProject) !== 0) { this.didProject(viewContext); } if ((cascadeFlags & View.NeedsAnimate) !== 0) { this.didAnimate(viewContext); } if ((cascadeFlags & View.NeedsChange) !== 0) { this.didChange(viewContext); } if ((cascadeFlags & View.NeedsScroll) !== 0) { this.didScroll(viewContext); } if ((cascadeFlags & View.NeedsResize) !== 0) { this.didResize(viewContext); } this.didProcess(cascadeFlags, viewContext); } } finally { this.setFlags(this.flags & ~(View.ProcessingFlag | View.ContextualFlag)); ViewContext.current = outerViewContext; } } protected willProcess(processFlags: ViewFlags, viewContext: ViewContextType<this>): void { // hook } protected onProcess(processFlags: ViewFlags, viewContext: ViewContextType<this>): void { // hook } protected didProcess(processFlags: ViewFlags, viewContext: ViewContextType<this>): void { // hook } protected willResize(viewContext: ViewContextType<this>): void { const observers = this.observerCache.viewWillResizeObservers; if (observers !== void 0) { for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; observer.viewWillResize(viewContext, this); } } this.evaluateConstraintVariables(); } protected onResize(viewContext: ViewContextType<this>): void { // hook } protected didResize(viewContext: ViewContextType<this>): void { const observers = this.observerCache.viewDidResizeObservers; if (observers !== void 0) { for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; observer.viewDidResize(viewContext, this); } } } protected willScroll(viewContext: ViewContextType<this>): void { const observers = this.observerCache.viewWillScrollObservers; if (observers !== void 0) { for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; observer.viewWillScroll(viewContext, this); } } } protected onScroll(viewContext: ViewContextType<this>): void { // hook } protected didScroll(viewContext: ViewContextType<this>): void { const observers = this.observerCache.viewDidScrollObservers; if (observers !== void 0) { for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; observer.viewDidScroll(viewContext, this); } } } protected willChange(viewContext: ViewContextType<this>): void { const observers = this.observerCache.viewWillChangeObservers; if (observers !== void 0) { for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; observer.viewWillChange(viewContext, this); } } } protected onChange(viewContext: ViewContextType<this>): void { this.updateTheme(); this.recohereFasteners(viewContext.updateTime); } protected didChange(viewContext: ViewContextType<this>): void { const observers = this.observerCache.viewDidChangeObservers; if (observers !== void 0) { for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; observer.viewDidChange(viewContext, this); } } } protected willAnimate(viewContext: ViewContextType<this>): void { const observers = this.observerCache.viewWillAnimateObservers; if (observers !== void 0) { for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; observer.viewWillAnimate(viewContext, this); } } } protected onAnimate(viewContext: ViewContextType<this>): void { this.recohereAnimators(viewContext.updateTime); } protected didAnimate(viewContext: ViewContextType<this>): void { const observers = this.observerCache.viewDidAnimateObservers; if (observers !== void 0) { for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; observer.viewDidAnimate(viewContext, this); } } } protected willProject(viewContext: ViewContextType<this>): void { const observers = this.observerCache.viewWillProjectObservers; if (observers !== void 0) { for (let i = 0; i < observers.length; i += 1) { const observer = observers[i]!; observer.viewWillProject(viewContext, this); } } } protected onProject(viewContext: ViewContextType<this>): void { // hook } protected didProject(viewContext: ViewContextType<this>): void { const observers = this.observerCache.viewDidProjectObservers; if (observers !== void 0) { for (let i = 0; i < observers.length; i += 1) { const observer = observers[i]!; observer.viewDidProject(viewContext, this); } } } protected processChildren(processFlags: ViewFlags, viewContext: ViewContextType<this>, processChild: (this: this, child: View, processFlags: ViewFlags, viewContext: ViewContextType<this>) => void): void { let child = this.firstChild; while (child !== null) { const next = child.nextSibling; processChild.call(this, child, processFlags, viewContext); if (next !== null && next.parent !== this) { throw new Error("inconsistent process pass"); } child = next; } } protected processChild(child: View, processFlags: ViewFlags, viewContext: ViewContextType<this>): void { child.cascadeProcess(processFlags, viewContext); } get displaying(): boolean { return (this.flags & View.DisplayingFlag) !== 0; } protected needsDisplay(displayFlags: ViewFlags, viewContext: ViewContextType<this>): ViewFlags { return displayFlags; } cascadeDisplay(displayFlags: ViewFlags, baseViewContext: ViewContext): void { const viewContext = this.extendViewContext(baseViewContext); const outerViewContext = ViewContext.current; try { ViewContext.current = viewContext; displayFlags &= ~View.NeedsDisplay; displayFlags |= this.flags & View.UpdateMask; displayFlags = this.needsDisplay(displayFlags, viewContext); if ((displayFlags & View.DisplayMask) !== 0) { let cascadeFlags = displayFlags; this.setFlags(this.flags & ~View.NeedsDisplay | (View.DisplayingFlag | View.ContextualFlag)); this.willDisplay(cascadeFlags, viewContext); if (((this.flags | displayFlags) & View.NeedsLayout) !== 0) { cascadeFlags |= View.NeedsLayout; this.setFlags(this.flags & ~View.NeedsLayout); this.willLayout(viewContext); } if (((this.flags | displayFlags) & View.NeedsRender) !== 0) { cascadeFlags |= View.NeedsRender; this.setFlags(this.flags & ~View.NeedsRender); this.willRender(viewContext); } if (((this.flags | displayFlags) & View.NeedsRasterize) !== 0) { cascadeFlags |= View.NeedsRasterize; this.setFlags(this.flags & ~View.NeedsRasterize); this.willRasterize(viewContext); } if (((this.flags | displayFlags) & View.NeedsComposite) !== 0) { cascadeFlags |= View.NeedsComposite; this.setFlags(this.flags & ~View.NeedsComposite); this.willComposite(viewContext); } this.onDisplay(cascadeFlags, viewContext); if ((cascadeFlags & View.NeedsLayout) !== 0) { this.onLayout(viewContext); } if ((cascadeFlags & View.NeedsRender) !== 0) { this.onRender(viewContext); } if ((cascadeFlags & View.NeedsRasterize) !== 0) { this.onRasterize(viewContext); } if ((cascadeFlags & View.NeedsComposite) !== 0) { this.onComposite(viewContext); } if ((cascadeFlags & View.DisplayMask) !== 0 && !this.hidden && !this.culled) { this.setFlags(this.flags & ~View.ContextualFlag); this.displayChildren(cascadeFlags, viewContext, this.displayChild); this.setFlags(this.flags | View.ContextualFlag); } if ((cascadeFlags & View.NeedsComposite) !== 0) { this.didComposite(viewContext); } if ((cascadeFlags & View.NeedsRasterize) !== 0) { this.didRasterize(viewContext); } if ((cascadeFlags & View.NeedsRender) !== 0) { this.didRender(viewContext); } if ((cascadeFlags & View.NeedsLayout) !== 0) { this.didLayout(viewContext); } this.didDisplay(cascadeFlags, viewContext); } } finally { this.setFlags(this.flags & ~(View.DisplayingFlag | View.ContextualFlag)); ViewContext.current = outerViewContext; } } protected willDisplay(displayFlags: ViewFlags, viewContext: ViewContextType<this>): void { // hook } protected onDisplay(displayFlags: ViewFlags, viewContext: ViewContextType<this>): void { // hook } protected didDisplay(displayFlags: ViewFlags, viewContext: ViewContextType<this>): void { // hook } protected willLayout(viewContext: ViewContextType<this>): void { const observers = this.observerCache.viewWillLayoutObservers; if (observers !== void 0) { for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; observer.viewWillLayout(viewContext, this); } } } protected onLayout(viewContext: ViewContextType<this>): void { // hook } protected didLayout(viewContext: ViewContextType<this>): void { const observers = this.observerCache.viewDidLayoutObservers; if (observers !== void 0) { for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; observer.viewDidLayout(viewContext, this); } } } protected willRender(viewContext: ViewContextType<this>): void { const observers = this.observerCache.viewWillRenderObservers; if (observers !== void 0) { for (let i = 0; i < observers.length; i += 1) { const observer = observers[i]!; observer.viewWillRender(viewContext, this); } } } protected onRender(viewContext: ViewContextType<this>): void { // hook } protected didRender(viewContext: ViewContextType<this>): void { const observers = this.observerCache.viewDidRenderObservers; if (observers !== void 0) { for (let i = 0; i < observers.length; i += 1) { const observer = observers[i]!; observer.viewDidRender(viewContext, this); } } } protected willRasterize(viewContext: ViewContextType<this>): void { const observers = this.observerCache.viewWillRasterizeObservers; if (observers !== void 0) { for (let i = 0; i < observers.length; i += 1) { const observer = observers[i]!; observer.viewWillRasterize(viewContext, this); } } } protected onRasterize(viewContext: ViewContextType<this>): void { // hook } protected didRasterize(viewContext: ViewContextType<this>): void { const observers = this.observerCache.viewDidRasterizeObservers; if (observers !== void 0) { for (let i = 0; i < observers.length; i += 1) { const observer = observers[i]!; observer.viewDidRasterize(viewContext, this); } } } protected willComposite(viewContext: ViewContextType<this>): void { const observers = this.observerCache.viewWillCompositeObservers; if (observers !== void 0) { for (let i = 0; i < observers.length; i += 1) { const observer = observers[i]!; observer.viewWillComposite(viewContext, this); } } } protected onComposite(viewContext: ViewContextType<this>): void { // hook } protected didComposite(viewContext: ViewContextType<this>): void { const observers = this.observerCache.viewDidCompositeObservers; if (observers !== void 0) { for (let i = 0; i < observers.length; i += 1) { const observer = observers[i]!; observer.viewDidComposite(viewContext, this); } } } protected displayChildren(displayFlags: ViewFlags, viewContext: ViewContextType<this>, displayChild: (this: this, child: View, displayFlags: ViewFlags, viewContext: ViewContextType<this>) => void): void { let child = this.firstChild; while (child !== null) { const next = child.nextSibling; displayChild.call(this, child, displayFlags, viewContext); if (next !== null && next.parent !== this) { throw new Error("inconsistent display pass"); } child = next; } } protected displayChild(child: View, displayFlags: ViewFlags, viewContext: ViewContextType<this>): void { child.cascadeDisplay(displayFlags, viewContext); } @Provider({ extends: ViewportProvider, type: ViewportService, observes: false, service: ViewportService.global(), }) readonly viewportProvider!: ViewportProvider<this>; @Provider({ extends: DisplayProvider, type: DisplayService, observes: false, service: DisplayService.global(), }) readonly displayProvider!: DisplayProvider<this>; @Provider({ extends: LayoutProvider, type: LayoutService, observes: false, service: LayoutService.global(), }) readonly layoutProvider!: LayoutProvider<this>; @Provider({ extends: ThemeProvider, type: ThemeService, observes: false, service: ThemeService.global(), }) readonly themeProvider!: ThemeProvider<this>; @Provider({ extends: ModalProvider, type: ModalService, observes: false, service: ModalService.global(), }) readonly modalProvider!: ModalProvider<this>; @Property({type: MoodVector, value: null, inherits: true}) readonly mood!: Property<this, MoodVector | null>; @Property({type: ThemeMatrix, value: null, inherits: true}) readonly theme!: Property<this, ThemeMatrix | null>; /** @override */ getLook<T>(look: Look<T, unknown>, mood?: MoodVector<Feel> | null): T | undefined { const theme = this.theme.value; let value: T | undefined; if (theme !== null) { if (mood === void 0 || mood === null) { mood = this.mood.value; } if (mood !== null) { value = theme.get(look, mood); } } return value; } /** @override */ getLookOr<T, E>(look: Look<T, unknown>, elseValue: E): T | E; /** @override */ getLookOr<T, E>(look: Look<T, unknown>, mood: MoodVector<Feel> | null, elseValue: E): T | E; getLookOr<T, E>(look: Look<T, unknown>, mood: MoodVector<Feel> | null | E, elseValue?: E): T | E { if (arguments.length === 2) { elseValue = mood as E; mood = null; } const theme = this.theme.value; let value: T | E; if (theme !== null) { if (mood === void 0 || mood === null) { mood = this.mood.value; } if (mood !== null) { value = theme.getOr(look, mood as MoodVector<Feel>, elseValue as E); } else { value = elseValue as E; } } else { value = elseValue as E; } return value; } /** @internal */ applyTheme(theme: ThemeMatrix, mood: MoodVector, timing?: AnyTiming | boolean): void { if (timing === void 0 || timing === true) { timing = theme.getOr(Look.timing, Mood.ambient, false); } else { timing = Timing.fromAny(timing); } this.willApplyTheme(theme, mood, timing as Timing | boolean); this.onApplyTheme(theme, mood, timing as Timing | boolean); this.didApplyTheme(theme, mood, timing as Timing | boolean); } protected willApplyTheme(theme: ThemeMatrix, mood: MoodVector, timing: Timing | boolean): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewWillApplyTheme !== void 0) { observer.viewWillApplyTheme(theme, mood, timing, this); } } } protected onApplyTheme(theme: ThemeMatrix, mood: MoodVector, timing: Timing | boolean): void { this.themeAnimators(theme, mood, timing); } protected didApplyTheme(theme: ThemeMatrix, mood: MoodVector, timing: Timing | boolean): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewDidApplyTheme !== void 0) { observer.viewDidApplyTheme(theme, mood, timing, this); } } } /** @internal */ protected themeAnimators(theme: ThemeMatrix, mood: MoodVector, timing: Timing | boolean): void { const fasteners = this.fasteners; for (const fastenerName in fasteners) { const fastener = fasteners[fastenerName]!; if (fastener instanceof ThemeAnimator) { fastener.applyTheme(theme, mood, timing); } } } @Property({type: MoodMatrix, value: null}) readonly moodModifier!: Property<this, MoodMatrix | null>; @Property({type: MoodMatrix, value: null}) readonly themeModifier!: Property<this, MoodMatrix | null>; /** @internal */ modifyMood(feel: Feel, updates: MoodVectorUpdates<Feel>, timing?: AnyTiming | boolean): void { if (this.moodModifier.hasAffinity(Affinity.Intrinsic)) { const oldMoodModifier = this.moodModifier.getValueOr(MoodMatrix.empty()); const newMoodModifier = oldMoodModifier.updatedCol(feel, updates, true); if (!newMoodModifier.equals(oldMoodModifier)) { this.moodModifier.setValue(newMoodModifier, Affinity.Intrinsic); this.changeMood(); if (timing !== void 0) { const theme = this.theme.value; const mood = this.mood.value; if (theme !== null && mood !== null) { if (timing === true) { timing = theme.getOr(Look.timing, mood, false); } else { timing = Timing.fromAny(timing); } this.applyTheme(theme, mood, timing); } } else { this.requireUpdate(View.NeedsChange); } } } } /** @internal */ modifyTheme(feel: Feel, updates: MoodVectorUpdates<Feel>, timing?: AnyTiming | boolean): void { if (this.themeModifier.hasAffinity(Affinity.Intrinsic)) { const oldThemeModifier = this.themeModifier.getValueOr(MoodMatrix.empty()); const newThemeModifier = oldThemeModifier.updatedCol(feel, updates, true); if (!newThemeModifier.equals(oldThemeModifier)) { this.themeModifier.setValue(newThemeModifier, Affinity.Intrinsic); this.changeTheme(); if (timing !== void 0) { const theme = this.theme.value; const mood = this.mood.value; if (theme !== null && mood !== null) { if (timing === true) { timing = theme.getOr(Look.timing, mood, false); } else { timing = Timing.fromAny(timing); } this.applyTheme(theme, mood, timing); } } else { this.requireUpdate(View.NeedsChange); } } } } /** @internal */ protected changeMood(): void { const moodModifierProperty = this.getFastener("moodModifier", Property) as Property<this, MoodMatrix | null> | null; if (moodModifierProperty !== null && this.mood.hasAffinity(Affinity.Intrinsic)) { const moodModifier = moodModifierProperty.value; if (moodModifier !== null) { let superMood = this.mood.superValue; if (superMood === void 0 || superMood === null) { const themeService = this.themeProvider.service; if (themeService !== void 0 && themeService !== null) { superMood = themeService.mood; } } if (superMood !== void 0 && superMood !== null) { const mood = moodModifier.timesCol(superMood, true); this.mood.setValue(mood, Affinity.Intrinsic); } } else { this.mood.setAffinity(Affinity.Inherited); } } } /** @internal */ protected changeTheme(): void { const themeModifierProperty = this.getFastener("themeModifier", Property) as Property<this, MoodMatrix | null> | null; if (themeModifierProperty !== null && this.theme.hasAffinity(Affinity.Intrinsic)) { const themeModifier = themeModifierProperty.value; if (themeModifier !== null) { let superTheme = this.theme.superValue; if (superTheme === void 0 || superTheme === null) { const themeService = this.themeProvider.service; if (themeService !== void 0 && themeService !== null) { superTheme = themeService.theme; } } if (superTheme !== void 0 && superTheme !== null) { const theme = superTheme.transform(themeModifier, true); this.theme.setValue(theme, Affinity.Intrinsic); } } else { this.theme.setAffinity(Affinity.Inherited); } } } /** @internal */ protected updateTheme(timing?: AnyTiming | boolean): void { this.changeMood(); this.changeTheme(); const theme = this.theme.value; const mood = this.mood.value; if (theme !== null && mood !== null) { this.applyTheme(theme, mood, timing); } } /** @internal */ protected mountTheme(): void { // hook } /** @internal */ protected override bindChildFastener(fastener: Fastener, child: View, target: View | null): void { super.bindChildFastener(fastener, child, target); if (fastener instanceof ViewRelation || fastener instanceof Gesture) { fastener.bindView(child, target); } } /** @internal */ protected override unbindChildFastener(fastener: Fastener, child: View): void { if (fastener instanceof ViewRelation || fastener instanceof Gesture) { fastener.unbindView(child); } super.unbindChildFastener(fastener, child); } /** @internal @override */ override decohereFastener(fastener: Fastener): void { super.decohereFastener(fastener); if (fastener instanceof Animator) { this.requireUpdate(View.NeedsAnimate); } else { this.requireUpdate(View.NeedsChange); } } /** @internal */ override recohereFasteners(t?: number): void { const decoherent = this.decoherent; if (decoherent !== null) { const decoherentCount = decoherent.length; if (decoherentCount !== 0) { if (t === void 0) { t = performance.now(); } (this as Mutable<this>).decoherent = null; for (let i = 0; i < decoherentCount; i += 1) { const fastener = decoherent[i]!; if (!(fastener instanceof Animator)) { fastener.recohere(t); } else { this.decohereFastener(fastener); } } } } } /** @internal */ recohereAnimators(t: number): void { const decoherent = this.decoherent; if (decoherent !== null) { const decoherentCount = decoherent.length; if (decoherentCount !== 0) { (this as Mutable<this>).decoherent = null; for (let i = 0; i < decoherentCount; i += 1) { const fastener = decoherent[i]!; if (fastener instanceof Animator) { fastener.recohere(t); } else { this.decohereFastener(fastener); } } } } } /** @override */ constraint(lhs: AnyConstraintExpression, relation: ConstraintRelation, rhs?: AnyConstraintExpression, strength?: AnyConstraintStrength): Constraint { lhs = ConstraintExpression.fromAny(lhs); if (rhs !== void 0) { rhs = ConstraintExpression.fromAny(rhs); } const expression = rhs !== void 0 ? lhs.minus(rhs) : lhs; if (strength === void 0) { strength = ConstraintStrength.Required; } else { strength = ConstraintStrength.fromAny(strength); } const constraint = new Constraint(this, expression, relation, strength); this.addConstraint(constraint); return constraint; } /** @internal */ readonly constraints: ReadonlyArray<Constraint>; /** @override */ hasConstraint(constraint: Constraint): boolean { return this.constraints.indexOf(constraint) >= 0; } /** @override */ addConstraint(constraint: Constraint): void { const oldConstraints = this.constraints; const newConstraints = Arrays.inserted(constraint, oldConstraints); if (oldConstraints !== newConstraints) { (this as Mutable<this>).constraints = newConstraints; this.activateConstraint(constraint); } } /** @override */ removeConstraint(constraint: Constraint): void { const oldConstraints = this.constraints; const newConstraints = Arrays.removed(constraint, oldConstraints); if (oldConstraints !== newConstraints) { this.deactivateConstraint(constraint); (this as Mutable<this>).constraints = newConstraints; } } /** @internal @override */ activateConstraint(constraint: Constraint): void { const layoutService = this.layoutProvider.service; if (layoutService !== void 0 && layoutService !== null) { layoutService.activateConstraint(constraint); this.requireUpdate(View.NeedsLayout); } } /** @internal @override */ deactivateConstraint(constraint: Constraint): void { const layoutService = this.layoutProvider.service; if (layoutService !== void 0 && layoutService !== null) { layoutService.deactivateConstraint(constraint); this.requireUpdate(View.NeedsLayout); } } /** @override */ constraintVariable(name: string, value?: number, strength?: AnyConstraintStrength): ConstraintProperty<unknown, number> { if (value === void 0) { value = 0; } if (strength !== void 0) { strength = ConstraintStrength.fromAny(strength); } else { strength = ConstraintStrength.Strong; } const property = ConstraintProperty.create(this) as ConstraintProperty<unknown, number>; Object.defineProperty(property, "name", { value: name, configurable: true, }); if (value !== void 0) { property.setValue(value); } property.setStrength(strength); property.mount(); return property; } /** @internal */ readonly constraintVariables: ReadonlyArray<ConstraintVariable>; /** @override */ hasConstraintVariable(constraintVariable: ConstraintVariable): boolean { return this.constraintVariables.indexOf(constraintVariable) >= 0; } /** @override */ addConstraintVariable(constraintVariable: ConstraintVariable): void { const oldConstraintVariables = this.constraintVariables; const newConstraintVariables = Arrays.inserted(constraintVariable, oldConstraintVariables); if (oldConstraintVariables !== newConstraintVariables) { (this as Mutable<this>).constraintVariables = newConstraintVariables; this.activateConstraintVariable(constraintVariable); } } /** @override */ removeConstraintVariable(constraintVariable: ConstraintVariable): void { const oldConstraintVariables = this.constraintVariables; const newConstraintVariables = Arrays.removed(constraintVariable, oldConstraintVariables); if (oldConstraintVariables !== newConstraintVariables) { this.deactivateConstraintVariable(constraintVariable); (this as Mutable<this>).constraintVariables = newConstraintVariables; } } /** @internal @override */ activateConstraintVariable(constraintVariable: ConstraintVariable): void { const layoutService = this.layoutProvider.service; if (layoutService !== void 0 && layoutService !== null) { layoutService.activateConstraintVariable(constraintVariable); this.requireUpdate(View.NeedsLayout); } } /** @internal @override */ deactivateConstraintVariable(constraintVariable: ConstraintVariable): void { const layoutService = this.layoutProvider.service; if (layoutService !== void 0 && layoutService !== null) { layoutService.deactivateConstraintVariable(constraintVariable); this.requireUpdate(View.NeedsLayout); } } /** @internal @override */ setConstraintVariable(constraintVariable: ConstraintVariable, value: number): void { const layoutService = this.layoutProvider.service; if (layoutService !== void 0 && layoutService !== null) { layoutService.setConstraintVariable(constraintVariable, value); } } /** @internal */ evaluateConstraintVariables(): void { const constraintVariables = this.constraintVariables; for (let i = 0, n = constraintVariables.length; i < n; i += 1) { const constraintVariable = constraintVariables[i]!; constraintVariable.evaluateConstraintVariable(); } } /** @internal */ protected activateLayout(): void { const layoutService = this.layoutProvider.service; if (layoutService !== void 0 && layoutService !== null) { const constraints = this.constraints; for (let i = 0, n = constraints.length; i < n; i += 1) { layoutService.activateConstraint(constraints[i]!); } } } /** @internal */ protected deactivateLayout(): void { const layoutService = this.layoutProvider.service; if (layoutService !== void 0 && layoutService !== null) { const constraints = this.constraints; for (let i = 0, n = constraints.length; i < n; i += 1) { layoutService.deactivateConstraint(constraints[i]!); } } } /** @internal */ setProperty(key: string, value: unknown, timing?: AnyTiming | boolean | null, affinity?: Affinity): void { const property = this.getLazyFastener(key, Property); if (property !== null) { if (property instanceof Animator) { property.setState(value, timing, affinity); } else { property.setValue(value, affinity); } } } setProperties(properties: MemberPropertyInitMap<this>, timingOrAffinity: Affinity | AnyTiming | boolean | null | undefined): void; setProperties(properties: MemberPropertyInitMap<this>, timing?: AnyTiming | boolean | null, affinity?: Affinity): void; setProperties(properties: MemberPropertyInitMap<this>, timing?: Affinity | AnyTiming | boolean | null, affinity?: Affinity): void { if (typeof timing === "number") { affinity = timing; timing = void 0; } for (const key in properties) { const value = properties[key]; this.setProperty(key, value, timing, affinity); } } /** @internal */ get superViewContext(): ViewContext { const parent = this.parent; if (parent !== null) { return parent.viewContext; } else { const viewContext = this.viewportProvider.viewContext; return this.displayProvider.updatedViewContext(viewContext); } } /** @internal */ extendViewContext(viewContext: ViewContext): ViewContextType<this> { return viewContext as ViewContextType<this>; } get viewContext(): ViewContextType<this> { if ((this.flags & View.ContextualFlag) !== 0) { return ViewContext.current as ViewContextType<this>; } else { return this.extendViewContext(this.superViewContext); } } get viewportIdiom(): ViewportIdiom { return this.viewContext.viewportIdiom; } get viewport(): Viewport { return this.viewContext.viewport; } /** * Returns the transformation from the parent view coordinates to view * coordinates. */ get parentTransform(): Transform { return Transform.identity(); } /** * Returns the transformation from page coordinates to view coordinates. */ get pageTransform(): Transform { const parent = this.parent; if (parent !== null) { return parent.pageTransform.transform(this.parentTransform); } else { return Transform.identity(); } } get pageBounds(): R2Box { const clientBounds = this.clientBounds; const clientTransform = this.clientTransform; return clientBounds.transform(clientTransform); } /** * Returns the bounding box, in page coordinates, the edges to which attached * popovers should point. */ get popoverFrame(): R2Box { return this.pageBounds; } /** * Returns the transformation from viewport coordinates to view coordinates. */ get clientTransform(): Transform { let clientTransform: Transform; const scrollX = window.pageXOffset; const scrollY = window.pageYOffset; if (scrollX !== 0 || scrollY !== 0) { clientTransform = Transform.translate(scrollX, scrollY); } else { clientTransform = Transform.identity(); } const pageTransform = this.pageTransform; return clientTransform.transform(pageTransform); } get clientBounds(): R2Box { const viewport = this.viewport; return new R2Box(0, 0, viewport.width, viewport.height); } intersectsViewport(): boolean { const bounds = this.clientBounds; const viewportWidth = document.documentElement.clientWidth; const viewportHeight = document.documentElement.clientHeight; return (bounds.top <= 0 && 0 < bounds.bottom || 0 <= bounds.top && bounds.top < viewportHeight) && (bounds.left <= 0 && 0 < bounds.right || 0 <= bounds.left && bounds.left < viewportWidth); } dispatchEvent(event: Event): boolean { return true; // nop } on(type: string, listener: EventListenerOrEventListenerObject, options?: AddEventListenerOptions | boolean): this { return this; // nop } off(type: string, listener: EventListenerOrEventListenerObject, options?: EventListenerOptions | boolean): this { return this; // nop } /** @internal */ readonly observerCache: ViewObserverCache<this>; protected override onObserve(observer: ObserverType<this>): void { super.onObserve(observer); if (observer.viewWillInsertChild !== void 0) { this.observerCache.viewWillInsertChildObservers = Arrays.inserted(observer as ViewWillInsertChild, this.observerCache.viewWillInsertChildObservers); } if (observer.viewDidInsertChild !== void 0) { this.observerCache.viewDidInsertChildObservers = Arrays.inserted(observer as ViewDidInsertChild, this.observerCache.viewDidInsertChildObservers); } if (observer.viewWillRemoveChild !== void 0) { this.observerCache.viewWillRemoveChildObservers = Arrays.inserted(observer as ViewWillRemoveChild, this.observerCache.viewWillRemoveChildObservers); } if (observer.viewDidRemoveChild !== void 0) { this.observerCache.viewDidRemoveChildObservers = Arrays.inserted(observer as ViewDidRemoveChild, this.observerCache.viewDidRemoveChildObservers); } if (observer.viewWillResize !== void 0) { this.observerCache.viewWillResizeObservers = Arrays.inserted(observer as ViewWillResize, this.observerCache.viewWillResizeObservers); } if (observer.viewDidResize !== void 0) { this.observerCache.viewDidResizeObservers = Arrays.inserted(observer as ViewDidResize, this.observerCache.viewDidResizeObservers); } if (observer.viewWillScroll !== void 0) { this.observerCache.viewWillScrollObservers = Arrays.inserted(observer as ViewWillScroll, this.observerCache.viewWillScrollObservers); } if (observer.viewDidScroll !== void 0) { this.observerCache.viewDidScrollObservers = Arrays.inserted(observer as ViewDidScroll, this.observerCache.viewDidScrollObservers); } if (observer.viewWillChange !== void 0) { this.observerCache.viewWillChangeObservers = Arrays.inserted(observer as ViewWillChange, this.observerCache.viewWillChangeObservers); } if (observer.viewDidChange !== void 0) { this.observerCache.viewDidChangeObservers = Arrays.inserted(observer as ViewDidChange, this.observerCache.viewDidChangeObservers); } if (observer.viewWillAnimate !== void 0) { this.observerCache.viewWillAnimateObservers = Arrays.inserted(observer as ViewWillAnimate, this.observerCache.viewWillAnimateObservers); } if (observer.viewDidAnimate !== void 0) { this.observerCache.viewDidAnimateObservers = Arrays.inserted(observer as ViewDidAnimate, this.observerCache.viewDidAnimateObservers); } if (observer.viewWillProject !== void 0) { this.observerCache.viewWillProjectObservers = Arrays.inserted(observer as ViewWillProject, this.observerCache.viewWillProjectObservers); } if (observer.viewDidProject !== void 0) { this.observerCache.viewDidProjectObservers = Arrays.inserted(observer as ViewDidProject, this.observerCache.viewDidProjectObservers); } if (observer.viewWillLayout !== void 0) { this.observerCache.viewWillLayoutObservers = Arrays.inserted(observer as ViewWillLayout, this.observerCache.viewWillLayoutObservers); } if (observer.viewDidLayout !== void 0) { this.observerCache.viewDidLayoutObservers = Arrays.inserted(observer as ViewDidLayout, this.observerCache.viewDidLayoutObservers); } if (observer.viewWillRender !== void 0) { this.observerCache.viewWillRenderObservers = Arrays.inserted(observer as ViewWillRender, this.observerCache.viewWillRenderObservers); } if (observer.viewDidRender !== void 0) { this.observerCache.viewDidRenderObservers = Arrays.inserted(observer as ViewDidRender, this.observerCache.viewDidRenderObservers); } if (observer.viewWillRasterize !== void 0) { this.observerCache.viewWillRasterizeObservers = Arrays.inserted(observer as ViewWillRasterize, this.observerCache.viewWillRasterizeObservers); } if (observer.viewDidRasterize !== void 0) { this.observerCache.viewDidRasterizeObservers = Arrays.inserted(observer as ViewDidRasterize, this.observerCache.viewDidRasterizeObservers); } if (observer.viewWillComposite !== void 0) { this.observerCache.viewWillCompositeObservers = Arrays.inserted(observer as ViewWillComposite, this.observerCache.viewWillCompositeObservers); } if (observer.viewDidComposite !== void 0) { this.observerCache.viewDidCompositeObservers = Arrays.inserted(observer as ViewDidComposite, this.observerCache.viewDidCompositeObservers); } } protected override onUnobserve(observer: ObserverType<this>): void { super.onUnobserve(observer); if (observer.viewWillInsertChild !== void 0) { this.observerCache.viewWillInsertChildObservers = Arrays.removed(observer as ViewWillInsertChild, this.observerCache.viewWillInsertChildObservers); } if (observer.viewDidInsertChild !== void 0) { this.observerCache.viewDidInsertChildObservers = Arrays.removed(observer as ViewDidInsertChild, this.observerCache.viewDidInsertChildObservers); } if (observer.viewWillRemoveChild !== void 0) { this.observerCache.viewWillRemoveChildObservers = Arrays.removed(observer as ViewWillRemoveChild, this.observerCache.viewWillRemoveChildObservers); } if (observer.viewDidRemoveChild !== void 0) { this.observerCache.viewDidRemoveChildObservers = Arrays.removed(observer as ViewDidRemoveChild, this.observerCache.viewDidRemoveChildObservers); } if (observer.viewWillResize !== void 0) { this.observerCache.viewWillResizeObservers = Arrays.removed(observer as ViewWillResize, this.observerCache.viewWillResizeObservers); } if (observer.viewDidResize !== void 0) { this.observerCache.viewDidResizeObservers = Arrays.removed(observer as ViewDidResize, this.observerCache.viewDidResizeObservers); } if (observer.viewWillScroll !== void 0) { this.observerCache.viewWillScrollObservers = Arrays.removed(observer as ViewWillScroll, this.observerCache.viewWillScrollObservers); } if (observer.viewDidScroll !== void 0) { this.observerCache.viewDidScrollObservers = Arrays.removed(observer as ViewDidScroll, this.observerCache.viewDidScrollObservers); } if (observer.viewWillChange !== void 0) { this.observerCache.viewWillChangeObservers = Arrays.removed(observer as ViewWillChange, this.observerCache.viewWillChangeObservers); } if (observer.viewDidChange !== void 0) { this.observerCache.viewDidChangeObservers = Arrays.removed(observer as ViewDidChange, this.observerCache.viewDidChangeObservers); } if (observer.viewWillAnimate !== void 0) { this.observerCache.viewWillAnimateObservers = Arrays.removed(observer as ViewWillAnimate, this.observerCache.viewWillAnimateObservers); } if (observer.viewDidAnimate !== void 0) { this.observerCache.viewDidAnimateObservers = Arrays.removed(observer as ViewDidAnimate, this.observerCache.viewDidAnimateObservers); } if (observer.viewWillProject !== void 0) { this.observerCache.viewWillProjectObservers = Arrays.removed(observer as ViewWillProject, this.observerCache.viewWillProjectObservers); } if (observer.viewDidProject !== void 0) { this.observerCache.viewDidProjectObservers = Arrays.removed(observer as ViewDidProject, this.observerCache.viewDidProjectObservers); } if (observer.viewWillLayout !== void 0) { this.observerCache.viewWillLayoutObservers = Arrays.removed(observer as ViewWillLayout, this.observerCache.viewWillLayoutObservers); } if (observer.viewDidLayout !== void 0) { this.observerCache.viewDidLayoutObservers = Arrays.removed(observer as ViewDidLayout, this.observerCache.viewDidLayoutObservers); } if (observer.viewWillRender !== void 0) { this.observerCache.viewWillRenderObservers = Arrays.removed(observer as ViewWillRender, this.observerCache.viewWillRenderObservers); } if (observer.viewDidRender !== void 0) { this.observerCache.viewDidRenderObservers = Arrays.removed(observer as ViewDidRender, this.observerCache.viewDidRenderObservers); } if (observer.viewWillRasterize !== void 0) { this.observerCache.viewWillRasterizeObservers = Arrays.removed(observer as ViewWillRasterize, this.observerCache.viewWillRasterizeObservers); } if (observer.viewDidRasterize !== void 0) { this.observerCache.viewDidRasterizeObservers = Arrays.removed(observer as ViewDidRasterize, this.observerCache.viewDidRasterizeObservers); } if (observer.viewWillComposite !== void 0) { this.observerCache.viewWillCompositeObservers = Arrays.removed(observer as ViewWillComposite, this.observerCache.viewWillCompositeObservers); } if (observer.viewDidComposite !== void 0) { this.observerCache.viewDidCompositeObservers = Arrays.removed(observer as ViewDidComposite, this.observerCache.viewDidCompositeObservers); } } /** @override */ override init(init: ViewInit): void { if (init.mood !== void 0) { this.mood(init.mood); } if (init.moodModifier !== void 0) { this.moodModifier(init.moodModifier); } if (init.theme !== void 0) { this.theme(init.theme); } if (init.themeModifier !== void 0) { this.themeModifier(init.themeModifier); } } static override create<S extends new () => InstanceType<S>>(this: S): InstanceType<S> { return new this(); } static override fromInit<S extends abstract new (...args: any) => InstanceType<S>>(this: S, init: InitType<InstanceType<S>>): InstanceType<S> { let type: Creatable<View>; if ((typeof init === "object" && init !== null || typeof init === "function") && Creatable.is((init as ViewInit).type)) { type = (init as ViewInit).type!; } else { type = this as unknown as Creatable<View>; } const view = type.create(); view.init(init as ViewInit); return view as InstanceType<S>; } static override fromAny<S extends abstract new (...args: any) => InstanceType<S>>(this: S, value: AnyView<InstanceType<S>>): InstanceType<S> { if (value === void 0 || value === null) { return value as InstanceType<S>; } else if (value instanceof View) { if (value instanceof this) { return value; } else { throw new TypeError(value + " not an instance of " + this); } } else if (Creatable.is(value)) { return (value as Creatable<InstanceType<S>>).create(); } else { return (this as unknown as ViewFactory<InstanceType<S>>).fromInit(value); } } /** @internal */ static override uid: () => number = (function () { let nextId = 1; return function uid(): number { const id = ~~nextId; nextId += 1; return id; } })(); /** @internal */ static override readonly MountedFlag: ViewFlags = Component.MountedFlag; /** @internal */ static override readonly RemovingFlag: ViewFlags = Component.RemovingFlag; /** @internal */ static readonly ProcessingFlag: ViewFlags = 1 << (Component.FlagShift + 0); /** @internal */ static readonly DisplayingFlag: ViewFlags = 1 << (Component.FlagShift + 1); /** @internal */ static readonly ContextualFlag: ViewFlags = 1 << (Component.FlagShift + 2); /** @internal */ static readonly CullFlag: ViewFlags = 1 << (Component.FlagShift + 3); /** @internal */ static readonly CulledFlag: ViewFlags = 1 << (Component.FlagShift + 4); /** @internal */ static readonly HideFlag: ViewFlags = 1 << (Component.FlagShift + 5); /** @internal */ static readonly HiddenFlag: ViewFlags = 1 << (Component.FlagShift + 6); /** @internal */ static readonly UnboundedFlag: ViewFlags = 1 << (Component.FlagShift + 7); /** @internal */ static readonly IntangibleFlag: ViewFlags = 1 << (Component.FlagShift + 8); /** @internal */ static readonly CulledMask: ViewFlags = View.CullFlag | View.CulledFlag; /** @internal */ static readonly HiddenMask: ViewFlags = View.HideFlag | View.HiddenFlag; /** @internal */ static readonly UpdatingMask: ViewFlags = View.ProcessingFlag | View.DisplayingFlag; /** @internal */ static readonly StatusMask: ViewFlags = View.MountedFlag | View.RemovingFlag | View.ProcessingFlag | View.DisplayingFlag | View.ContextualFlag | View.CullFlag | View.CulledFlag | View.HiddenFlag | View.UnboundedFlag | View.IntangibleFlag; static readonly NeedsProcess: ViewFlags = 1 << (Component.FlagShift + 9); static readonly NeedsResize: ViewFlags = 1 << (Component.FlagShift + 10); static readonly NeedsScroll: ViewFlags = 1 << (Component.FlagShift + 11); static readonly NeedsChange: ViewFlags = 1 << (Component.FlagShift + 12); static readonly NeedsAnimate: ViewFlags = 1 << (Component.FlagShift + 13); static readonly NeedsProject: ViewFlags = 1 << (Component.FlagShift + 14); /** @internal */ static readonly ProcessMask: ViewFlags = View.NeedsProcess | View.NeedsResize | View.NeedsScroll | View.NeedsChange | View.NeedsAnimate | View.NeedsProject; static readonly NeedsDisplay: ViewFlags = 1 << (Component.FlagShift + 15); static readonly NeedsLayout: ViewFlags = 1 << (Component.FlagShift + 16); static readonly NeedsRender: ViewFlags = 1 << (Component.FlagShift + 17); static readonly NeedsRasterize: ViewFlags = 1 << (Component.FlagShift + 18); static readonly NeedsComposite: ViewFlags = 1 << (Component.FlagShift + 19); /** @internal */ static readonly DisplayMask: ViewFlags = View.NeedsDisplay | View.NeedsLayout | View.NeedsRender | View.NeedsRasterize | View.NeedsComposite; /** @internal */ static readonly UpdateMask: ViewFlags = View.ProcessMask | View.DisplayMask; /** @internal */ static override readonly FlagShift: number = Component.FlagShift + 20; /** @internal */ static override readonly FlagMask: ViewFlags = (1 << View.FlagShift) - 1; static override readonly MountFlags: ViewFlags = Component.MountFlags | View.NeedsResize | View.NeedsChange | View.NeedsLayout; static readonly UncullFlags: ViewFlags = View.NeedsResize | View.NeedsChange | View.NeedsLayout; static readonly UnhideFlags: ViewFlags = View.NeedsLayout; static override readonly InsertChildFlags: ViewFlags = Component.InsertChildFlags | View.NeedsLayout; static override readonly RemoveChildFlags: ViewFlags = Component.RemoveChildFlags | View.NeedsLayout; }
the_stack
import { } from 'jest' import { fetchSpec, fillInSpec, renderChart } from '../../src/render/render' import bar from '../../src/specs/bar' import scatter from '../../src/specs/scatter' import timeline from '../../src/specs/timeline' import builtBarSpec from '../data/builtBarSpec' import * as definitions from '../data/definitions' describe('Spec gets fetched properly', () => { test('fetch spec properly gets spec...', () => { const grabbedSpec = fetchSpec('bar') expect(grabbedSpec).toEqual(bar) }) test('time is properly converted to timeline', () => { const convertedSpec = fetchSpec('time') expect(convertedSpec).toEqual(timeline) }) test('bubble is properly converted to scatter', () => { const convertedSpec = fetchSpec('bubble') expect(convertedSpec).toEqual(scatter) }) test('grouped is properly converted to bar', () => { const convertedSpec = fetchSpec('grouped') expect(convertedSpec).toEqual(bar) }) }) describe('when filling in a bar spec', () => { test('it should get filled in properly', () => { const definition = definitions.bar const spec = fetchSpec(definition.type) // we're not testing the data provider here spec.dataProvider = builtBarSpec.dataProvider const result = fillInSpec(spec, definition) expect(result).toEqual(builtBarSpec) }) }) describe('when filling in a scatter spec', () => { let result beforeAll(() => { const spec = (scatter as any) result = fillInSpec(spec, definitions.scatter) }) test('it should set the graph xField field', () => { expect(result.graphs[0].xField).toEqual('TotalPop2015') }) test('it should set the graph yField field', () => { expect(result.graphs[0].yField).toEqual('MedianHHIncome2015') }) test('should set x axis title', () => { const xAxis = result.valueAxes[0] expect(xAxis.title).toEqual('Population') expect(xAxis.position).toEqual('bottom') }) test('should set y axis title', () => { const yAxis = result.valueAxes[1] expect(yAxis.title).toEqual('Median Median Household Income') expect(yAxis.position).toEqual('left') }) }) describe('when filling in a bubble spec', () => { let result let definition beforeAll(() => { const spec = (scatter as any) definition = definitions.scatter // turn this into a bubble definition.series[0].size = { field: 'Not_Taught', label: 'Number not Taught' } definition.legend = { position: 'left' } result = fillInSpec(spec, definition) }) test('it should set value field', () => { expect(result.graphs[0].valueField = definition.series[0].size.field) }) test('it should have only updated legend position, not visibility', () => { expect(result.legend.enabled).toBe(false) }) afterAll(() => { // clean up delete definition.series[0].size delete definition.legend }) }) describe('when filling in a stacked bar spec', () => { let result let definition beforeAll(() => { definition = definitions.barJoined const spec = fetchSpec(definition.type) result = fillInSpec(spec, definition) }) test('it should set category field', () => { expect(result.categoryField).toEqual('categoryField') }) test('it should set graph stack and value field properties', () => { expect(result.graphs.length).toEqual(3) result.graphs.forEach((graph, i) => { expect(graph.newStack).toBe(false) expect(graph.valueField).toEqual(`${definition.series[i].source}_Number_of_SUM`) }) }) test('it should disable legend if passed in by definition', () => { expect(result.legend.enabled).toBe(false) }) }) describe('when overriding legend defaults', () => { let result let definition beforeAll(() => { definition = definitions.bar definition.legend = { visible: true, position: 'right' } const spec = fetchSpec(definition.type) result = fillInSpec(spec, definition) }) test('Legend should be true if visible: true passed in', () => { expect(result.legend.enabled).toBe(true) }) test('Legend position should be right when position: right is passed in', () => { expect(result.legend.position).toEqual('right') }) afterAll(() => { // clean up delete definition.legend }) }) describe('When filling in style', () => { let result let definition beforeAll(() => { definition = definitions.pie definition.style = { pie: { innerRadius: '50%', expand: 0 }, padding: { top: 10, bottom: 10, right: 10, left: 10 }, colors: ['#BB4040', '#2C6175', '#95B23D'] } const spec = fetchSpec(definition.type) result = fillInSpec(spec, definition) }) test('spec.innerRadius should be 50% if definition.style.pie.innerRadius: 50% is passed in', () => { expect(result.innerRadius).toEqual('50%') }) test('spec.pullOutRadius should be 0 if definition.style.pie.expand: 0 is passed in', () => { expect(result.pullOutRadius).toEqual(0) }) test('spec.autoMargins should be false if definition.style.padding exists', () => { expect(result.autoMargins).toBeFalsy() }) test('spec.marginTop should be 10 if definition.style.padding.top: 10 is passed in', () => { expect(result.marginTop).toEqual(10) }) test('spec.marginBottom should be 10 if definition.style.padding.bottom: 10 is passed in', () => { expect(result.marginBottom).toEqual(10) }) test('spec.marginLeft should be 10 if definition.style.padding.left: 10 is passed in', () => { expect(result.marginLeft).toEqual(10) }) test('spec.marginRight should be 10 if definition.style.padding.right: 10 is passed in', () => { expect(result.marginRight).toEqual(10) }) test('spec.colors should be an array that contains the proper colors', () => { expect(result.colors).toEqual(['#BB4040', '#2C6175', '#95B23D']) }) afterAll(() => { // clean up delete definition.style }) }) describe('when filling in a line spec', () => { let result beforeAll(() => { const definition = definitions.line const spec = fetchSpec(definition.type) result = fillInSpec(spec, definitions.line) }) test('should have graphed the series', () => { /* tslint:disable quotemark object-literal-key-quotes */ const expected = [{"balloonText": "<div>Year: [[EXPR_1]]</div><div>Minor Injuries: [[MINORINJURIES_SUM]]</div>", "bullet": "circle", "bulletAlpha": 1, "bulletBorderAlpha": 0.8, "bulletBorderThickness": 0, "dashLengthField": "dashLengthLine", "fillAlphas": 0, "title": "Minor Injuries", "useLineColorForBulletBorder": true, "valueField": "MINORINJURIES_SUM"}] /* tslint:enable */ expect(result.graphs).toEqual(expected) }) }) describe('when filling in a pie spec', () => { let result beforeAll(() => { const definition = definitions.pie const spec = fetchSpec(definition.type) result = fillInSpec(spec, definition) }) test('it should set type', () => { expect(result.type).toEqual('pie') }) test('it should set title field', () => { expect(result.titleField).toEqual('Type') }) test('it should set value field', () => { expect(result.valueField).toEqual('Number_of_SUM') }) }) describe('When rendering a pie chart', () => { beforeEach(() => { // @ts-ignore global global.AmCharts = { makeChart: jest.fn().mockReturnValue({ balloonText: undefined }) } }) test('balloonText should be properly filled in', () => { const chart = renderChart('blah', definitions.pie, []) expect(chart.balloonText).toEqual('<div>Type: [[title]]</div><div>Number of Students: [[percents]]% ([[value]])</div>') }) test('It should handle missing category labels', () => { const chart = renderChart('blah', definitions.pieMissingLabels, []) expect(chart.balloonText).toEqual('<div>[[title]]</div><div>[[percents]]% ([[value]])</div>') }) afterEach(() => { // clean up // @ts-ignore global delete global.AmCharts }) }) describe('when passed an interim (v0.9.x) bar definition', () => { let result beforeAll(() => { const definition = definitions.barInterim const spec = fetchSpec(definition.type) result = fillInSpec(spec, definition) }) test('should use series category field ', () => { expect(result.categoryField).toEqual('Type') }) test('single series chart should be disabled by default', () => { expect(result.legend.enabled).toEqual(false) }) test('should set x axis', () => { expect(result.categoryAxis.title).toEqual('Facility Use') }) test('should set y axis', () => { const yAxis = result.valueAxes[0] expect(yAxis.title).toEqual('Total Students') expect(yAxis.position).toEqual('left') }) }) describe('when passed an interim (v0.9.x) scatter definition', () => { let result beforeAll(() => { const spec = (scatter as any) result = fillInSpec(spec, definitions.scatterInterim) }) test('should use series category field ', () => { expect(result.categoryField).toEqual('Number_of') }) test('single series chart should have legend disabled by default', () => { expect(result.legend.enabled).toEqual(false) }) test('should set x axis', () => { const xAxis = result.valueAxes[0] expect(xAxis.position).toEqual('bottom') expect(xAxis.title).toEqual('Student Enrollment (2008)') }) test('should set y axis', () => { const yAxis = result.valueAxes[1] expect(yAxis.position).toEqual('left') expect(yAxis.title).toEqual('Fraction of Teachers') }) }) describe('when rendering a chart', () => { describe('bar chart', () => { beforeEach(() => { // @ts-ignore global global.AmCharts = { makeChart: jest.fn() } }) describe('when passing a definition w/ overrides', () => { let expected let tempBalloonText beforeAll(() => { // add expected overrides to built bar spec expected = (builtBarSpec as any) expected.categoryAxis.labelRotation = -45 tempBalloonText = expected.graphs[0].balloonText expected.graphs[0].balloonText = '[[categoryField]]: <b>[[Number_of_SUM]]</b>' }) test('it calls makeChart with the correct arguments', () => { renderChart('blah', definitions.bar, builtBarSpec.dataProvider) // @ts-ignore global const makeChartArgs = global.AmCharts.makeChart.mock.calls[0] expect(makeChartArgs[0]).toBe('blah') expect(makeChartArgs[1]).toEqual(builtBarSpec) }) afterAll(() => { // clean up delete expected.categoryAxis.labelRotation expected.graphs[0].balloonText = tempBalloonText }) }) describe('when passing a definition w/ a specification', () => { test('it calls makeChart with the correct arguments', () => { const definition = definitions.specification const expected = { dataProvider: [], ...definition.specification } renderChart('blah', definition, []) // @ts-ignore global const makeChartArgs = global.AmCharts.makeChart.mock.calls[0] expect(makeChartArgs[0]).toBe('blah') expect(makeChartArgs[1]).toEqual(expected) }) }) describe('when passing a custom definition w/ a specification', () => { test('it calls makeChart with the correct arguments', () => { const definition = definitions.custom renderChart('blah', definition) // @ts-ignore global const makeChartArgs = global.AmCharts.makeChart.mock.calls[0] expect(makeChartArgs[0]).toBe('blah') expect(makeChartArgs[1]).toBe(definition.specification) }) }) afterEach(() => { // clean up // @ts-ignore global delete global.AmCharts }) }) })
the_stack
import { ContextLevel } from '@/core/constants'; import { Injectable } from '@angular/core'; import { CoreCourse } from '@features/course/services/course'; import { CoreFileUploader, CoreFileUploaderStoreFilesResult } from '@features/fileuploader/services/fileuploader'; import { CoreRatingOffline } from '@features/rating/services/rating-offline'; import { FileEntry } from '@ionic-native/file/ngx'; import { CoreSites } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreFormFields } from '@singletons/form'; import { CoreTextUtils } from '@services/utils/text'; import { CoreUtils } from '@services/utils/utils'; import { makeSingleton, Translate } from '@singletons'; import { CoreEvents } from '@singletons/events'; import { AddonModDataEntry, AddonModData, AddonModDataProvider, AddonModDataSearchEntriesOptions, AddonModDataEntries, AddonModDataEntryFields, AddonModDataAction, AddonModDataGetEntryFormatted, AddonModDataData, AddonModDataTemplateType, AddonModDataGetDataAccessInformationWSResponse, AddonModDataTemplateMode, AddonModDataField, AddonModDataEntryWSField, } from './data'; import { AddonModDataFieldsDelegate } from './data-fields-delegate'; import { AddonModDataOffline, AddonModDataOfflineAction } from './data-offline'; import { CoreFileEntry } from '@services/file-helper'; /** * Service that provides helper functions for datas. */ @Injectable({ providedIn: 'root' }) export class AddonModDataHelperProvider { /** * Returns the record with the offline actions applied. * * @param record Entry to modify. * @param offlineActions Offline data with the actions done. * @param fields Entry defined fields indexed by fieldid. * @return Promise resolved when done. */ protected async applyOfflineActions( record: AddonModDataEntry, offlineActions: AddonModDataOfflineAction[], fields: AddonModDataField[], ): Promise<AddonModDataEntry> { const promises: Promise<void>[] = []; offlineActions.forEach((action) => { record.timemodified = action.timemodified; record.hasOffline = true; const offlineContents: Record<number, CoreFormFields> = {}; switch (action.action) { case AddonModDataAction.APPROVE: record.approved = true; break; case AddonModDataAction.DISAPPROVE: record.approved = false; break; case AddonModDataAction.DELETE: record.deleted = true; break; case AddonModDataAction.ADD: case AddonModDataAction.EDIT: record.groupid = action.groupid; action.fields.forEach((offlineContent) => { if (typeof offlineContents[offlineContent.fieldid] == 'undefined') { offlineContents[offlineContent.fieldid] = {}; } if (offlineContent.subfield) { offlineContents[offlineContent.fieldid][offlineContent.subfield] = CoreTextUtils.parseJSON(offlineContent.value, ''); } else { offlineContents[offlineContent.fieldid][''] = CoreTextUtils.parseJSON(offlineContent.value, ''); } }); // Override field contents. fields.forEach((field) => { if (AddonModDataFieldsDelegate.hasFiles(field)) { promises.push(this.getStoredFiles(record.dataid, record.id, field.id).then((offlineFiles) => { record.contents[field.id] = AddonModDataFieldsDelegate.overrideData( field, record.contents[field.id], offlineContents[field.id], offlineFiles, ); record.contents[field.id].fieldid = field.id; return; })); } else { record.contents[field.id] = AddonModDataFieldsDelegate.overrideData( field, record.contents[field.id], offlineContents[field.id], ); record.contents[field.id].fieldid = field.id; } }); break; default: break; } }); await Promise.all(promises); return record; } /** * Approve or disapprove a database entry. * * @param dataId Database ID. * @param entryId Entry ID. * @param approve True to approve, false to disapprove. * @param courseId Course ID. It not defined, it will be fetched. * @param siteId Site ID. If not defined, current site. */ async approveOrDisapproveEntry( dataId: number, entryId: number, approve: boolean, courseId?: number, siteId?: string, ): Promise<void> { siteId = siteId || CoreSites.getCurrentSiteId(); const modal = await CoreDomUtils.showModalLoading('core.sending', true); try { courseId = await this.getActivityCourseIdIfNotSet(dataId, courseId, siteId); try { // Approve/disapprove entry. await AddonModData.approveEntry(dataId, entryId, approve, courseId, siteId); } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'addon.mod_data.errorapproving', true); throw error; } const promises: Promise<void>[] = []; promises.push(AddonModData.invalidateEntryData(dataId, entryId, siteId)); promises.push(AddonModData.invalidateEntriesData(dataId, siteId)); await CoreUtils.ignoreErrors(Promise.all(promises)); CoreEvents.trigger(AddonModDataProvider.ENTRY_CHANGED, { dataId: dataId, entryId: entryId }, siteId); CoreDomUtils.showToast(approve ? 'addon.mod_data.recordapproved' : 'addon.mod_data.recorddisapproved', true, 3000); } catch { // Ignore error, it was already displayed. } finally { modal.dismiss(); } } /** * Displays fields for being shown. * * @param template Template HMTL. * @param fields Fields that defines every content in the entry. * @param entry Entry. * @param offset Entry offset. * @param mode Mode list or show. * @param actions Actions that can be performed to the record. * @return Generated HTML. */ displayShowFields( template: string, fields: AddonModDataField[], entry: AddonModDataEntry, offset = 0, mode: AddonModDataTemplateMode, actions: Record<AddonModDataAction, boolean>, ): string { if (!template) { return ''; } // Replace the fields found on template. fields.forEach((field) => { let replace = '[[' + field.name + ']]'; replace = replace.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&'); const replaceRegex = new RegExp(replace, 'gi'); // Replace field by a generic directive. const render = '<addon-mod-data-field-plugin [field]="fields[' + field.id + ']" [value]="entries[' + entry.id + '].contents[' + field.id + ']" mode="' + mode + '" [database]="database" (gotoEntry)="gotoEntry(' + entry.id + ')"></addon-mod-data-field-plugin>'; template = template.replace(replaceRegex, render); }); for (const action in actions) { const replaceRegex = new RegExp('##' + action + '##', 'gi'); // Is enabled? if (actions[action]) { let render = ''; if (action == AddonModDataAction.MOREURL) { // Render more url directly because it can be part of an HTML attribute. render = CoreSites.getCurrentSite()!.getURL() + '/mod/data/view.php?d={{database.id}}&rid=' + entry.id; } else if (action == 'approvalstatus') { render = Translate.instant('addon.mod_data.' + (entry.approved ? 'approved' : 'notapproved')); } else { render = '<addon-mod-data-action action="' + action + '" [entry]="entries[' + entry.id + ']" mode="' + mode + '" [database]="database" [module]="module" [offset]="' + offset + '" [group]="group" ></addon-mod-data-action>'; } template = template.replace(replaceRegex, render); } else { template = template.replace(replaceRegex, ''); } } return template; } /** * Get online and offline entries, or search entries. * * @param database Database object. * @param fields The fields that define the contents. * @param options Other options. * @return Promise resolved when the database is retrieved. */ async fetchEntries( database: AddonModDataData, fields: AddonModDataField[], options: AddonModDataSearchEntriesOptions = {}, ): Promise<AddonModDataEntries> { const site = await CoreSites.getSite(options.siteId); options.groupId = options.groupId || 0; options.page = options.page || 0; const offlineActions: Record<number, AddonModDataOfflineAction[]> = {}; const result: AddonModDataEntries = { entries: [], totalcount: 0, offlineEntries: [], }; options.siteId = site.id; const offlinePromise = AddonModDataOffline.getDatabaseEntries(database.id, site.id).then((actions) => { result.hasOfflineActions = !!actions.length; actions.forEach((action) => { if (typeof offlineActions[action.entryid] == 'undefined') { offlineActions[action.entryid] = []; } offlineActions[action.entryid].push(action); // We only display new entries in the first page when not searching. if (action.action == AddonModDataAction.ADD && options.page == 0 && !options.search && !options.advSearch && (!action.groupid || !options.groupId || action.groupid == options.groupId)) { result.offlineEntries!.push({ id: action.entryid, canmanageentry: true, approved: !database.approval || database.manageapproved, dataid: database.id, groupid: action.groupid, timecreated: -action.entryid, timemodified: -action.entryid, userid: site.getUserId(), fullname: site.getInfo()?.fullname, contents: {}, }); } }); // Sort offline entries by creation time. result.offlineEntries!.sort((a, b) => b.timecreated - a.timecreated); return; }); const ratingsPromise = CoreRatingOffline.hasRatings('mod_data', 'entry', ContextLevel.MODULE, database.coursemodule) .then((hasRatings) => { result.hasOfflineRatings = hasRatings; return; }); let fetchPromise: Promise<void>; if (options.search || options.advSearch) { fetchPromise = AddonModData.searchEntries(database.id, options).then((searchResult) => { result.entries = searchResult.entries; result.totalcount = searchResult.totalcount; result.maxcount = searchResult.maxcount; return; }); } else { fetchPromise = AddonModData.getEntries(database.id, options).then((entriesResult) => { result.entries = entriesResult.entries; result.totalcount = entriesResult.totalcount; return; }); } await Promise.all([offlinePromise, ratingsPromise, fetchPromise]); // Apply offline actions to online and offline entries. const promises: Promise<AddonModDataEntry>[] = []; result.entries.forEach((entry) => { promises.push(this.applyOfflineActions(entry, offlineActions[entry.id] || [], fields)); }); result.offlineEntries!.forEach((entry) => { promises.push(this.applyOfflineActions(entry, offlineActions[entry.id] || [], fields)); }); await Promise.all(promises); return result; } /** * Fetch an online or offline entry. * * @param database Database. * @param fields List of database fields. * @param entryId Entry ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the entry. */ async fetchEntry( database: AddonModDataData, fields: AddonModDataField[], entryId: number, siteId?: string, ): Promise<AddonModDataGetEntryFormatted> { const site = await CoreSites.getSite(siteId); const offlineActions = await AddonModDataOffline.getEntryActions(database.id, entryId, site.id); let response: AddonModDataGetEntryFormatted; if (entryId > 0) { // Online entry. response = await AddonModData.getEntry(database.id, entryId, { cmId: database.coursemodule, siteId: site.id }); } else { // Offline entry or new entry. response = { entry: { id: entryId, userid: site.getUserId(), groupid: 0, dataid: database.id, timecreated: -entryId, timemodified: -entryId, approved: !database.approval || database.manageapproved, canmanageentry: true, fullname: site.getInfo()?.fullname, contents: {}, }, }; } await this.applyOfflineActions(response.entry, offlineActions, fields); return response; } /** * Returns an object with all the actions that the user can do over the record. * * @param database Database activity. * @param accessInfo Access info to the activity. * @param entry Entry or record where the actions will be performed. * @return Keyed with the action names and boolean to evalute if it can or cannot be done. */ getActions( database: AddonModDataData, accessInfo: AddonModDataGetDataAccessInformationWSResponse, entry: AddonModDataEntry, ): Record<AddonModDataAction, boolean> { return { add: false, // Not directly used on entries. more: true, moreurl: true, user: true, userpicture: true, timeadded: true, timemodified: true, tags: true, edit: entry.canmanageentry && !entry.deleted, // This already checks capabilities and readonly period. delete: entry.canmanageentry, approve: database.approval && accessInfo.canapprove && !entry.approved && !entry.deleted, disapprove: database.approval && accessInfo.canapprove && entry.approved && !entry.deleted, approvalstatus: database.approval, comments: database.comments, // Unsupported actions. delcheck: false, export: false, }; } /** * Convenience function to get the course id of the database. * * @param dataId Database id. * @param courseId Course id, if known. * @param siteId Site id, if not set, current site will be used. * @return Resolved with course Id when done. */ protected async getActivityCourseIdIfNotSet(dataId: number, courseId?: number, siteId?: string): Promise<number> { if (courseId) { return courseId; } const module = await CoreCourse.getModuleBasicInfoByInstance(dataId, 'data', siteId); return module.course; } /** * Returns the default template of a certain type. * * Based on Moodle function data_generate_default_template. * * @param type Type of template. * @param fields List of database fields. * @return Template HTML. */ getDefaultTemplate(type: AddonModDataTemplateType, fields: AddonModDataField[]): string { if (type == AddonModDataTemplateType.LIST_HEADER || type == AddonModDataTemplateType.LIST_FOOTER) { return ''; } const html: string[] = []; if (type == AddonModDataTemplateType.LIST) { html.push('##delcheck##<br />'); } html.push( '<div class="defaulttemplate">', '<table class="mod-data-default-template ##approvalstatus##">', '<tbody>', ); fields.forEach((field) => { html.push( '<tr class="">', '<td class="template-field cell c0" style="">', field.name, ': </td>', '<td class="template-token cell c1 lastcol" style="">[[', field.name, ']]</td>', '</tr>', ); }); if (type == AddonModDataTemplateType.LIST) { html.push( '<tr class="lastrow">', '<td class="controls template-field cell c0 lastcol" style="" colspan="2">', '##edit## ##more## ##delete## ##approve## ##disapprove## ##export##', '</td>', '</tr>', ); } else if (type == AddonModDataTemplateType.SINGLE) { html.push( '<tr class="lastrow">', '<td class="controls template-field cell c0 lastcol" style="" colspan="2">', '##edit## ##delete## ##approve## ##disapprove## ##export##', '</td>', '</tr>', ); } else if (type == AddonModDataTemplateType.SEARCH) { html.push( '<tr class="searchcontrols">', '<td class="template-field cell c0" style="">Author first name: </td>', '<td class="template-token cell c1 lastcol" style="">##firstname##</td>', '</tr>', '<tr class="searchcontrols lastrow">', '<td class="template-field cell c0" style="">Author surname: </td>', '<td class="template-token cell c1 lastcol" style="">##lastname##</td>', '</tr>', ); } html.push( '</tbody>', '</table>', '</div>', ); if (type == AddonModDataTemplateType.LIST) { html.push('<hr />'); } return html.join(''); } /** * Retrieve the entered data in the edit form. * We don't use ng-model because it doesn't detect changes done by JavaScript. * * @param inputData Array with the entered form values. * @param fields Fields that defines every content in the entry. * @param dataId Database Id. If set, files will be uploaded and itemId set. * @param entryId Entry Id. * @param entryContents Original entry contents. * @param offline True to prepare the data for an offline uploading, false otherwise. * @param siteId Site ID. If not defined, current site. * @return That contains object with the answers. */ async getEditDataFromForm( inputData: CoreFormFields, fields: AddonModDataField[], dataId: number, entryId: number, entryContents: AddonModDataEntryFields, offline = false, siteId?: string, ): Promise<AddonModDataEntryWSField[]> { if (!inputData) { return []; } siteId = siteId || CoreSites.getCurrentSiteId(); // Filter and translate fields to each field plugin. const entryFieldDataToSend: AddonModDataEntryWSField[] = []; const promises = fields.map(async (field) => { const fieldData = AddonModDataFieldsDelegate.getFieldEditData(field, inputData, entryContents[field.id]); if (!fieldData) { return; } const proms = fieldData.map(async (fieldSubdata) => { let value = fieldSubdata.value; // Upload Files if asked. if (dataId && fieldSubdata.files) { value = await this.uploadOrStoreFiles( dataId, 0, entryId, fieldSubdata.fieldid, fieldSubdata.files, offline, siteId, ); } // WS wants values in JSON format. entryFieldDataToSend.push({ fieldid: fieldSubdata.fieldid, subfield: fieldSubdata.subfield || '', value: value ? JSON.stringify(value) : '', }); return; }); await Promise.all(proms); }); await Promise.all(promises); return entryFieldDataToSend; } /** * Retrieve the temp files to be updated. * * @param inputData Array with the entered form values. * @param fields Fields that defines every content in the entry. * @param entryContents Original entry contents indexed by field id. * @return That contains object with the files. */ async getEditTmpFiles( inputData: CoreFormFields, fields: AddonModDataField[], entryContents: AddonModDataEntryFields, ): Promise<CoreFileEntry[]> { if (!inputData) { return []; } // Filter and translate fields to each field plugin. const promises = fields.map((field) => AddonModDataFieldsDelegate.getFieldEditFiles(field, inputData, entryContents[field.id])); const fieldsFiles = await Promise.all(promises); return fieldsFiles.reduce((files, fieldFiles) => files.concat(fieldFiles), []); } /** * Get a list of stored attachment files for a new entry. See $mmaModDataHelper#storeFiles. * * @param dataId Database ID. * @param entryId Entry ID or, if creating, timemodified. * @param fieldId Field ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the files. */ async getStoredFiles(dataId: number, entryId: number, fieldId: number, siteId?: string): Promise<FileEntry[]> { const folderPath = await AddonModDataOffline.getEntryFieldFolder(dataId, entryId, fieldId, siteId); try { return await CoreFileUploader.getStoredFiles(folderPath); } catch { // Ignore not found files. return []; } } /** * Returns the template of a certain type. * * @param data Database object. * @param type Type of template. * @param fields List of database fields. * @return Template HTML. */ getTemplate(data: AddonModDataData, type: AddonModDataTemplateType, fields: AddonModDataField[]): string { let template = data[type] || this.getDefaultTemplate(type, fields); if (type != AddonModDataTemplateType.LIST_HEADER && type != AddonModDataTemplateType.LIST_FOOTER) { // Try to fix syntax errors so the template can be parsed by Angular. template = CoreDomUtils.fixHtml(template); } // Add core-link directive to links. template = template.replace( /<a ([^>]*href="[^>]*)>/ig, (match, attributes) => '<a core-link capture="true" ' + attributes + '>', ); return template; } /** * Check if data has been changed by the user. * * @param inputData Object with the entered form values. * @param fields Fields that defines every content in the entry. * @param dataId Database Id. If set, fils will be uploaded and itemId set. * @param entryContents Original entry contents indexed by field id. * @return True if changed, false if not. */ hasEditDataChanged( inputData: CoreFormFields, fields: AddonModDataField[], entryContents: AddonModDataEntryFields, ): boolean { return fields.some((field) => AddonModDataFieldsDelegate.hasFieldDataChanged(field, inputData, entryContents[field.id])); } /** * Displays a confirmation modal for deleting an entry. * * @param dataId Database ID. * @param entryId Entry ID. * @param courseId Course ID. It not defined, it will be fetched. * @param siteId Site ID. If not defined, current site. */ async showDeleteEntryModal(dataId: number, entryId: number, courseId?: number, siteId?: string): Promise<void> { siteId = siteId || CoreSites.getCurrentSiteId(); try { await CoreDomUtils.showDeleteConfirm('addon.mod_data.confirmdeleterecord'); const modal = await CoreDomUtils.showModalLoading(); try { if (entryId > 0) { courseId = await this.getActivityCourseIdIfNotSet(dataId, courseId, siteId); } AddonModData.deleteEntry(dataId, entryId, courseId!, siteId); } catch (message) { CoreDomUtils.showErrorModalDefault(message, 'addon.mod_data.errordeleting', true); modal.dismiss(); return; } try { await AddonModData.invalidateEntryData(dataId, entryId, siteId); await AddonModData.invalidateEntriesData(dataId, siteId); } catch (error) { // Ignore errors. } CoreEvents.trigger(AddonModDataProvider.ENTRY_CHANGED, { dataId, entryId, deleted: true }, siteId); CoreDomUtils.showToast('addon.mod_data.recorddeleted', true, 3000); modal.dismiss(); } catch { // Ignore error, it was already displayed. } } /** * Given a list of files (either online files or local files), store the local files in a local folder * to be submitted later. * * @param dataId Database ID. * @param entryId Entry ID or, if creating, timemodified. * @param fieldId Field ID. * @param files List of files. * @param siteId Site ID. If not defined, current site. * @return Promise resolved if success, rejected otherwise. */ async storeFiles( dataId: number, entryId: number, fieldId: number, files: CoreFileEntry[], siteId?: string, ): Promise<CoreFileUploaderStoreFilesResult> { // Get the folder where to store the files. const folderPath = await AddonModDataOffline.getEntryFieldFolder(dataId, entryId, fieldId, siteId); return CoreFileUploader.storeFilesToUpload(folderPath, files); } /** * Upload or store some files, depending if the user is offline or not. * * @param dataId Database ID. * @param itemId Draft ID to use. Undefined or 0 to create a new draft ID. * @param entryId Entry ID or, if creating, timemodified. * @param fieldId Field ID. * @param files List of files. * @param offline True if files sould be stored for offline, false to upload them. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the itemId for the uploaded file/s. */ async uploadOrStoreFiles( dataId: number, itemId: number, entryId: number, fieldId: number, files: CoreFileEntry[], offline: true, siteId?: string, ): Promise<CoreFileUploaderStoreFilesResult>; async uploadOrStoreFiles( dataId: number, itemId: number, entryId: number, fieldId: number, files: CoreFileEntry[], offline: false, siteId?: string, ): Promise<number>; async uploadOrStoreFiles( dataId: number, itemId: number, entryId: number, fieldId: number, files: CoreFileEntry[], offline: boolean, siteId?: string, ): Promise<number | CoreFileUploaderStoreFilesResult>; async uploadOrStoreFiles( dataId: number, itemId: number = 0, entryId: number, fieldId: number, files: CoreFileEntry[], offline: boolean, siteId?: string, ): Promise<number | CoreFileUploaderStoreFilesResult> { if (offline) { return this.storeFiles(dataId, entryId, fieldId, files, siteId); } if (!files.length) { return 0; } return CoreFileUploader.uploadOrReuploadFiles(files, AddonModDataProvider.COMPONENT, itemId, siteId); } } export const AddonModDataHelper = makeSingleton(AddonModDataHelperProvider);
the_stack
import { Component, IBobrilCtx, IBobrilComponent, IBobrilChildren, invalidate, addEvent, IBobrilCacheNode, IBobrilNode, assign, init, IBobrilStyles, postEnhance, IDataWithChildren, getCurrentCtx, getDomNode, } from "./core"; import { style, styleDef } from "./cssInJs"; import { isArray, isFunction, isObject } from "./isFunc"; import { newHashObj, noop } from "./localHelpers"; import { preventClickingSpree } from "./mouseEvents"; declare var DEBUG: boolean; declare module "./core" { interface IBobrilComponent<TData = any, TCtx extends IBobrilCtx<TData> = any> extends IBobrilEventsWithCtx<TCtx> { // this is "static" function that's why it does not have ctx - because it does not exists canActivate?(transition: IRouteTransition): IRouteCanResult; canDeactivate?(ctx: IBobrilCtx<TData>, transition: IRouteTransition): IRouteCanResult; } interface Component { //static canActivate?(transition: IRouteTransition): IRouteCanResult; canDeactivate?(transition: IRouteTransition): IRouteCanResult; } } export interface Params extends Record<string, string | undefined> {} // Just marker interface export interface IRoute { name?: string; url?: string; data?: Object; handler?: IRouteHandler; keyBuilder?: (params: Params) => string; children?: Array<IRoute>; isDefault?: boolean; isNotFound?: boolean; } export enum RouteTransitionType { Push, Replace, Pop, } export interface IRouteTransition { inApp: boolean; type: RouteTransitionType; name: string | undefined; params: Params | undefined; state: any; distance?: number; } export type IRouteCanResult = boolean | IRouteTransition | PromiseLike<boolean | IRouteTransition>; export interface IRouteHandlerData { activeRouteHandler: () => IBobrilChildren; routeParams: Params; } export type IRouteHandler = IBobrilComponent | ((data: IRouteHandlerData | any) => IBobrilChildren); export interface IRouteConfig { // name cannot contain ":" or "/" name?: string; url?: string; data?: Object; handler?: IRouteHandler; keyBuilder?: (params: Params) => string; } // Heavily inspired by https://github.com/rackt/react-router/ Thanks to authors interface OutFindMatch { p: Params; } var waitingForPopHashChange = -1; function emitOnHashChange() { if (waitingForPopHashChange >= 0) clearTimeout(waitingForPopHashChange); waitingForPopHashChange = -1; invalidate(); return false; } addEvent("hashchange", 10, emitOnHashChange); let historyDeepness = 0; let programPath = ""; function history() { return window.history; } function push(path: string, inApp: boolean, state?: any): void { var l = window.location; if (inApp) { programPath = path; activeState = state; historyDeepness++; history().pushState({ historyDeepness, state }, "", path); invalidate(); } else { l.href = path; } } function replace(path: string, inApp: boolean, state?: any) { var l = window.location; if (inApp) { programPath = path; activeState = state; history().replaceState({ historyDeepness, state }, "", path); invalidate(); } else { l.replace(path); } } function pop(distance: number) { waitingForPopHashChange = setTimeout(emitOnHashChange, 50) as unknown as number; history().go(-distance); } let rootRoutes: IRoute[]; let nameRouteMap: { [name: string]: IRoute } = {}; export function encodeUrl(url: string): string { return encodeURIComponent(url).replace(/%20/g, "+"); } export function decodeUrl(url: string): string { return decodeURIComponent(url.replace(/\+/g, " ")); } export function encodeUrlPath(path: string | undefined): string { return String(path).split("/").map(encodeUrl).join("/"); } const paramCompileMatcher = /(\/?):([a-zA-Z_$][a-zA-Z0-9_$]*)([?]?)|[*.()\[\]\\+|{}^$]/g; const paramInjectMatcher = /(\/?)(?::([a-zA-Z_$][a-zA-Z0-9_$?]*[?]?)|[*])/g; let compiledPatterns: { [pattern: string]: { matcher: RegExp; paramNames: string[] }; } = {}; function compilePattern(pattern: string) { if (!(pattern in <any>compiledPatterns)) { var paramNames: Array<string> = []; var source = pattern.replace( paramCompileMatcher, (match: string, leadingSlash: string | undefined, paramName: string, optionalParamChar: string = "") => { if (paramName) { paramNames.push(paramName); return (leadingSlash ? "(?:/([^/?#]+))" : "([^/?#]+)") + optionalParamChar; } else if (match === "*") { paramNames.push("splat"); return "(.*?)"; } else { return "\\" + match; } } ); compiledPatterns[pattern] = { matcher: new RegExp("^" + source + (pattern.endsWith("/") ? "?" : "\\/?") + "$", "i"), paramNames: paramNames, }; } return compiledPatterns[pattern]!; } /// Extracts the portions of the given URL path that match the given pattern. /// Returns undefined if the pattern does not match the given path. export function extractParams(pattern: string, path: string): Params | undefined { var object = compilePattern(pattern); var match = decodeUrl(path).match(object.matcher); if (!match) return undefined; var params: { [name: string]: string } = {}; var pn = object.paramNames; var l = pn.length; for (var i = 0; i < l; i++) { params[pn[i]!] = match[i + 1]!; } return params; } /// Returns a version of the given route path with params interpolated. /// Throws if there is a dynamic segment of the route path for which there is no param. export function injectParams(pattern: string, params?: Params): string { params = params || {}; var splatIndex = 0; return ( pattern.replace(paramInjectMatcher, (_match: string, leadingSlash: string = "", paramName: string) => { paramName = paramName || "splat"; // If param is optional don't check for existence if (paramName.slice(-1) !== "?") { if (params![paramName] == undefined) throw new Error('Missing "' + paramName + '" parameter for path "' + pattern + '"'); } else { paramName = paramName.slice(0, -1); if (params![paramName] == undefined) { return ""; } } var segment: string | undefined; if (paramName === "splat" && Array.isArray(params![paramName])) { segment = params![paramName]![splatIndex++]; if (segment == undefined) throw new Error("Missing splat # " + splatIndex + ' for path "' + pattern + '"'); } else { segment = params![paramName]; } return leadingSlash + encodeUrlPath(segment); }) || "/" ); } function findMatch(path: string, rs: Array<IRoute>, outParams: OutFindMatch): IRoute[] | undefined { var l = rs.length; var notFoundRoute: IRoute | undefined; var defaultRoute: IRoute | undefined; var params: Params | undefined; for (var i = 0; i < l; i++) { var r = rs[i]!; if (r.isNotFound) { notFoundRoute = r; continue; } if (r.isDefault) { defaultRoute = r; continue; } if (r.children) { var res = findMatch(path, r.children, outParams); if (res) { res.push(r); return res; } } if (r.url) { params = extractParams(r.url, path); if (params) { outParams.p = params; return [r]; } } } if (defaultRoute) { params = extractParams(defaultRoute.url || "", path); if (params) { outParams.p = params; return [defaultRoute]; } } if (notFoundRoute) { params = extractParams(notFoundRoute.url || "", path); if (params) { outParams.p = params; return [notFoundRoute]; } } return undefined; } let activeRoutes: IRoute[] = []; let futureRoutes: IRoute[]; let activeParams: Params = newHashObj(); let activeState: any = undefined; let nodesArray: (IBobrilCacheNode | undefined)[] = []; let setterOfNodesArray: ((node: IBobrilCacheNode | undefined) => void)[] = []; const urlRegex = /.*(?:\:|\/).*/; function isInApp(name: string): boolean { return !urlRegex.test(name); } function isAbsolute(url: string): boolean { return url[0] === "/"; } const renderActiveRouter: IBobrilComponent = { render(_ctx: IBobrilCtx, me: IBobrilNode) { me.children = me.data.activeRouteHandler(); }, }; function getSetterOfNodesArray(idx: number): (node: IBobrilCacheNode | undefined) => void { while (idx >= setterOfNodesArray.length) { setterOfNodesArray.push( ((a: (IBobrilCacheNode | undefined)[], ii: number) => (n: IBobrilCacheNode | undefined) => { if (n) { var i = ii; a[i] = n; while (i-- > 0) { a[i] = undefined; } } })(nodesArray, setterOfNodesArray.length) ); } return setterOfNodesArray[idx]!; } addEvent("popstate", 5, (ev: PopStateEvent) => { let newHistoryDeepness = ev.state?.historyDeepness; if (newHistoryDeepness != undefined) { activeState = ev.state.state; if (newHistoryDeepness != historyDeepness) invalidate(); historyDeepness = newHistoryDeepness; } return false; }); var firstRouting = true; function rootNodeFactory(): IBobrilNode | undefined { if (waitingForPopHashChange >= 0) return undefined; if (history().state == undefined && historyDeepness != undefined) { history().replaceState({ historyDeepness: historyDeepness, state: activeState }, ""); } let browserPath = window.location.hash; let path = browserPath.substr(1); if (!isAbsolute(path)) path = "/" + path; var out: OutFindMatch = { p: {} }; var matches = findMatch(path, rootRoutes, out) || []; if (firstRouting) { firstRouting = false; currentTransition = { inApp: true, type: RouteTransitionType.Pop, name: undefined, params: undefined, state: undefined, }; transitionState = -1; programPath = browserPath; } else { if (!currentTransition && matches.length > 0 && browserPath != programPath) { programPath = browserPath; runTransition(createRedirectReplace(matches[0]!.name!, out.p)); } } if (currentTransition && currentTransition.type === RouteTransitionType.Pop && transitionState < 0) { programPath = browserPath; currentTransition.inApp = true; if (currentTransition.name == undefined && matches.length > 0) { currentTransition.name = matches[0]!.name; currentTransition.params = out.p; nextIteration(); if (currentTransition != null) return undefined; } else return undefined; } if (currentTransition == undefined) { activeRoutes = matches; while (nodesArray.length > activeRoutes.length) nodesArray.shift(); while (nodesArray.length < activeRoutes.length) nodesArray.unshift(undefined); activeParams = out.p; } var fn: (otherData?: any) => IBobrilNode | undefined = noop; for (var i = 0; i < activeRoutes.length; i++) { ((fnInner: Function, r: IRoute, routeParams: Params, i: number) => { fn = (otherData?: any) => { var data: any = r.data || {}; assign(data, otherData); data.activeRouteHandler = fnInner; data.routeParams = routeParams; var handler = r.handler; var res: IBobrilNode; if (isFunction(handler)) { res = { key: undefined, ref: undefined, children: handler(data) }; } else { res = { key: undefined, ref: undefined, data, component: handler || renderActiveRouter, }; } if (r.keyBuilder) res.key = r.keyBuilder(routeParams); else res.key = r.name; res.ref = getSetterOfNodesArray(i); return res; }; })(fn, activeRoutes[i]!, activeParams, i); } return fn(); } function joinPath(p1: string, p2: string): string { if (isAbsolute(p2)) return p2; if (p1[p1.length - 1] === "/") return p1 + p2; return p1 + "/" + p2; } function registerRoutes(url: string, rs: Array<IRoute>): void { var l = rs.length; for (var i = 0; i < l; i++) { var r = rs[i]!; var u = url; var name = r.name; if (!name && url === "/") { name = "root"; r.name = name; nameRouteMap[name] = r; } else if (name) { nameRouteMap[name] = r; u = joinPath(u, name); } if (r.isDefault) { u = url; } else if (r.isNotFound) { u = joinPath(url, "*"); } else if (r.url) { u = joinPath(url, r.url); } r.url = u; if (r.children) registerRoutes(u, r.children); } } export function routes(root: IRoute | IRoute[]): void { if (!isArray(root)) { root = <IRoute[]>[root]; } registerRoutes("/", <IRoute[]>root); rootRoutes = <IRoute[]>root; init(rootNodeFactory); } export function route(config: IRouteConfig, nestedRoutes?: Array<IRoute>): IRoute { return { name: config.name, url: config.url, data: config.data, handler: config.handler, keyBuilder: config.keyBuilder, children: nestedRoutes, }; } export function routeDefault(config: IRouteConfig): IRoute { return { name: config.name, data: config.data, handler: config.handler, keyBuilder: config.keyBuilder, isDefault: true, }; } export function routeNotFound(config: IRouteConfig): IRoute { return { name: config.name, data: config.data, handler: config.handler, keyBuilder: config.keyBuilder, isNotFound: true, }; } export function isActive(name: string | undefined, params?: Params): boolean { if (params) { for (var prop in params) { if (params.hasOwnProperty(prop)) { if (activeParams[prop] !== params[prop]) return false; } } } for (var i = 0, l = activeRoutes.length; i < l; i++) { if (activeRoutes[i]!.name === name) { return true; } } return false; } export function urlOfRoute(name: string, params?: Params): string { if (isInApp(name)) { var r = nameRouteMap[name]!; if (DEBUG) { if (rootRoutes == undefined) throw Error("Cannot use urlOfRoute before defining routes"); if (r == undefined) throw Error("Route with name " + name + " if not defined in urlOfRoute"); } return "#" + injectParams(r.url!, params); } return name; } export const activeStyleDef = styleDef("active"); export function Link(data: { name: string; params?: Params; state?: any; replace?: boolean; style?: IBobrilStyles; activeStyle?: IBobrilStyles; children: IBobrilChildren; }): IBobrilNode { return style( { tag: "a", component: { id: "link", onClick() { runTransition( (data.replace ? createRedirectReplace : createRedirectPush)(data.name, data.params, data.state) ); return true; }, }, children: data.children, attrs: { href: urlOfRoute(data.name, data.params) }, }, isActive(data.name, data.params) ? data.activeStyle != undefined ? data.activeStyle : [data.style, activeStyleDef] : data.style ); } export function link(node: IBobrilNode, name: string, params?: Params, state?: any): IBobrilNode { node.data = node.data || {}; node.data.routeName = name; node.data.routeParams = params; node.data.routeState = state; postEnhance(node, { render(ctx: any, me: IBobrilNode) { let data = ctx.data; if (me.tag === "a") { me.attrs = me.attrs || {}; me.attrs.href = urlOfRoute(data.routeName, data.routeParams); } me.className = me.className || ""; if (isActive(data.routeName, data.routeParams)) { me.className += " active"; } }, onClick(ctx: any) { let data = ctx.data; runTransition(createRedirectPush(data.routeName, data.routeParams, data.routeState)); return true; }, }); return node; } export function createRedirectPush(name: string, params?: Params, state?: any): IRouteTransition { return { inApp: isInApp(name), type: RouteTransitionType.Push, name: name, params: params || {}, state: state ?? activeState, }; } export function createRedirectReplace(name: string, params?: Params, state?: any): IRouteTransition { return { inApp: isInApp(name), type: RouteTransitionType.Replace, name: name, params: params || {}, state: state ?? activeState, }; } export function createBackTransition(distance?: number): IRouteTransition { distance = distance || 1; return { inApp: historyDeepness - distance >= 0, type: RouteTransitionType.Pop, name: undefined, params: {}, state: undefined, distance, }; } var currentTransition: IRouteTransition | null = null; var nextTransition: IRouteTransition | null = null; var transitionState: number = 0; function doAction(transition: IRouteTransition) { switch (transition.type) { case RouteTransitionType.Push: push(urlOfRoute(transition.name!, transition.params), transition.inApp, transition.state); break; case RouteTransitionType.Replace: replace(urlOfRoute(transition.name!, transition.params), transition.inApp, transition.state); break; case RouteTransitionType.Pop: pop(transition.distance!); break; } } function nextIteration(): void { while (true) { if (transitionState >= 0 && transitionState < activeRoutes.length) { let node = nodesArray[transitionState]; transitionState++; if (!node) continue; let comp = node.component; if (!comp && isArray(node.children)) { node = node.children[0]; if (!node) continue; comp = node.component; } if (!comp) continue; let fn = comp.canDeactivate; if (!fn) continue; let res = fn.call(comp, node.ctx!, currentTransition!); if (res === true) continue; (<any>Promise) .resolve(res) .then((resp: boolean | IRouteTransition) => { if (resp === true) { } else if (resp === false) { currentTransition = null; nextTransition = null; if (programPath) replace(programPath, true); return; } else { nextTransition = <IRouteTransition>resp; } nextIteration(); }) .catch((err: any) => { console.log(err); }); return; } else if (transitionState == activeRoutes.length) { if (nextTransition) { if (currentTransition && currentTransition.type == RouteTransitionType.Push) { push(urlOfRoute(currentTransition.name!, currentTransition.params), currentTransition.inApp); } currentTransition = nextTransition; nextTransition = null; } transitionState = -1; if (!currentTransition!.inApp || currentTransition!.type === RouteTransitionType.Pop) { let tr = currentTransition; if (!currentTransition!.inApp) currentTransition = null; doAction(tr!); return; } } else if (transitionState === -1) { var out: OutFindMatch = { p: {} }; if (currentTransition!.inApp) { futureRoutes = findMatch( urlOfRoute(currentTransition!.name!, currentTransition!.params).substring(1), rootRoutes, out ) || []; } else { futureRoutes = []; } transitionState = -2; } else if (transitionState === -2 - futureRoutes.length) { if (nextTransition) { transitionState = activeRoutes.length; continue; } if (currentTransition!.type !== RouteTransitionType.Pop) { let tr = currentTransition; currentTransition = null; doAction(tr!); } else { invalidate(); } currentTransition = null; return; } else { if (nextTransition) { transitionState = activeRoutes.length; continue; } let rr = futureRoutes[futureRoutes.length + 1 + transitionState]!; transitionState--; let handler = rr.handler; let comp: IBobrilComponent | undefined = undefined; if (isFunction(handler)) { let node = handler({ activeRouteHandler: () => undefined, routeParams: currentTransition!.params! }); if (!node || !isObject(node) || isArray(node)) continue; comp = node.component; } else { comp = handler; } if (!comp) continue; let fn = comp.canActivate; if (!fn) continue; let res = fn.call(comp, currentTransition!); if (res === true) continue; Promise.resolve<boolean | IRouteTransition>(res) .then((resp: boolean | IRouteTransition) => { if (resp === true) { } else if (resp === false) { currentTransition = null; nextTransition = null; return; } else { nextTransition = resp; } nextIteration(); }) .catch((err: any) => { console.log(err); }); return; } } } export let transitionRunCount = 1; export function runTransition(transition: IRouteTransition): void { transitionRunCount++; preventClickingSpree(); if (currentTransition != null) { nextTransition = transition; return; } firstRouting = false; currentTransition = transition; transitionState = 0; nextIteration(); } export interface IAnchorData extends IDataWithChildren { name?: string; params?: Params; onAnchor?: (el: HTMLElement) => boolean; } export function Anchor({ children, name, params, onAnchor }: IAnchorData): IBobrilNode { return anchor(children, name, params, onAnchor); } interface IBobrilAnchorCtx extends IBobrilCtx { l: number; } // shortened lastTransitionRunCount export function anchor( children: IBobrilChildren, name?: string, params?: Params, onAnchor?: (el: HTMLElement) => boolean ): IBobrilNode { return { children, component: { id: "anchor", postUpdateDom(ctx: IBobrilAnchorCtx, me: IBobrilCacheNode) { handleAnchorRoute(ctx, me, name, params, onAnchor); }, postInitDom(ctx: IBobrilAnchorCtx, me: IBobrilCacheNode) { handleAnchorRoute(ctx, me, name, params, onAnchor); }, }, }; } function handleAnchorRoute( ctx: IBobrilAnchorCtx, me: IBobrilCacheNode, name?: string, params?: Params, onAnchor?: (el: HTMLElement) => boolean ) { let routeName: string | undefined; if (name) { routeName = name; } else { const firstChild = (me.children && me.children[0]) as IBobrilCacheNode; routeName = firstChild.attrs && firstChild.attrs.id; } if (!isActive(routeName, params)) { ctx.l = 0; return; } if (ctx.l === transitionRunCount) { return; } const element = getDomNode(me) as HTMLElement; (onAnchor && onAnchor(element)) || element.scrollIntoView(); ctx.l = transitionRunCount; } export function getRoutes() { return rootRoutes; } export function getActiveRoutes() { return activeRoutes; } export function getActiveParams() { return activeParams; } export function getActiveState() { return activeState; } export function useCanDeactivate(handler: NonNullable<Component["canDeactivate"]>): void { const ctx = getCurrentCtx(); if (ctx) { ctx.me.component.canDeactivate = function (ctx: IBobrilCtx, transition: IRouteTransition): IRouteCanResult { return handler.call(ctx, transition); }; } }
the_stack
import * as BluebirdPromise from "bluebird"; import { ChildProcess, spawn } from "child_process"; import * as os from "os"; import { CONSTANTS } from "../../src/Constants"; import { DocumentStore } from "../../src/Documents/DocumentStore"; import { IDocumentStore } from "../../src/Documents/IDocumentStore"; import { GetStatisticsOperation } from "../../src/Documents/Operations/GetStatisticsOperation"; import { throwError } from "../../src/Exceptions"; import { IDisposable } from "../../src/Types/Contracts"; import { getLogger } from "../../src/Utility/LogUtil"; import { RavenServerLocator } from "./RavenServerLocator"; import { RavenServerRunner } from "./RavenServerRunner"; import { RevisionsConfiguration } from "../../src/Documents/Operations/RevisionsConfiguration"; import { RevisionsCollectionConfiguration } from "../../src/Documents/Operations/RevisionsCollectionConfiguration"; import { ConfigureRevisionsOperation, ConfigureRevisionsOperationResult } from "../../src/Documents/Operations/Revisions/ConfigureRevisionsOperation"; import { Dog, Entity, Genre, Movie, Rating, User } from "../Assets/Graph"; import { RequestExecutor } from "../../src/Http/RequestExecutor"; import * as proxyAgent from "http-proxy-agent"; import * as http from "http"; import { Stopwatch } from "../../src/Utility/Stopwatch"; import { delay } from "../../src/Utility/PromiseUtil"; import * as open from "open"; import { ClusterTestContext } from "../Utils/TestUtil"; import { GetIndexErrorsOperation } from "../../src"; import { TimeUtil } from "../../src/Utility/TimeUtil"; const log = getLogger({ module: "TestDriver" }); export abstract class RavenTestDriver { private _serverVersion: string; public get serverVersion() { return this._serverVersion; } protected _disposed: boolean = false; public isDisposed(): boolean { return this._disposed; } public static debug: boolean; public enableFiddler(): IDisposable { RequestExecutor.requestPostProcessor = (req) => { req.agent = new proxyAgent.HttpProxyAgent("http://127.0.0.1:8888") as unknown as http.Agent; }; return { dispose() { RequestExecutor.requestPostProcessor = null; } }; } protected _setupDatabase(documentStore: IDocumentStore): Promise<void> { return Promise.resolve(); } protected async _runServerInternal(locator: RavenServerLocator, processRef: (process: ChildProcess) => void, configureStore: (store: DocumentStore) => void): Promise<IDocumentStore> { log.info("Run global server"); const process = RavenServerRunner.run(locator); processRef(process); process.once("exit", (code, signal) => { log.info("Exiting."); }); const scrapServerUrl = () => { const SERVER_VERSION_REGEX = /Version (4.\d)/; const SERVER_URL_REGEX = /Server available on:\s*(\S+)\s*$/m; const serverProcess = process; let serverOutput = ""; const result = new BluebirdPromise<string>((resolve, reject) => { serverProcess.stderr .on("data", (chunk) => serverOutput += chunk); serverProcess.stdout .on("data", (chunk) => { serverOutput += chunk; const serverVersionMatch = serverOutput.match(SERVER_VERSION_REGEX); if (serverVersionMatch && serverVersionMatch.length) { this._serverVersion = serverVersionMatch[1]; } try { const regexMatch = serverOutput.match(SERVER_URL_REGEX); if (!regexMatch) { return; } const data = regexMatch[1]; if (data) { resolve(data); } } catch (err) { reject(err); } }) .on("error", (err) => reject(err)); }); // timeout if url won't show up after 5s return result // tslint:disable-next-line:no-console .tap(url => console.log("DEBUG: RavenDB server URL", url)) .timeout(5000) .catch((err) => { throwError("UrlScrappingError", "Error scrapping URL from server process output: " + os.EOL + serverOutput, err); }); }; let serverUrl: string; try { serverUrl = await scrapServerUrl(); } catch (err) { try { process.kill("SIGKILL"); } catch (processKillErr) { log.error(processKillErr); } throwError("InvalidOperationException", "Unable to start server.", err); } const store = new DocumentStore([serverUrl], "test.manager"); store.conventions.disableTopologyUpdates = true; if (configureStore) { configureStore(store); } return store.initialize(); } public waitForIndexing(store: IDocumentStore): Promise<void>; public waitForIndexing(store: IDocumentStore, database?: string): Promise<void>; public waitForIndexing(store: IDocumentStore, database?: string, timeout?: number): Promise<void>; public waitForIndexing( store: IDocumentStore, database?: string, timeout?: number, throwOnIndexErrors?: boolean): Promise<void>; public waitForIndexing( store: IDocumentStore, database?: string, timeout?: number, throwOnIndexErrors?: boolean, nodeTag?: string): Promise<void>; public waitForIndexing( store: IDocumentStore, database?: string, timeout?: number, throwOnIndexErrors: boolean = true, nodeTag?: string): Promise<void> { const admin = store.maintenance.forDatabase(database); if (!timeout) { timeout = 60 * 1000; // minute } const isIndexingDone = async (): Promise<boolean> => { const dbStats = await admin.send(new GetStatisticsOperation("wait-for-indexing", nodeTag)); const indexes = dbStats.indexes.filter(x => x.state !== "Disabled"); const errIndexes = indexes.filter(x => x.state === "Error"); if (errIndexes.length && throwOnIndexErrors) { throwError("IndexInvalidException", `The following indexes are erroneous: ${errIndexes.map(x => x.name).join(", ")}`); } return indexes.every(x => !x.isStale && !x.name.startsWith(CONSTANTS.Documents.Indexing.SIDE_BY_SIDE_INDEX_NAME_PREFIX)); }; const pollIndexingStatus = async () => { log.info("Waiting for indexing..."); const indexingDone = await isIndexingDone(); if (!indexingDone) { await delay(100); await pollIndexingStatus(); } else { log.info("Done waiting for indexing."); } }; const result = BluebirdPromise.resolve(pollIndexingStatus()) .timeout(timeout) .tapCatch((err) => { log.warn(err, "Wait for indexing timeout."); }); return Promise.resolve(result); } public async waitForIndexingErrors(store: IDocumentStore, timeoutInMs: number, ...indexNames: string[]) { const sw = Stopwatch.createStarted(); while (sw.elapsed < timeoutInMs) { const indexes = await store.maintenance.send(new GetIndexErrorsOperation(indexNames)); for (const index of indexes) { if (index.errors && index.errors.length) { return indexes; } } await delay(32); } throwError("TimeoutException", "Got no index error from more than " + TimeUtil.millisToTimeSpan(timeoutInMs)); } public async waitForDocumentDeletion(store: IDocumentStore, id: string) { const sw = Stopwatch.createStarted(); while (sw.elapsed <= 10_000) { const session = store.openSession(); if (!await session.advanced.exists(id)) { return true; } await delay(100); } return false; } public async waitForValue<T>(act: () => Promise<T>, expectedValue: T, opts: { timeout?: number; equal?: (a: T, b: T) => boolean } = {}) { return ClusterTestContext.waitForValue(act, expectedValue, opts); } public static async waitForValue<T>(act: () => Promise<T>, expectedValue: T, opts: { timeout?: number; equal?: (a: T, b: T) => boolean } = {}) { const timeout = opts.timeout ?? 15_000; const identity = (a, b) => a === b; const compare = opts.equal ?? identity; const sw = Stopwatch.createStarted(); do { try { const currentVal = await act(); if (compare(expectedValue, currentVal)) { return currentVal; } if (sw.elapsed > timeout) { return currentVal; } } catch (e) { if (sw.elapsed > timeout) { throwError("InvalidOperationException", e); } } await delay(16); } while (true); } protected static _killProcess(p: ChildProcess) { if (p && !p.killed) { log.info("Kill global server"); try { p.kill("SIGKILL"); } catch (err) { log.error(err); } } } public async waitForUserToContinueTheTest(store: IDocumentStore) { const databaseNameEncoded = encodeURIComponent(store.database); const documentsPage = store.urls[0] + "/studio/index.html#databases/documents?&database=" + databaseNameEncoded + "&withStop=true&disableAnalytics=true"; this._openBrowser(documentsPage); do { await delay(500); const session = store.openSession(); if (await session.load("Debug/Done")) { break; } } while (true); } protected _openBrowser(url: string): void { // tslint:disable-next-line:no-console console.log(url); if (os.platform() === "win32") { // noinspection JSIgnoredPromiseFromCall open(url); } else { spawn("xdg-open", [url], { detached: true }); } } public setupRevisions( store: IDocumentStore, purgeOnDelete: boolean, minimumRevisionsToKeep: number): Promise<ConfigureRevisionsOperationResult> { const revisionsConfiguration = new RevisionsConfiguration(); const defaultConfiguration = new RevisionsCollectionConfiguration(); defaultConfiguration.purgeOnDelete = purgeOnDelete; defaultConfiguration.minimumRevisionsToKeep = minimumRevisionsToKeep; revisionsConfiguration.defaultConfig = defaultConfiguration; const operation = new ConfigureRevisionsOperation(revisionsConfiguration); return store.maintenance.send(operation); } public async createSimpleData(store: IDocumentStore) { { const session = store.openSession(); const entityA = Object.assign(new Entity(), { id: "entity/1", name: "A" }); const entityB = Object.assign(new Entity(), { id: "entity/2", name: "B" }); const entityC = Object.assign(new Entity(), { id: "entity/3", name: "C" }); await session.store(entityA); await session.store(entityB); await session.store(entityC); entityA.references = entityB.id; entityB.references = entityC.id; entityC.references = entityA.id; await session.saveChanges(); } } public async createDogDataWithoutEdges(store: IDocumentStore) { { const session = store.openSession(); const arava = Object.assign(new Dog(), { name: "Arava" }); const oscar = Object.assign(new Dog(), { name: "Oscar" }); const pheobe = Object.assign(new Dog(), { name: "Pheobe" }); await session.store(arava); await session.store(oscar); await session.store(pheobe); await session.saveChanges(); } } public async createDataWithMultipleEdgesOfTheSameType(store: IDocumentStore) { { const session = store.openSession(); const arava = Object.assign(new Dog(), { name: "Arava" }); const oscar = Object.assign(new Dog(), { name: "Oscar" }); const pheobe = Object.assign(new Dog(), { name: "Pheobe" }); await session.store(arava); await session.store(oscar); await session.store(pheobe); //dogs/1 => dogs/2 arava.likes = [ oscar.id ]; arava.dislikes = [ pheobe.id ]; //dogs/2 => dogs/2,dogs/3 (cycle!) oscar.likes = [ oscar.id, pheobe.id ]; oscar.dislikes = []; //dogs/3 => dogs/2 pheobe.likes = [ oscar.id ]; pheobe.dislikes = [ arava.id ]; await session.saveChanges(); } } public async createMoviesData(store: IDocumentStore) { { const session = store.openSession(); const scifi = Object.assign(new Genre(), { id: "genres/1", name: "Sci-Fi" }); const fantasy = Object.assign(new Genre(), { id: "genres/2", name: "Fantasy" }); const adventure = Object.assign(new Genre(), { id: "genres/3", name: "Adventure" }); await session.store(scifi); await session.store(fantasy); await session.store(adventure); const starwars = Object.assign(new Movie(), { id: "movies/1", name: "Star Wars Ep.1", genres: [ "genres/1", "genres/2" ] }); const firefly = Object.assign(new Movie(), { id: "movies/2", name: "Firefly Serenity", genres: [ "genres/2", "genres/3" ] }); const indianaJones = Object.assign(new Movie(), { id: "movies/3", name: "Indiana Jones and the Temple Of Doom", genres: [ "genres/3" ] }); await session.store(starwars); await session.store(firefly); await session.store(indianaJones); const user1 = Object.assign(new User(), { id: "users/1", name: "Jack" }); const rating11 = Object.assign(new Rating(), { movie: "movies/1", score: 5 }); const rating12 = Object.assign(new Rating(), { movie: "movies/2", score: 7 }); user1.hasRated = [ rating11, rating12 ]; await session.store(user1); const user2 = Object.assign(new User(), { id: "users/2", name: "Jill" }); const rating21 = Object.assign(new Rating(), { movie: "movies/2", score: 7 }); const rating22 = Object.assign(new Rating(), { movie: "movies/3", score: 9 }); user2.hasRated = [ rating21, rating22 ]; await session.store(user2); const user3 = Object.assign(new User(), { id: "users/3", name: "Bob" }); const rating31 = Object.assign(new Rating(), { movie: "movies/3", score: 5 }); user3.hasRated = [ rating31 ]; await session.store(user3); await session.saveChanges(); } } }
the_stack
import {Mutable, FromAny} from "@swim/util"; import {Affinity, FastenerOwner, FastenerFlags, PropertyInit, PropertyClass, Property} from "@swim/component"; import {ConstraintId} from "./ConstraintId"; import {ConstraintMap} from "./ConstraintMap"; import {AnyConstraintExpression, ConstraintExpression} from "./ConstraintExpression"; import type {ConstraintTerm} from "./ConstraintTerm"; import type {ConstraintVariable} from "./ConstraintVariable"; import {AnyConstraintStrength, ConstraintStrength} from "./"; // forward import import type {Constraint} from "./Constraint"; import {ConstraintScope} from "./"; // forward import import type {ConstraintSolver} from "./ConstraintSolver"; /** @public */ export interface ConstraintPropertyInit<T = unknown, U = T> extends PropertyInit<T, U> { extends?: {prototype: ConstraintProperty<any, any>} | string | boolean | null; constrain?: boolean; strength?: AnyConstraintStrength; willStartConstraining?(): void; didStartConstraining?(): void; willStopConstraining?(): void; didStopConstraining?(): void; toNumber?(value: T): number; } /** @public */ export type ConstraintPropertyDescriptor<O = unknown, T = unknown, U = T, I = {}> = ThisType<ConstraintProperty<O, T, U> & I> & ConstraintPropertyInit<T, U> & Partial<I>; /** @public */ export interface ConstraintPropertyClass<P extends ConstraintProperty<any, any> = ConstraintProperty<any, any>> extends PropertyClass<P> { /** @internal */ readonly ConstrainedFlag: FastenerFlags; /** @internal */ readonly ConstrainingFlag: FastenerFlags; /** @internal @override */ readonly FlagShift: number; /** @internal @override */ readonly FlagMask: FastenerFlags; } /** @public */ export interface ConstraintPropertyFactory<P extends ConstraintProperty<any, any> = ConstraintProperty<any, any>> extends ConstraintPropertyClass<P> { extend<I = {}>(className: string, classMembers?: Partial<I> | null): ConstraintPropertyFactory<P> & I; specialize(type: unknown): ConstraintPropertyFactory | null; define<O, T, U = T>(className: string, descriptor: ConstraintPropertyDescriptor<O, T, U>): ConstraintPropertyFactory<ConstraintProperty<any, T, U>>; define<O, T, U = T, I = {}>(className: string, descriptor: {implements: unknown} & ConstraintPropertyDescriptor<O, T, U, I>): ConstraintPropertyFactory<ConstraintProperty<any, T, U> & I>; <O, T extends number | undefined = number | undefined, U extends number | string | undefined = number | string | undefined>(descriptor: {type: typeof Number} & ConstraintPropertyDescriptor<O, T, U>): PropertyDecorator; <O, T, U = T>(descriptor: ({type: FromAny<T, U>} | {fromAny(value: T | U): T}) & ConstraintPropertyDescriptor<O, T, U>): PropertyDecorator; <O, T, U = T>(descriptor: ConstraintPropertyDescriptor<O, T, U>): PropertyDecorator; <O, T, U = T, I = {}>(descriptor: {implements: unknown} & ConstraintPropertyDescriptor<O, T, U, I>): PropertyDecorator; } /** @public */ export interface ConstraintProperty<O = unknown, T = unknown, U = T> extends Property<O, T, U>, ConstraintVariable { /** @internal @override */ readonly id: number; /** @internal @override */ isExternal(): boolean; /** @internal @override */ isDummy(): boolean; /** @internal @override */ isInvalid(): boolean; /** @override */ isConstant(): boolean; /** @internal @override */ evaluateConstraintVariable(): void; /** @internal @override */ updateConstraintSolution(value: number): void; /** @override */ readonly strength: ConstraintStrength; setStrength(strength: AnyConstraintStrength): void; /** @override */ get coefficient(): number; /** @override */ get variable(): ConstraintVariable | null; /** @override */ get terms(): ConstraintMap<ConstraintVariable, number>; /** @override */ get constant(): number; /** @override */ plus(that: AnyConstraintExpression): ConstraintExpression; /** @override */ negative(): ConstraintTerm; /** @override */ minus(that: AnyConstraintExpression): ConstraintExpression; /** @override */ times(scalar: number): ConstraintExpression; /** @override */ divide(scalar: number): ConstraintExpression; get constrained(): boolean; constrain(constrained?: boolean): this; /** @internal */ readonly conditionCount: number; /** @internal @override */ addConstraintCondition(constraint: Constraint, solver: ConstraintSolver): void; /** @internal @override */ removeConstraintCondition(constraint: Constraint, solver: ConstraintSolver): void; /** @internal */ get constraining(): boolean; /** @internal */ startConstraining(): void; /** @protected */ willStartConstraining(): void; /** @protected */ onStartConstraining(): void; /** @protected */ didStartConstraining(): void; /** @internal */ stopConstraining(): void; /** @protected */ willStopConstraining(): void; /** @protected */ onStopConstraining(): void; /** @protected */ didStopConstraining(): void; /** @internal */ updateConstraintVariable(): void; /** @protected @override */ onSetValue(newValue: T, oldValue: T): void; /** @protected @override */ onMount(): void; /** @protected @override */ onUnmount(): void; /** @override */ fromAny(value: T | U): T; /** @internal @protected */ toNumber(value: T): number; } /** @public */ export const ConstraintProperty = (function (_super: typeof Property) { const ConstraintProperty: ConstraintPropertyFactory = _super.extend("ConstraintProperty"); ConstraintProperty.prototype.isExternal = function (this: ConstraintProperty): boolean { return true; }; ConstraintProperty.prototype.isDummy = function (this: ConstraintProperty): boolean { return false; }; ConstraintProperty.prototype.isInvalid = function (this: ConstraintProperty): boolean { return false; }; ConstraintProperty.prototype.isConstant = function (this: ConstraintProperty): boolean { return false; }; ConstraintProperty.prototype.evaluateConstraintVariable = function <T>(this: ConstraintProperty<unknown, T>): void { // hook }; ConstraintProperty.prototype.updateConstraintSolution = function <T>(this: ConstraintProperty<unknown, T>, value: number): void { if (this.constrained && this.toNumber(this.value) !== value) { this.setValue(value as unknown as T, Affinity.Reflexive); } }; ConstraintProperty.prototype.setStrength = function (this: ConstraintProperty, strength: AnyConstraintStrength): void { (this as Mutable<typeof this>).strength = ConstraintStrength.fromAny(strength); }; Object.defineProperty(ConstraintProperty.prototype, "coefficient", { get(this: ConstraintProperty): number { return 1; }, configurable: true, }); Object.defineProperty(ConstraintProperty.prototype, "variable", { get(this: ConstraintProperty): ConstraintVariable { return this; }, configurable: true, }); Object.defineProperty(ConstraintProperty.prototype, "terms", { get(this: ConstraintProperty): ConstraintMap<ConstraintVariable, number> { const terms = new ConstraintMap<ConstraintVariable, number>(); terms.set(this, 1); return terms; }, configurable: true, }); Object.defineProperty(ConstraintProperty.prototype, "constant", { get(this: ConstraintProperty): number { return 0; }, configurable: true, }); ConstraintProperty.prototype.plus = function (this: ConstraintProperty, that: AnyConstraintExpression): ConstraintExpression { that = ConstraintExpression.fromAny(that); if (this === that) { return ConstraintExpression.product(2, this); } else { return ConstraintExpression.sum(this, that); } }; ConstraintProperty.prototype.negative = function (this: ConstraintProperty): ConstraintTerm { return ConstraintExpression.product(-1, this); }; ConstraintProperty.prototype.minus = function (this: ConstraintProperty, that: AnyConstraintExpression): ConstraintExpression { that = ConstraintExpression.fromAny(that); if (this === that) { return ConstraintExpression.zero; } else { return ConstraintExpression.sum(this, that.negative()); } }; ConstraintProperty.prototype.times = function (this: ConstraintProperty, scalar: number): ConstraintExpression { return ConstraintExpression.product(scalar, this); }; ConstraintProperty.prototype.divide = function (this: ConstraintProperty, scalar: number): ConstraintExpression { return ConstraintExpression.product(1 / scalar, this); }; Object.defineProperty(ConstraintProperty.prototype, "constrained", { get(this: ConstraintProperty): boolean { return (this.flags & ConstraintProperty.ConstrainedFlag) !== 0; }, configurable: true, }); ConstraintProperty.prototype.constrain = function (this: ConstraintProperty<unknown, unknown, unknown>, constrained?: boolean): typeof this { if (constrained === void 0) { constrained = true; } const flags = this.flags; if (constrained && (flags & ConstraintProperty.ConstrainedFlag) === 0) { this.setFlags(flags | ConstraintProperty.ConstrainedFlag); if (this.conditionCount !== 0 && this.mounted) { this.stopConstraining(); } } else if (!constrained && (flags & ConstraintProperty.ConstrainedFlag) !== 0) { this.setFlags(flags & ~ConstraintProperty.ConstrainedFlag); if (this.conditionCount !== 0 && this.mounted) { this.startConstraining(); this.updateConstraintVariable(); } } return this; }; ConstraintProperty.prototype.addConstraintCondition = function (this: ConstraintProperty, constraint: Constraint, solver: ConstraintSolver): void { (this as Mutable<typeof this>).conditionCount += 1; if (!this.constrained && this.conditionCount === 1 && this.mounted) { this.startConstraining(); this.updateConstraintVariable(); } }; ConstraintProperty.prototype.removeConstraintCondition = function (this: ConstraintProperty, constraint: Constraint, solver: ConstraintSolver): void { (this as Mutable<typeof this>).conditionCount -= 1; if (!this.constrained && this.conditionCount === 0 && this.mounted) { this.stopConstraining(); } }; Object.defineProperty(ConstraintProperty.prototype, "constraining", { get(this: ConstraintProperty): boolean { return (this.flags & ConstraintProperty.ConstrainingFlag) !== 0; }, configurable: true, }); ConstraintProperty.prototype.startConstraining = function (this: ConstraintProperty): void { if ((this.flags & ConstraintProperty.ConstrainingFlag) === 0) { this.willStartConstraining(); this.setFlags(this.flags | ConstraintProperty.ConstrainingFlag); this.onStartConstraining(); this.didStartConstraining(); } }; ConstraintProperty.prototype.willStartConstraining = function (this: ConstraintProperty): void { // hook }; ConstraintProperty.prototype.onStartConstraining = function (this: ConstraintProperty): void { const constraintScope = this.owner; if (ConstraintScope.is(constraintScope)) { constraintScope.addConstraintVariable(this); } }; ConstraintProperty.prototype.didStartConstraining = function (this: ConstraintProperty): void { // hook }; ConstraintProperty.prototype.stopConstraining = function (this: ConstraintProperty): void { if ((this.flags & ConstraintProperty.ConstrainingFlag) !== 0) { this.willStopConstraining(); this.setFlags(this.flags & ~ConstraintProperty.ConstrainingFlag); this.onStopConstraining(); this.didStopConstraining(); } }; ConstraintProperty.prototype.willStopConstraining = function (this: ConstraintProperty): void { // hook }; ConstraintProperty.prototype.onStopConstraining = function (this: ConstraintProperty): void { const constraintScope = this.owner; if (ConstraintScope.is(constraintScope)) { constraintScope.removeConstraintVariable(this); } }; ConstraintProperty.prototype.didStopConstraining = function (this: ConstraintProperty): void { // hook }; ConstraintProperty.prototype.updateConstraintVariable = function (this: ConstraintProperty): void { const constraintScope = this.owner; const value = this.value; if (value !== void 0 && ConstraintScope.is(constraintScope)) { constraintScope.setConstraintVariable(this, this.toNumber(value)); } }; ConstraintProperty.prototype.onSetValue = function <T>(this: ConstraintProperty<unknown, T>, newValue: T, oldValue: T): void { _super.prototype.onSetValue.call(this, newValue, oldValue); const constraintScope = this.owner; if (this.constraining && ConstraintScope.is(constraintScope)) { constraintScope.setConstraintVariable(this, newValue !== void 0 && newValue !== null ? this.toNumber(newValue) : 0); } }; ConstraintProperty.prototype.onMount = function <T>(this: ConstraintProperty<unknown, T>): void { _super.prototype.onMount.call(this); if (!this.constrained && this.conditionCount !== 0) { this.startConstraining(); } }; ConstraintProperty.prototype.onUnmount = function <T>(this: ConstraintProperty<unknown, T>): void { if (!this.constrained && this.conditionCount !== 0) { this.stopConstraining(); } _super.prototype.onUnmount.call(this); }; ConstraintProperty.prototype.fromAny = function <T, U>(this: ConstraintProperty<unknown, T, U>, value: T | U): T { if (typeof value === "string") { const number = +value; if (isFinite(number)) { return number as unknown as T; } } return value as T; }; ConstraintProperty.prototype.toNumber = function <T>(this: ConstraintProperty<unknown, T>, value: T): number { return value !== void 0 && value !== null ? +value : 0; }; ConstraintProperty.construct = function <P extends ConstraintProperty<any, any>>(propertyClass: {prototype: P}, property: P | null, owner: FastenerOwner<P>): P { property = _super.construct(propertyClass, property, owner) as P; (property as Mutable<typeof property>).id = ConstraintId.next(); (property as Mutable<typeof property>).strength = ConstraintStrength.Strong; (property as Mutable<typeof property>).conditionCount = 0; return property; }; ConstraintProperty.specialize = function (type: unknown): ConstraintPropertyFactory | null { return null; }; ConstraintProperty.define = function <O, T, U>(className: string, descriptor: ConstraintPropertyDescriptor<O, T, U>): ConstraintPropertyFactory<ConstraintProperty<any, T, U>> { let superClass = descriptor.extends as ConstraintPropertyFactory | null | undefined; const affinity = descriptor.affinity; const inherits = descriptor.inherits; const strength = descriptor.strength !== void 0 ? ConstraintStrength.fromAny(descriptor.strength) : void 0; const constrain = descriptor.constrain; const value = descriptor.value; const initValue = descriptor.initValue; delete descriptor.extends; delete descriptor.implements; delete descriptor.affinity; delete descriptor.inherits; delete descriptor.strength; delete descriptor.constrain; delete descriptor.value; delete descriptor.initValue; if (superClass === void 0 || superClass === null) { superClass = this.specialize(descriptor.type); } if (superClass === null) { superClass = this; if (descriptor.fromAny === void 0 && FromAny.is<T, U>(descriptor.type)) { descriptor.fromAny = descriptor.type.fromAny; } } const propertyClass = superClass.extend(className, descriptor); propertyClass.construct = function (propertyClass: {prototype: ConstraintProperty<any, any>}, property: ConstraintProperty<O, T, U> | null, owner: O): ConstraintProperty<O, T, U> { property = superClass!.construct(propertyClass, property, owner); if (affinity !== void 0) { property.initAffinity(affinity); } if (inherits !== void 0) { property.initInherits(inherits); } if (strength !== void 0) { (property as Mutable<typeof property>).strength = strength; } if (initValue !== void 0) { (property as Mutable<typeof property>).value = property.fromAny(initValue()); } else if (value !== void 0) { (property as Mutable<typeof property>).value = property.fromAny(value); } if (constrain === true) { property.constrain(); } return property; }; return propertyClass; }; (ConstraintProperty as Mutable<typeof ConstraintProperty>).ConstrainedFlag = 1 << (_super.FlagShift + 0); (ConstraintProperty as Mutable<typeof ConstraintProperty>).ConstrainingFlag = 1 << (_super.FlagShift + 1); (ConstraintProperty as Mutable<typeof ConstraintProperty>).FlagShift = _super.FlagShift + 2; (ConstraintProperty as Mutable<typeof ConstraintProperty>).FlagMask = (1 << ConstraintProperty.FlagShift) - 1; return ConstraintProperty; })(Property);
the_stack
import { SSHLogger } from "./SSHLogger"; import { Server } from "./Server"; import { ByteReader } from "./ByteReader"; import { ByteWriter } from "./ByteWriter"; import { ExchangeContext } from "./ExchangeContext"; import * as Packets from "./Packets/PacketType"; import * as Exceptions from "./SSHServerException"; import { IKexAlgorithm } from "./KexAlgorithms/IKexAlgorithm"; import net = require("net"); import util = require("util"); import crypto = require("crypto"); export class Client { private m_Socket: net.Socket; private m_LastBytesRead: number = 0; private m_HasCompletedProtocolVersionExchange: boolean = false; private m_ProtocolVersionExchange: string = ""; private m_KexInitServerToClient: Packets.KexInit = new Packets.KexInit(); private m_KexInitClientToServer: Packets.KexInit = null; private m_SessionId: Buffer = null; private m_CurrentSentPacketNumber: number = 0; private m_CurrentReceivedPacketNumber: number = 0; private m_TotalBytesTransferred: number = 0; private m_KeyTimeout: NodeJS.Timer = null; private m_ActiveExchangeContext: ExchangeContext = new ExchangeContext(); private m_PendingExchangeContext: ExchangeContext = new ExchangeContext(); constructor(socket: net.Socket) { this.m_Socket = socket; this.resetKeyTimer(); this.m_KexInitServerToClient.kexAlgorithms = Server.SupportedKexAlgorithms; this.m_KexInitServerToClient.serverHostKeyAlgorithms = Server.SupportedHostKeyAlgorithms; this.m_KexInitServerToClient.encryptionAlgorithmsClientToServer = Server.SupportedCiphers; this.m_KexInitServerToClient.encryptionAlgorithmsServerToClient = Server.SupportedCiphers; this.m_KexInitServerToClient.macAlgorithmsClientToServer = Server.SupportedMACAlgorithms; this.m_KexInitServerToClient.macAlgorithmsServerToClient = Server.SupportedMACAlgorithms; this.m_KexInitServerToClient.compressionAlgorithmsClientToServer = Server.SupportedCompressions; this.m_KexInitServerToClient.compressionAlgorithmsServerToClient = Server.SupportedCompressions; this.m_KexInitServerToClient.firstKexPacketFollows = false; this.m_Socket.setNoDelay(true); this.m_Socket.on("close", this.closeReceived.bind(this)); // 4.2.Protocol Version Exchange - https://tools.ietf.org/html/rfc4253#section-4.2 this.sendString(util.format("%s\r\n", Server.ProtocolVersionExchange)); // 7.1. Algorithm Negotiation - https://tools.ietf.org/html/rfc4253#section-7.1 this.sendPacket(this.m_KexInitServerToClient); } public getIsConnected(): boolean { return (this.m_Socket != null); } public poll(): void { if (!this.getIsConnected()) { return; } if (this.getIsDataAvailable()) { if (!this.m_HasCompletedProtocolVersionExchange) { // wait for CRLF try { this.readProtocolVersionExchange(); if (this.m_HasCompletedProtocolVersionExchange) { SSHLogger.logDebug(util.format("Received ProtocolVersionExchange: %s", this.m_ProtocolVersionExchange)); this.validateProtocolVersionExchange(); } } catch (ex) { SSHLogger.logError(ex); this.disconnect( Exceptions.DisconnectReason.SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED, "Failed to get the protocol version exchange."); return; } } if (this.m_HasCompletedProtocolVersionExchange) { try { let packet: Packets.Packet = this.readPacket(); while (packet != null) { this.handlePacket(packet); packet = this.readPacket(); } this.considerReExchange(); } catch (ex) { if (ex instanceof Exceptions.SSHServerException) { let serverEx: Exceptions.SSHServerException = <Exceptions.SSHServerException>ex; SSHLogger.logError(ex); this.disconnect(serverEx.reason, serverEx.message); return; } else { SSHLogger.logError(ex); this.disconnect(Exceptions.DisconnectReason.SSH_DISCONNECT_PROTOCOL_ERROR, ex.message); return; } } } } } public sendString(message: string): void { if (!this.getIsConnected()) { return; } SSHLogger.logDebug(util.format("Sending raw string: %s", message.trim())); this.m_Socket.write(message, "UTF8"); } public sendPacket(packet: Packets.Packet): void { packet.packetSequence = this.m_CurrentSentPacketNumber; this.m_CurrentSentPacketNumber += 1; let payload: Buffer = this.m_ActiveExchangeContext.compressionServerToClient.compress(packet.getBytes()); let blockSize: number = this.m_ActiveExchangeContext.cipherServerToClient.getBlockSize(); let paddingLength: number = blockSize - (payload.length + 5) % blockSize; if (paddingLength < 4) { paddingLength += blockSize; } let padding: Buffer = crypto.randomBytes(paddingLength); let packetLength: number = payload.length + paddingLength + 1; let writer: ByteWriter = new ByteWriter(); writer.writeUInt32(packetLength); writer.writeByte(paddingLength); writer.writeRawBytes(payload); writer.writeRawBytes(padding); payload = writer.toBuffer(); let encryptedPayload: Buffer = this.m_ActiveExchangeContext.cipherServerToClient.encrypt(payload); if (this.m_ActiveExchangeContext.macAlgorithmServerToClient != null) { let mac: Buffer = this.m_ActiveExchangeContext.macAlgorithmServerToClient.computeHash(packet.packetSequence, payload); encryptedPayload = Buffer.concat([encryptedPayload, mac]); } this.sendRaw(payload); this.considerReExchange(); } public disconnect(reason: Exceptions.DisconnectReason, message: string): void { if (this.m_Socket != null) { SSHLogger.logInfo(util.format( "Disconnected from: %s - %s - %s", this.m_Socket.remoteAddress, Exceptions.DisconnectReason[reason], message)); if (reason !== Exceptions.DisconnectReason.None) { try { let disconnect: Packets.Disconnect = new Packets.Disconnect(); disconnect.reason = reason; disconnect.description = message; this.sendPacket(disconnect); } catch (ex) { } } try { this.m_Socket.destroy(); } catch (ex) { } this.m_Socket = null; } } private handlePacket(packet: Packets.Packet): void { switch (packet.getPacketType()) { case Packets.PacketType.SSH_MSG_KEXINIT: this.handleKexInit(<Packets.KexInit>packet); break; case Packets.PacketType.SSH_MSG_KEXDH_INIT: this.handleKexDHInit(<Packets.KexDHInit>packet); break; case Packets.PacketType.SSH_MSG_NEWKEYS: this.handleNewKeys(<Packets.NewKeys>packet); break; case Packets.PacketType.SSH_MSG_DISCONNECT: this.handleDisconnect(<Packets.Disconnect>packet); break; default: SSHLogger.logWarning(util.format("Unhandled packet type: %s", packet.getPacketType())); let unimplemented: Packets.Unimplemented = new Packets.Unimplemented(); unimplemented.rejectedPacketNumber = packet.packetSequence; this.sendPacket(unimplemented); break; } } private handleKexInit(packet: Packets.KexInit): void { SSHLogger.logDebug("Received KexInit"); if (this.m_PendingExchangeContext === null) { SSHLogger.logDebug("Trigger re-exchange from client"); this.m_PendingExchangeContext = new ExchangeContext(); this.sendPacket(this.m_KexInitServerToClient); } this.m_KexInitClientToServer = packet; this.m_PendingExchangeContext.kexAlgorithm = packet.pickKexAlgorithm(); this.m_PendingExchangeContext.hostKeyAlgorithm = packet.pickHostKeyAlgorithm(); this.m_PendingExchangeContext.cipherClientToServer = packet.pickCipherClientToServer(); this.m_PendingExchangeContext.cipherServerToClient = packet.pickCipherServerToClient(); this.m_PendingExchangeContext.macAlgorithmClientToServer = packet.pickMACAlgorithmClientToServer(); this.m_PendingExchangeContext.macAlgorithmServerToClient = packet.pickMACAlgorithmServerToClient(); this.m_PendingExchangeContext.compressionClientToServer = packet.pickCompressionAlgorithmClientToServer(); this.m_PendingExchangeContext.compressionServerToClient = packet.pickCompressionAlgorithmServerToClient(); SSHLogger.logDebug(util.format("Selected KexAlgorithm: %s", this.m_PendingExchangeContext.kexAlgorithm.getName())); SSHLogger.logDebug(util.format("Selected HostKeyAlgorithm: %s", this.m_PendingExchangeContext.hostKeyAlgorithm.getName())); SSHLogger.logDebug(util.format("Selected CipherClientToServer: %s", this.m_PendingExchangeContext.cipherClientToServer.getName())); SSHLogger.logDebug(util.format("Selected CipherServerToClient: %s", this.m_PendingExchangeContext.cipherServerToClient.getName())); SSHLogger.logDebug(util.format("Selected MACAlgorithmClientToServer: %s", this.m_PendingExchangeContext.macAlgorithmClientToServer.getName())); SSHLogger.logDebug(util.format("Selected MACAlgorithmServerToClient: %s", this.m_PendingExchangeContext.macAlgorithmServerToClient.getName())); SSHLogger.logDebug(util.format("Selected CompressionClientToServer: %s", this.m_PendingExchangeContext.compressionClientToServer.getName())); SSHLogger.logDebug(util.format("Selected CompressionServerToClient: %s", this.m_PendingExchangeContext.compressionServerToClient.getName())); } private handleKexDHInit(packet: Packets.KexDHInit): void { SSHLogger.logDebug("Received KexDHInit"); if ((this.m_PendingExchangeContext === null) || (this.m_PendingExchangeContext.kexAlgorithm === null)) { throw new Exceptions.SSHServerException( Exceptions.DisconnectReason.SSH_DISCONNECT_PROTOCOL_ERROR, "Server did not receive SSH_MSG_KEX_INIT as expected."); } // 1. C generates a random number x (1 < x < q) and computes e = g ^ x mod p. C sends e to S. // 2. S receives e. It computes K = e^y mod p let sharedSecret: Buffer = this.m_PendingExchangeContext.kexAlgorithm.decryptKeyExchange(packet.clientValue); // 2. S generates a random number y (0 < y < q) and computes f = g ^ y mod p. let serverKeyExchange: Buffer = this.m_PendingExchangeContext.kexAlgorithm.createKeyExchange(); let hostKey: Buffer = this.m_PendingExchangeContext.hostKeyAlgorithm.createKeyAndCertificatesData(); // h = hash(V_C || V_S || I_C || I_S || K_S || e || f || K) let exchangeHash: Buffer = this.computeExchangeHash( this.m_PendingExchangeContext.kexAlgorithm, hostKey, packet.clientValue, serverKeyExchange, sharedSecret); if (this.m_SessionId === null) { this.m_SessionId = exchangeHash; } // initial IV client to server: HASH(K || H || "A" || session_id) // (Here K is encoded as mpint and "A" as byte and session_id as raw // data. "A" means the single character A, ASCII 65). let clientCipherIV: Buffer = this.computeEncryptionKey( this.m_PendingExchangeContext.kexAlgorithm, exchangeHash, this.m_PendingExchangeContext.cipherClientToServer.getBlockSize(), sharedSecret, "A"); // initial IV server to client: HASH(K || H || "B" || session_id) let serverCipherIV: Buffer = this.computeEncryptionKey( this.m_PendingExchangeContext.kexAlgorithm, exchangeHash, this.m_PendingExchangeContext.cipherServerToClient.getBlockSize(), sharedSecret, "B"); // encryption key client to server: HASH(K || H || "C" || session_id) let clientCipherKey: Buffer = this.computeEncryptionKey( this.m_PendingExchangeContext.kexAlgorithm, exchangeHash, this.m_PendingExchangeContext.cipherClientToServer.getKeySize(), sharedSecret, "C"); // encryption key server to client: HASH(K || H || "D" || session_id) let serverCipherKey: Buffer = this.computeEncryptionKey( this.m_PendingExchangeContext.kexAlgorithm, exchangeHash, this.m_PendingExchangeContext.cipherServerToClient.getKeySize(), sharedSecret, "D"); // integrity key client to server: HASH(K || H || "E" || session_id) let clientHmacKey: Buffer = this.computeEncryptionKey( this.m_PendingExchangeContext.kexAlgorithm, exchangeHash, this.m_PendingExchangeContext.macAlgorithmClientToServer.getKeySize(), sharedSecret, "E"); // integrity key server to client: HASH(K || H || "F" || session_id) let serverHmacKey: Buffer = this.computeEncryptionKey( this.m_PendingExchangeContext.kexAlgorithm, exchangeHash, this.m_PendingExchangeContext.macAlgorithmServerToClient.getKeySize(), sharedSecret, "F"); // set all keys we just generated this.m_PendingExchangeContext.cipherClientToServer.setKey(clientCipherKey, clientCipherIV); this.m_PendingExchangeContext.cipherServerToClient.setKey(serverCipherKey, serverCipherIV); this.m_PendingExchangeContext.macAlgorithmClientToServer.setKey(clientHmacKey); this.m_PendingExchangeContext.macAlgorithmServerToClient.setKey(serverHmacKey); let reply: Packets.KexDHReply = new Packets.KexDHReply(); reply.serverHostKey = hostKey; reply.serverValue = serverKeyExchange; reply.signature = this.m_PendingExchangeContext.hostKeyAlgorithm.createSignatureData(exchangeHash); this.sendPacket(reply); this.sendPacket(new Packets.NewKeys()); } private handleNewKeys(packet: Packets.NewKeys): void { SSHLogger.logDebug("Received NewKeys"); this.m_ActiveExchangeContext = this.m_PendingExchangeContext; this.m_PendingExchangeContext = null; this.m_TotalBytesTransferred = 0; this.resetKeyTimer(); } private handleDisconnect(packet: Packets.Disconnect): void { this.disconnect(packet.reason, packet.description); } private sendRaw(data: Buffer): void { if (!this.getIsConnected()) { return; } // increase bytes transferred this.m_TotalBytesTransferred += data.byteLength; this.m_Socket.write(new Buffer(data)); } private closeReceived(hadError: boolean): void { this.disconnect( Exceptions.DisconnectReason.SSH_DISCONNECT_CONNECTION_LOST, "The client disconnected."); } private getIsDataAvailable(): boolean { if (this.m_Socket == null) { return false; } return (this.m_Socket.bytesRead !== this.m_LastBytesRead); } private readBytes(size: number): Buffer { if (this.m_Socket == null) { return null; } let buffer: Buffer = this.m_Socket.read(size); if (buffer === null) { throw new Exceptions.SSHServerException( Exceptions.DisconnectReason.SSH_DISCONNECT_CONNECTION_LOST, "Failed to read from socket."); } if (buffer.byteLength !== size) { throw new Exceptions.SSHServerException( Exceptions.DisconnectReason.SSH_DISCONNECT_CONNECTION_LOST, "Failed to read from socket."); } this.m_LastBytesRead += size; return buffer; } private getDataAvailable(): number { if (this.m_Socket == null) { return 0; } return (this.m_Socket.bytesRead - this.m_LastBytesRead); } private readProtocolVersionExchange(): void { let data: Array<number> = new Array<number>(); let foundCR: boolean = false; let value: Buffer = this.readBytes(1); while (value != null) { if (foundCR && (value[0] === 10)) { // done this.m_HasCompletedProtocolVersionExchange = true; break; } if (value[0] === 13) { foundCR = true; } else { foundCR = false; data.push(value[0]); } value = this.readBytes(1); } this.m_ProtocolVersionExchange += new Buffer(data).toString("UTF8"); } private readPacket(): Packets.Packet { if (this.m_Socket == null) { return; } let blockSize: number = this.m_ActiveExchangeContext.cipherClientToServer.getBlockSize(); // we must have at least 1 block to read if (this.getDataAvailable() < blockSize) { return null; // packet not here } let firstBlock: Buffer = this.m_ActiveExchangeContext.cipherClientToServer.decrypt(this.readBytes(blockSize)); let reader: ByteReader = new ByteReader(firstBlock); // uint32 packet_length // packet_length // the length of the packet in bytes, not including 'mac' or the // 'packet_length' field itself. let packetLength: number = reader.getUInt32(); if (packetLength > Packets.Packet.MaxPacketSize) { throw new Exceptions.SSHServerException( Exceptions.DisconnectReason.SSH_DISCONNECT_PROTOCOL_ERROR, util.format( "Client tried to send a packet bigger than MaxPacketSize (%d bytes): %d bytes", Packets.Packet.MaxPacketSize, packetLength)); } // byte padding_length // padding_length // length of 'random padding' (bytes). let paddingLength: number = reader.getByte(); // byte[n1] payload; n1 = packet_length - padding_length - 1 // payload // the useful contents of the packet. If compression has been // negotiated, this field is compressed. Initially, compression // must be "none". let bytesToRead: number = packetLength - blockSize + 4; let restOfPacket: Buffer = this.m_ActiveExchangeContext.cipherClientToServer.decrypt(this.readBytes(bytesToRead)); let payloadLength: number = packetLength - paddingLength - 1; let fullPacket: Buffer = Buffer.concat([ firstBlock, restOfPacket ]); // track total bytes read this.m_TotalBytesTransferred += fullPacket.byteLength; let payload: Buffer = fullPacket.slice( Packets.Packet.PacketHeaderSize, Packets.Packet.PacketHeaderSize + payloadLength); // byte[n2] random padding; n2 = padding_length // random padding // arbitrary-length padding, such that the total length of // (packet_length || padding_length || payload || random padding) // is a multiple of the cipher block size or 8, whichever is // larger. There MUST be at least four bytes of padding. The // padding SHOULD consist of random bytes. The maximum amount of // padding is 255 bytes. // byte[m] mac (Message Authentication Code - MAC); m = mac_length // mac // message Authentication Code. If message authentication has // been negotiated, this field contains the MAC bytes. Initially, // the MAC algorithm MUST be "none". let packetNumber: number = this.m_CurrentReceivedPacketNumber; this.m_CurrentReceivedPacketNumber += 1; if (this.m_ActiveExchangeContext.macAlgorithmClientToServer != null) { let clientMac: Buffer = this.readBytes(this.m_ActiveExchangeContext.macAlgorithmClientToServer.getDigestLength()); let mac: Buffer = this.m_ActiveExchangeContext.macAlgorithmClientToServer.computeHash(packetNumber, fullPacket); if (clientMac.compare(mac) !== 0) { throw new Exceptions.SSHServerException( Exceptions.DisconnectReason.SSH_DISCONNECT_MAC_ERROR, "MAC from client is invalid"); } } payload = this.m_ActiveExchangeContext.compressionClientToServer.decompress(payload); let packetReader: ByteReader = new ByteReader(payload); let packetType: Packets.PacketType = packetReader.getByte(); let packet: Packets.Packet = Client.createPacket(packetType); if (packet != null) { SSHLogger.logDebug(util.format("Received Packet: %s", Packets.PacketType[packetType])); packet.load(packetReader); } return packet; } private considerReExchange(): void { const OneGB: number = (1024 * 1024 * 1024); if (this.m_TotalBytesTransferred > OneGB) { this.reExchangeKeys(); } } private resetKeyTimer(): void { const MSInOneHour: number = 1000 * 60 * 60; if (this.m_KeyTimeout !== null) { clearTimeout(this.m_KeyTimeout); } this.m_KeyTimeout = setTimeout(this.reExchangeKeys, MSInOneHour); } private reExchangeKeys(): void { // time to get new keys! this.m_TotalBytesTransferred = 0; this.resetKeyTimer(); SSHLogger.logDebug("Trigger re-exchange from server"); this.m_PendingExchangeContext = new ExchangeContext(); this.sendPacket(this.m_KexInitServerToClient); } private computeExchangeHash( kexAlgorithm: IKexAlgorithm, hostKeyAndCerts: Buffer, clientExchangeValue: Buffer, serverExchangeValue: Buffer, sharedSecret: Buffer): Buffer { let writer: ByteWriter = new ByteWriter(); writer.writeString(this.m_ProtocolVersionExchange); writer.writeString(Server.ProtocolVersionExchange); writer.writeBytes(this.m_KexInitClientToServer.getBytes()); writer.writeBytes(this.m_KexInitServerToClient.getBytes()); writer.writeBytes(hostKeyAndCerts); writer.writeMPInt(clientExchangeValue); writer.writeMPInt(serverExchangeValue); writer.writeMPInt(sharedSecret); return kexAlgorithm.computeHash(writer.toBuffer()); } private computeEncryptionKey(kexAlgorithm: IKexAlgorithm, exchangeHash: Buffer, keySize: number, sharedSecret: Buffer, letter: string): Buffer { // k(X) = HASH(K || H || X || session_id) // prepare the buffer let keyBuffer: Buffer = new Buffer(keySize); let keyBufferIndex: number = 0; let currentHashLength: number = 0; let currentHash: Buffer = null; // we can stop once we fill the key buffer while (keyBufferIndex < keySize) { let writer: ByteWriter = new ByteWriter(); // write "K" writer.writeMPInt(sharedSecret); // write "H" writer.writeRawBytes(exchangeHash); if (currentHash === null) { // if we haven't done this yet, add the "X" and session_id writer.writeByte(letter.charCodeAt(0)); writer.writeRawBytes(this.m_SessionId); } else { // if the key isn't long enough after the first pass, we need to // write the current hash as described here: // k1 = HASH(K || H || X || session_id) (X is e.g., "A") // k2 = HASH(K || H || K1) // k3 = HASH(K || H || K1 || K2) // ... // key = K1 || K2 || K3 || ... writer.writeRawBytes(currentHash); } currentHash = kexAlgorithm.computeHash(writer.toBuffer()); currentHashLength = Math.min(currentHash.byteLength, (keySize - keyBufferIndex)); currentHash.copy(keyBuffer, keyBufferIndex, 0, currentHashLength); keyBufferIndex += currentHashLength; } return keyBuffer; } private validateProtocolVersionExchange(): void { // https://tools.ietf.org/html/rfc4253#section-4.2 // - SSH-protoversion-softwareversion SP comments let pveParts: string[] = this.m_ProtocolVersionExchange.split(" "); if (pveParts.length == 0) { throw new Error("Invalid Protocol Version Exchange was received - No Data"); } let versionParts: string[] = pveParts[0].split("-"); if (versionParts.length < 3) { throw new Error(util.format("Invalid Protocol Version Exchange was received - Not enough dashes - %s", pveParts[0])); } if (versionParts[1] !== "2.0") { throw new Error(util.format("Invalid Protocol Version Exchange was received - Unsupported Version - %s", versionParts[1])); } // if we get here, all is well! } private static createPacket(packetType: Packets.PacketType): Packets.Packet { switch (packetType) { case Packets.PacketType.SSH_MSG_KEXINIT: return new Packets.KexInit(); case Packets.PacketType.SSH_MSG_KEXDH_INIT: return new Packets.KexDHInit(); case Packets.PacketType.SSH_MSG_NEWKEYS: return new Packets.NewKeys(); case Packets.PacketType.SSH_MSG_DISCONNECT: return new Packets.Disconnect(); } SSHLogger.logDebug(util.format("Unknown PacketType: %s", Packets.PacketType[packetType])); return null; } }
the_stack
import { JsonRPCRequest, JsonRPCResponse } from './jsonrpc'; import { BigNumber } from 'bignumber.js'; // TODO change to BN import Web3JS = require('web3'); // W3 is the only class wrapper over JS object, others are interfaces // cannot just cast from JS, but ctor does some standard logic to resolve web3 // so we do not need cast but could just use new W3() /** Convert number or hex string to BigNumber */ export function toBN(value: number): BigNumber { // TODO BN.js return new BigNumber(value); } // tslint:disable:member-ordering // tslint:disable:max-line-length /** * Strongly-types wrapper over web3.js with additional helper methods. */ export class W3 { private static _counter: number = 0; private static _default: W3; private _globalWeb3; private _netId: string; private _netNode: Promise<string>; private _defaultAccount: string; private _defaultTimeout: number = 240000; /** * Default W3 instance that is used as a fallback when such an instance is not provided to a constructor. * You must set it explicitly via W3.default setter. Use an empty `new W3()` constructor to get an instance that * automatically resolves to a global web3 instance `window['web3']` provided by e.g. MIST/Metamask or connects * to the default 8545 port if no global instance is present. */ public static get default(): W3 { if (W3._default) { return W3._default; } throw 'Default W3 instance is not set. Use W3.default setter.'; } /** * Set default W3 instance. */ public static set default(w3: W3) { W3._default = w3; } /** Get Global W3 incrementing counter. Starts with zero. */ public static getNextCounter(): number { // node is single-threaded // same provider in two W3 instances is OK, counter will be unique accross them let value = W3._counter; W3._counter++; return value; } /** Web3 providers. */ public static providers: W3.Providers = Web3JS.providers; /** Current Web3 provider. */ public get currentProvider(): W3.Provider { return this.web3 ? this.web3.currentProvider : undefined; } /** Convert number or hex string to BigNumber */ public toBigNumber(value: number | string): BigNumber { return this.web3.toBigNumber(value); } /** Converts a number or number string to its HEX representation. */ public fromDecimal(value: number | string): string { return this.web3.fromDecimal(value); } /** * web3.js untyped instance created with a resolved or given in ctor provider, if any. */ public web3; /** Default account for sending transactions without explicit txParams. */ public get defaultAccount(): string { return this._defaultAccount; } public set defaultAccount(defaultAccount: string) { this._defaultAccount = defaultAccount; this.web3.defaultAccount = defaultAccount; } /** Default timeout in seconds. */ public get defaultTimeout(): number { return this._defaultTimeout / 1000; } public set defaultTimeout(defaultTimeout: number) { if (defaultTimeout && defaultTimeout > 240) { this._defaultTimeout = defaultTimeout; } else { throw new Error('Bad defaultTimeout value.'); } } /** * Create a default Web3 instance - resolves to a global window['web3'] injected my MIST, MetaMask, etc * or to `localhost:8545` if not running on https. */ constructor(); /** * Create a W3 instance with a given provider. * @param provider web3.js provider. */ constructor(provider?: W3.Provider); constructor(provider?: W3.Provider, defaultAccount?: string) { let tmpWeb3; if (typeof provider === 'undefined') { // tslint:disable-next-line:no-string-literal if ( (typeof window !== 'undefined' && typeof window['web3'] !== 'undefined' && typeof window['web3'].currentProvider !== 'undefined') || this._globalWeb3 ) { // tslint:disable-next-line:no-string-literal this._globalWeb3 = window['web3']; // tslint:disable-next-line:no-string-literal tmpWeb3 = new Web3JS(this._globalWeb3.currentProvider); console.log('Using an injected web3 provider.'); } else { // set the provider you want from Web3.providers if (typeof window === 'undefined' || window.location.protocol !== 'https:') { tmpWeb3 = new Web3JS(new Web3JS.providers.HttpProvider('http://localhost:8545')); console.log('Cannot find an injected web3 provider. Using HttpProvider(http://localhost:8545).'); } else { // tslint:disable-next-line:max-line-length console.log( 'Cannot find an injected web3 provider. Running on https, will not try to access localhost at 8545' ); } } } else { // regardless if a web3 exists, we create a new one for a specific provider tmpWeb3 = new Web3JS(provider); console.log('Using a provider from constructor.'); } if (!tmpWeb3.version.api.startsWith('0.20')) { throw 'Only web3 0.20.xx package is currently supported'; } this.web3 = tmpWeb3; // set and override eth's default account with a given value or use eth's one if it is set if (defaultAccount) { // set property, that will also set this.web3.defaultAccount this.defaultAccount = defaultAccount; } else if (this.web3.defaultAccount) { // set private field directly this._defaultAccount = this.web3.defaultAccount; } this.updateNetworkInfo(); } /** Request netid string from ctor or after provider change */ private updateNetworkInfo(netid?: string): void { if (!netid) { this.networkId.then(nid => (this._netId = nid)); } else { this._netId = netid; } this._netNode = new Promise((resolve, reject) => this.web3.version.getNode((error, result) => (error ? reject(error) : resolve(result))) ); } /* Below are frequently used functions that should not depend on web3 API (0.20 or 1.0). Will update them for web3 1.0 when truffle-contract support it without sendAsync error. */ /** Returns a list of accounts the node controlst */ public get accounts(): Promise<string[]> { return new Promise((resolve, reject) => this.web3.eth.getAccounts((error, result) => (error ? reject(error) : resolve(result))) ); } /** Web3.js version API */ public get web3API(): string { return this.web3.version.api; } /** True if current web3.js version is 0.20.x. */ public get isPre1API(): boolean { return this.web3API.startsWith('0.20.'); } /** True if current node name contains TestRPC string */ public get isTestRPC(): Promise<boolean> { return this._netNode.then(node => { return node.includes('TestRPC'); }); } /** Get network ID. */ public get networkId(): Promise<string> { return new Promise((resolve, reject) => this.web3.version.getNetwork((error, result) => { if (error) { return reject(error); } if (result + '' !== this._netId) { this.updateNetworkInfo(result + ''); } return resolve(result); }) ); } /** Set web3 provider and update network info asynchronously. */ public setProvider(provider: W3.Provider) { this.web3.setProvider(provider); this.updateNetworkInfo(); } /** Send raw JSON RPC request to the current provider. */ public sendRPC(payload: JsonRPCRequest): Promise<JsonRPCResponse> { return new Promise((resolve, reject) => { if (this.isPre1API) { this.web3.currentProvider.sendAsync(payload, (e, r) => { if (e) { reject(e); } else { resolve(r); } }); } else { this.web3.currentProvider.send(payload, (e, r) => { if (e) { reject(e); } else { resolve(r); } }); } }); } /** Returns the time of the last mined block in seconds. */ public get latestTime(): Promise<number> { return new Promise((resolve, reject) => { if (this.isPre1API) { this.web3.eth.getBlock('latest', (err, res) => { if (err) { reject(err); } else { resolve(res.timestamp as number); } }); } else { reject('web3 1.0 support is not implemented'); } }); } /** Returns the current block number */ public get blockNumber(): Promise<number> { // getBlockNumber(callback: (err: Error, blockNumber: number) => void): void; return new Promise((resolve, reject) => { if (this.isPre1API) { this.web3.eth.getBlockNumber((err, res) => { if (err) { reject(err); } else { resolve(res as number); } }); } else { reject('web3 1.0 support is not implemented'); } }); } /** Async unlock while web3.js only has sync version. This function uses `personal_unlockAccount` RPC message that is not available in some web3 providers. */ public async unlockAccount(address: string, password: string, duration?: number): Promise<boolean> { const id = 'W3:' + W3.getNextCounter(); return this.sendRPC({ jsonrpc: '2.0', method: 'personal_unlockAccount', params: [address, password, duration || 10], id: id }).then(async r => { if (r.error) { return false; } return <boolean>r.result; }); } /** Get account balance */ public async getBalance(address: string): Promise<BigNumber> { return new Promise<BigNumber>((resolve, reject) => { this.web3.eth.getBalance(address, (error, result) => { if (error) { reject(error); } else { resolve(result as BigNumber); } }); }); } /** Sign using eth.sign but with prefix as personal_sign */ public async ethSignRaw(hex: string, account: string): Promise<string> { // NOTE geth already adds the prefix to eth.sign, no need to do so manually // hex = hex.replace('0x', ''); // let prefix = '\x19Ethereum Signed Message:\n' + (hex.length / 2); // let message = this.web3.toHex(prefix) + hex; return new Promise<string>((resolve, reject) => { this.web3.eth.sign(account, hex, (err, res) => { if (err) { reject(err); } resolve(res); }); }); } /** Sign a message */ public async sign(message: string, account: string, password?: string): Promise<string> { message = W3.toHex(message); return this.signRaw(message, account, password); } /** Message already as hex */ public async signRaw(message: any, account: string, password?: string): Promise<string> { const id = 'W3:' + W3.getNextCounter(); console.log('signRaw MESSAGE', message); return this.sendRPC({ jsonrpc: '2.0', method: 'personal_sign', params: password ? [message, account, password] : [message, account], id: id }).then(async r => { if (r.error) { console.log('ERROR:', r.error); throw new Error(r.error.message); } return <string>r.result; }); } /** True if current web3 provider is from MetaMask. */ public get isMetaMask() { try { return this.web3.currentProvider.isMetaMask ? true : false; } catch { return false; } } /** * Get the numbers of transactions sent from this address. * @param account The address to get the numbers of transactions from. * @param defaultBlock (optional) If you pass this parameter it will not use the default block set with. */ public async getTransactionCount(account?: string, defaultBlock?: number | string): Promise<number> { account = account || this.defaultAccount; if (!account) { throw new Error('No default account set to call getTransactionCount without a given account address'); } return new Promise<number>((resolve, reject) => { this.web3.eth.getTransactionCount(account, defaultBlock, (e, r) => { if (e) { reject(e); } else { resolve(r); } }); }); } /** * Sends a raw signed transaction and returns tx hash. Use waitTransactionReceipt method on w3 or a contract to get a tx receipt. * @param to Target contract address or zero address (W3.zeroAddress) to deploy a new contract. * @param privateKey Private key hex string prefixed with 0x. * @param data Payload data. * @param txParams Tx parameters. * @param nonce Nonce override if needed to replace a pending transaction. */ public async sendSignedTransaction( to: string, privateKey: string, data?: string, txParams?: W3.TX.TxParams, nonce?: number ): Promise<string> { if (!this.isPre1API) { throw new Error('Web3.js v.1.0 is not supported yet'); } if (!to || !W3.isValidAddress(to)) { throw new Error('To address is not set in sendSignedTransaction'); } if (!privateKey) { throw new Error('PrivateKey is not set in sendSignedTransaction'); } txParams = txParams || W3.TX.txParamsDefaultSend(this.defaultAccount); nonce = nonce || (await this.getTransactionCount(txParams.from)); let EthereumTx = W3.TX.getEthereumjsTx(); let pb = W3.EthUtils.toBuffer(privateKey); let nid = +(this._netId || (await this.networkId)); const signedTxParams = { nonce: W3.toHex(nonce), gasPrice: W3.toHex(txParams.gasPrice), gasLimit: W3.toHex(txParams.gas), to: to, value: W3.toHex(txParams.value), data: data, chainId: nid }; if (W3.zeroAddress === to) { delete signedTxParams.to; } const tx = new EthereumTx(signedTxParams); tx.sign(pb); const serializedTx = tx.serialize(); const raw = `0x${serializedTx.toString('hex')}`; return new Promise<string>((resolve, reject) => { this.web3.eth.sendRawTransaction(raw, (e, r) => { if (e) { reject(e); } else { resolve(r); } }); }); } /** * Returns the receipt of a transaction by transaction hash. Retries for up to 240 seconds. * @param hashString The transaction hash. * @param timeoutSeconds Timeout in seconds, must be above 240 or ignored. */ public async waitTransactionReceipt(hashString: string, timeoutSeconds?: number): Promise<W3.TransactionReceipt> { return new Promise<W3.TransactionReceipt>((accept, reject) => { var timeout = timeoutSeconds && timeoutSeconds > 240 ? timeoutSeconds * 1000 : this._defaultTimeout; var start = new Date().getTime(); let makeAttempt = () => { this.web3.eth.getTransactionReceipt(hashString, (err, receipt) => { if (err) { return reject(err); } if (receipt != null) { return accept(receipt); } if (timeout > 0 && new Date().getTime() - start > timeout) { return reject( new Error('Transaction ' + hashString + " wasn't processed in " + timeout / 1000 + ' seconds!') ); } setTimeout(makeAttempt, 1000); }); }; makeAttempt(); }); } } export namespace W3 { /** Type alias for Ethereum address. */ export type address = string; /** Type alias for bytes string. */ export type bytes = string; /** Hex zero address. */ export const zeroAddress: string = '0x0000000000000000000000000000000000000000'; /** Check if Ethereum address is in valid format. */ export function isValidAddress(addr: address): boolean { return W3.EthUtils.isValidAddress(addr); } /** Utf8 package. */ export let Utf8: any = require('utf8'); /** * Convert value to hex with optional left padding. If a string is already a hex it will be converted to lower case. * @param value Value to convert to hex * @param size Size of number in bits (8 for int8, 16 for uint16, etc) */ export function toHex(value: number | string | BigNumber, stripPrefix?: boolean, size?: number): string { const HEX_CHAR_SIZE = 4; if (typeof value === 'string') { if (size) { throw new Error('W3.toHex: using optional size argument with strings is not supported'); } if (!value.startsWith('0x')) { // non-hex string return W3.utf8ToHex(value, stripPrefix); } else { let lowerCase = value.toLowerCase(); return stripPrefix ? lowerCase.slice(2) : lowerCase; } } let hexWithPrefix: string; if ((value as any).isBigNumber) { let bn = value as BigNumber; let hex = bn.toString(16); hexWithPrefix = bn.lessThan(0) ? '-0x' + hex.substr(1) : '0x' + hex; } else { hexWithPrefix = EthUtils.bufferToHex(EthUtils.toBuffer(value as any)); } // numbers, big numbers, and hex strings if (size) { // tslint:disable-next-line:no-bitwise let hexNoPrefix = hexWithPrefix.slice(2); // tslint:disable-next-line:no-bitwise let leftPadded = W3.leftPad(hexNoPrefix, size / HEX_CHAR_SIZE, value < 0 ? 'F' : '0'); return stripPrefix ? leftPadded : '0x' + leftPadded; } else { // tslint:disable-next-line:no-bitwise return stripPrefix ? hexWithPrefix.slice(2) : hexWithPrefix; } } /** String left pad. Same as the notorious left-pad package as a single function. */ export function leftPad(str: string, len: number, ch: any) { // the notorious 12-lines npm package str = String(str); var i = -1; if (!ch && ch !== 0) { ch = ' '; } len = len - str.length; while (++i < len) { str = ch + str; } return str; } /** Utf8 to hex convertor. */ export function utf8ToHex(str: string, stripPrefix?: boolean): string { // this is from web3 1.0 str = W3.Utf8.encode(str); let hex = ''; // remove \u0000 padding from either side str = str.replace(/^(?:\u0000)*/, ''); str = str .split('') .reverse() .join(''); str = str.replace(/^(?:\u0000)*/, ''); str = str .split('') .reverse() .join(''); for (let i = 0; i < str.length; i++) { let code = str.charCodeAt(i); // if (code !== 0) { let n = code.toString(16); hex += n.length < 2 ? '0' + n : n; // } } return stripPrefix ? hex : '0x' + hex; } /** Ethereumjs-util package. */ export let EthUtils: W3.EthUtils = require('ethereumjs-util'); /** Creates SHA-3 hash of the input. */ export function sha3(a: Buffer | Array<any> | string | number, bits?: number): string { return EthUtils.bufferToHex(EthUtils.sha3(a, bits)); } /** Creates SHA256 hash of the input. */ export function sha256(a: Buffer | Array<any> | string | number): string { return EthUtils.bufferToHex(EthUtils.sha256(a)); } /** ECDSA sign. */ export function sign(message: any, privateKey: string): bytes { let mb = W3.EthUtils.toBuffer(message); let pb = W3.EthUtils.toBuffer(privateKey); let personalHash = W3.EthUtils.hashPersonalMessage(mb); let signature = W3.EthUtils.ecsign(personalHash, pb); let rpcSignature = W3.EthUtils.toRpcSig(signature.v, signature.r, signature.s); return rpcSignature; } /** ECDSA public key recovery from signature. */ export function ecrecover(message: string, signature: string): address { let mb = W3.EthUtils.toBuffer(message); let sigObject = W3.EthUtils.fromRpcSig(signature); let personalHash = W3.EthUtils.hashPersonalMessage(mb); let recoveredPubKeyBuffer = W3.EthUtils.ecrecover(personalHash, sigObject.v, sigObject.r, sigObject.s); let recoveredAddress = W3.EthUtils.pubToAddress(recoveredPubKeyBuffer); let addr = W3.EthUtils.bufferToHex(recoveredAddress); return addr; } let _keythereum: any; /** * Get Keythereum instance. https://github.com/ethereumjs/keythereum */ export function getKeythereum() { if (_keythereum) { return _keythereum; } // tslint:disable-next-line:no-string-literal if (typeof window !== 'undefined' && typeof window['keythereum'] !== 'undefined') { // tslint:disable-next-line:no-string-literal _keythereum = window['keythereum']; } else { _keythereum = require('keythereum'); } return _keythereum; } /** Truffle Contract */ export namespace TX { /** Standard transaction parameters. */ export interface TxParams { from: address; gas: number | BigNumber; gasPrice: number | BigNumber; value: number | BigNumber; } export type ContractDataType = BigNumber | number | string | boolean | BigNumber[] | number[] | string[]; export interface TransactionResult { /** Transaction hash. */ tx: string; receipt: TransactionReceipt; /** This array has decoded events, while reseipt.logs has raw logs when returned from TC transaction */ logs: Log[]; } /** 4500000 gas @ 2 Gwei */ export function txParamsDefaultDeploy(from: address, gas?: number, gasPrice?: number): TxParams { if (gasPrice && gasPrice > 40000000000) { throw new Error( `Given gasPrice ${gasPrice} is above 40Gwei (our default is 2 Gwei, common value for fast transactions is 20Gwei), this could be costly. Construct txParams manually if you know what you are doing.` ); } if (gas && gas > 4500000) { throw new Error(`Given gas ${gas} is too large and could exceed block size.`); } return { from: from, gas: gas || 4500000, gasPrice: gasPrice || 2000000000, // 2 Gwei, not 20 value: 0 }; } /** 50000 gas @ 2 Gwei */ export function txParamsDefaultSend(from: address, gas?: number, gasPrice?: number): TxParams { if (gasPrice && gasPrice > 40000000000) { throw new Error( `Given gasPrice ${gasPrice} is above 40Gwei (our default is 2 Gwei, common value for fast transactions is 20Gwei), this could be costly. Construct txParams manually if you know what you are doing.` ); } if (gas && gas > 500000) { throw new Error( `Given gas ${gas} is too large for a normal transaction (>500k). Use txParamsDefaultDeploy or construct params manually.` ); } return { from: from, gas: gas || 50000, gasPrice: gasPrice || 2000000000, // 2 Gwei, not 20 value: 0 }; } let _ethereumjsTx: any; export function getEthereumjsTx() { if (_ethereumjsTx) { return _ethereumjsTx; } // tslint:disable-next-line:no-string-literal if (typeof window !== 'undefined' && typeof window['ethereumjs-tx'] !== 'undefined') { // tslint:disable-next-line:no-string-literal _ethereumjsTx = window['ethereumjs-tx']; } else { _ethereumjsTx = require('ethereumjs-tx'); } return _ethereumjsTx; } } export interface Provider { sendAsync(payload: JsonRPCRequest, callback: (err: Error, result: JsonRPCResponse) => void): void; } // export interface Provider { // send(payload: JsonRPCRequest, callback: (e: Error, val: JsonRPCResponse) => void); // } export interface WebsocketProvider extends Provider {} export interface HttpProvider extends Provider {} export interface IpcProvider extends Provider {} export interface Providers { WebsocketProvider: new (host: string, timeout?: number) => WebsocketProvider; HttpProvider: new (host: string, timeout?: number) => HttpProvider; IpcProvider: new (path: string, net: any) => IpcProvider; } // tslint:disable-next-line:max-line-length export type Unit = | 'kwei' | 'femtoether' | 'babbage' | 'mwei' | 'picoether' | 'lovelace' | 'qwei' | 'nanoether' | 'shannon' | 'microether' | 'szabo' | 'nano' | 'micro' | 'milliether' | 'finney' | 'milli' | 'ether' | 'kether' | 'grand' | 'mether' | 'gether' | 'tether'; export type BlockType = 'latest' | 'pending' | 'genesis' | number; export interface BatchRequest { add(request: Request): void; execute(): void; } export interface Iban {} export interface Utils { BN: BigNumber; // TODO only static-definition isBN(obj: any): boolean; isBigNumber(obj: any): boolean; isAddress(obj: any): boolean; isHex(obj: any): boolean; asciiToHex(val: string): string; hexToAscii(val: string): string; bytesToHex(val: number[]): string; numberToHex(val: number | BigNumber): string; checkAddressChecksum(address: string): boolean; fromAscii(val: string): string; fromDecimal(val: string | number | BigNumber): string; fromUtf8(val: string): string; fromWei(val: string | number | BigNumber, unit: Unit): string | BigNumber; hexToBytes(val: string): number[]; hexToNumber(val: string | number | BigNumber): number; hexToNumberString(val: string | number | BigNumber): string; hexToString(val: string): string; hexToUtf8(val: string): string; keccak256(val: string): string; leftPad(str: string, chars: number, sign: string): string; padLeft(str: string, chars: number, sign: string): string; rightPad(str: string, chars: number, sign: string): string; padRight(str: string, chars: number, sign: string): string; sha3(val: string, val2?: string, val3?: string, val4?: string, val5?: string): string; soliditySha3(val: string): string; randomHex(bytes: number): string; stringToHex(val: string): string; toAscii(hex: string): string; toBN(obj: any): BigNumber; toChecksumAddress(val: string): string; toDecimal(val: any): number; toHex(val: any): string; toUtf8(val: any): string; toWei(val: string | number | BigNumber, unit: Unit): string | BigNumber; // tslint:disable-next-line:member-ordering unitMap: any; } /** * https://github.com/ethereumjs/ethereumjs-util/blob/master/docs/index.md */ export interface EthUtils { /** BN.js */ BN: BigNumber; /** Adds "0x" to a given String if it does not already start with "0x". */ addHexPrefix(str: string): string; /** Converts a Buffer or Array to JSON. */ baToJSON(ba: Buffer | Array<any>): any; bufferToHex(buf: Buffer): string; bufferToInt(buf: Buffer): number; ecrecover(msgHash: Buffer, v: number, r: Buffer, s: Buffer): Buffer; ecsign(msgHash: Buffer, privateKey: Buffer): any; fromRpcSig(sig: string): any; fromSigned(num: Buffer): any; // TODO BN generateAddress(from: Buffer, nonce: Buffer): Buffer; hashPersonalMessage(message: Buffer): Buffer; importPublic(publicKey: Buffer): Buffer; isValidAddress(address: string): boolean; isValidChecksumAddress(address: Buffer): boolean; isValidPrivate(privateKey: Buffer): boolean; isValidPublic(privateKey: Buffer, sanitize: boolean): any; isValidSignature(v: number, r: Buffer, s: Buffer, homestead?: boolean): any; privateToAddress(privateKey: Buffer): Buffer; pubToAddress(privateKey: Buffer, sanitize?: boolean): Buffer; sha256(a: Buffer | Array<any> | string | number): Buffer; /** Keccak[bits] */ sha3(a: Buffer | Array<any> | string | number, bits?: number): Buffer; SHA3_NULL: Buffer; SHA3_NULL_S: string; toBuffer(v: any): Buffer; toChecksumAddress(address: string): string; toRpcSig(v: number, r: Buffer, s: Buffer): string; privateToPublic(privateKey: Buffer): Buffer; zeros(bytes: number): Buffer; } export type Callback<T> = (error: Error, result: T) => void; export type ABIDataTypes = 'uint256' | 'boolean' | 'string' | 'bytes' | string; // TODO complete list export interface ABIDefinition { constant?: boolean; payable?: boolean; anonymous?: boolean; inputs?: Array<{ name: string; type: ABIDataTypes; indexed?: boolean }>; name?: string; outputs?: Array<{ name: string; type: ABIDataTypes }>; type: 'function' | 'constructor' | 'event' | 'fallback'; } export interface CompileResult { code: string; info: { source: string; language: string; languageVersion: string; compilerVersion: string; abiDefinition: Array<ABIDefinition>; }; userDoc: { methods: object }; developerDoc: { methods: object }; } export interface Transaction { hash: string; nonce: number; blockHash: string; blockNumber: number; transactionIndex: number; from: string; to: string; value: string; gasPrice: string; gas: number; input: string; v?: string; r?: string; s?: string; } export interface TransactionReceipt { transactionHash: string; transactionIndex: number; blockHash: string; blockNumber: number; from: string; to: string; contractAddress: string; cumulativeGasUsed: number; gasUsed: number; logs?: Log[]; events?: { [eventName: string]: EventLog; }; } export interface BlockHeader { number: number; hash: string; parentHash: string; nonce: string; sha3Uncles: string; logsBloom: string; transactionRoot: string; stateRoot: string; receiptRoot: string; miner: string; extraData: string; gasLimit: number; gasUsed: number; timestamp: number; } export interface Block extends BlockHeader { transactions: Array<Transaction>; size: number; difficulty: number; totalDifficulty: number; uncles: Array<string>; } export interface Logs { fromBlock?: number; address?: string; topics?: Array<string | string[]>; } /** Transaction log entry. */ export interface Log { address: string; logIndex: number; transactionIndex: number; transactionHash: string; blockHash: string; blockNumber: number; /** true when the log was removed, due to a chain reorganization. false if its a valid log. */ removed?: boolean; data?: string; topics?: Array<string>; /** Event name decoded by Truffle-contract */ event?: string; /** Truffle-contract returns this as 'mined' */ type?: string; /** Args passed to a Truffle-contract method */ args?: any; } export interface EventLog extends Log { event: string; // from parent Log // address: string; // logIndex: number; // transactionIndex: number; // transactionHash: string; // blockHash: string; // blockNumber: number; returnValues: any; signature: string | null; raw?: { data: string; topics: any[] }; } export interface Subscribe<T> { subscription: { id: string; subscribe(callback?: Callback<Subscribe<T>>): Subscribe<T>; unsubscribe(callback?: Callback<boolean>): void | boolean; // tslint:disable-next-line:member-ordering arguments: object; }; /* on(type: "data" , handler:(data:Transaction)=>void): void on(type: "changed" , handler:(data:Logs)=>void): void on(type: "error" , handler:(data:Error)=>void): void on(type: "block" , handler:(data:BlockHeader)=>void): void */ on(type: 'data', handler: (data: T) => void): void; on(type: 'changed', handler: (data: T) => void): void; on(type: 'error', handler: (data: Error) => void): void; } export interface Account { address: string; privateKey: string; publicKey: string; } export interface PrivateKey { address: string; Crypto: { cipher: string; ciphertext: string; cipherparams: { iv: string; }; kdf: string; kdfparams: { dklen: number; n: number; p: number; r: number; salt: string; }; mac: string; }; id: string; version: number; } export interface Signature { message: string; hash: string; r: string; s: string; v: string; } export interface Tx { nonce?: string | number; chainId?: string | number; from?: string; to?: string; data?: string; value?: string | number; gas?: string | number; gasPrice?: string | number; } export interface ContractOptions { address: string; jsonInterface: ABIDefinition[]; from?: string; gas?: string | number | BigNumber; gasPrice?: number; data?: string; } export type PromiEventType = 'transactionHash' | 'receipt' | 'confirmation' | 'error'; export interface PromiEvent<T> extends Promise<T> { once(type: 'transactionHash', handler: (receipt: string) => void): PromiEvent<T>; once(type: 'receipt', handler: (receipt: TransactionReceipt) => void): PromiEvent<T>; once(type: 'confirmation', handler: (confNumber: number, receipt: TransactionReceipt) => void): PromiEvent<T>; once(type: 'error', handler: (error: Error) => void): PromiEvent<T>; // tslint:disable-next-line:max-line-length once( type: 'error' | 'confirmation' | 'receipt' | 'transactionHash', handler: (error: Error | TransactionReceipt | string) => void ): PromiEvent<T>; on(type: 'transactionHash', handler: (receipt: string) => void): PromiEvent<T>; on(type: 'receipt', handler: (receipt: TransactionReceipt) => void): PromiEvent<T>; on(type: 'confirmation', handler: (confNumber: number, receipt: TransactionReceipt) => void): PromiEvent<T>; on(type: 'error', handler: (error: Error) => void): PromiEvent<T>; // tslint:disable-next-line:max-line-length on( type: 'error' | 'confirmation' | 'receipt' | 'transactionHash', handler: (error: Error | TransactionReceipt | string) => void ): PromiEvent<T>; } export interface EventEmitter { on(type: 'data', handler: (event: EventLog) => void): EventEmitter; on(type: 'changed', handler: (receipt: EventLog) => void): EventEmitter; on(type: 'error', handler: (error: Error) => void): EventEmitter; // tslint:disable-next-line:max-line-length on(type: 'error' | 'data' | 'changed', handler: (error: Error | TransactionReceipt | string) => void): EventEmitter; } export interface TransactionObject<T> { arguments: any[]; call(tx?: Tx): Promise<T>; send(tx?: Tx): PromiEvent<T>; estimateGas(tx?: Tx): Promise<number>; encodeABI(): string; } export interface Contract { options: ContractOptions; methods: { [fnName: string]: (...args: any[]) => TransactionObject<any>; }; deploy(options: { data: string; arguments: any[] }): TransactionObject<Contract>; // tslint:disable-next-line:member-ordering events: { [eventName: string]: ( options?: { filter?: object; fromBlock?: BlockType; topics?: any[]; }, cb?: Callback<EventLog> ) => EventEmitter; // tslint:disable-next-line:max-line-length allEvents: ( options?: { filter?: object; fromBlock?: BlockType; topics?: any[] }, cb?: Callback<EventLog> ) => EventEmitter; }; } export interface Eth { readonly defaultAccount: string; readonly defaultBlock: BlockType; BatchRequest: new () => BatchRequest; Iban: new (address: string) => Iban; Contract: new ( jsonInterface: any[], address?: string, options?: { from?: string; gas?: string | number | BigNumber; gasPrice?: number; data?: string; } ) => Contract; abi: { decodeLog(inputs: object, hexString: string, topics: string[]): object; encodeParameter(type: string, parameter: any): string; encodeParameters(types: string[], paramaters: any[]): string; encodeEventSignature(name: string | object): string; encodeFunctionCall(jsonInterface: object, parameters: any[]): string; encodeFunctionSignature(name: string | object): string; decodeParameter(type: string, hex: string): any; decodeParameters(types: string[], hex: string): any; }; accounts: { 'new'(entropy?: string): Account; privateToAccount(privKey: string): Account; publicToAddress(key: string): string; // tslint:disable-next-line:max-line-length signTransaction( tx: Tx, privateKey: string, returnSignature?: boolean, cb?: (err: Error, result: string | Signature) => void ): Promise<string> | Signature; recoverTransaction(signature: string | Signature): string; sign(data: string, privateKey: string, returnSignature?: boolean): string | Signature; recover(signature: string | Signature): string; encrypt(privateKey: string, password: string): PrivateKey; decrypt(privateKey: PrivateKey, password: string): Account; // tslint:disable-next-line:member-ordering wallet: { 'new'(numberOfAccounts: number, entropy: string): Account[]; add(account: string | Account): any; remove(account: string | number): any; save(password: string, keyname?: string): string; load(password: string, keyname: string): any; clear(): any; }; }; call(callObject: Tx, defaultBloc?: BlockType, callBack?: Callback<string>): Promise<string>; clearSubscriptions(): boolean; subscribe(type: 'logs', options?: Logs, callback?: Callback<Subscribe<Log>>): Promise<Subscribe<Log>>; subscribe(type: 'syncing', callback?: Callback<Subscribe<any>>): Promise<Subscribe<any>>; // tslint:disable-next-line:max-line-length subscribe(type: 'newBlockHeaders', callback?: Callback<Subscribe<BlockHeader>>): Promise<Subscribe<BlockHeader>>; subscribe( type: 'pendingTransactions', callback?: Callback<Subscribe<Transaction>> ): Promise<Subscribe<Transaction>>; // tslint:disable-next-line:max-line-length subscribe( type: 'pendingTransactions' | 'newBlockHeaders' | 'syncing' | 'logs', options?: Logs, callback?: Callback<Subscribe<Transaction | BlockHeader | any>> ): Promise<Subscribe<Transaction | BlockHeader | any>>; unsubscribe(callBack: Callback<boolean>): void | boolean; // tslint:disable-next-line:member-ordering compile: { solidity(source: string, callback?: Callback<CompileResult>): Promise<CompileResult>; lll(source: string, callback?: Callback<CompileResult>): Promise<CompileResult>; serpent(source: string, callback?: Callback<CompileResult>): Promise<CompileResult>; }; // tslint:disable-next-line:member-ordering currentProvider: Provider; estimateGas(tx: Tx, callback?: Callback<number>): Promise<number>; getAccounts(cb?: Callback<Array<string>>): Promise<Array<string>>; getBalance(address: string, defaultBlock?: BlockType, cb?: Callback<number>): Promise<number>; // tslint:disable-next-line:variable-name getBlock(number: BlockType, returnTransactionObjects?: boolean, cb?: Callback<Block>): Promise<Block>; getBlockNumber(callback?: Callback<number>): Promise<number>; // tslint:disable-next-line:variable-name getBlockTransactionCount(number: BlockType | string, cb?: Callback<number>): Promise<number>; // tslint:disable-next-line:variable-name getBlockUncleCount(number: BlockType | string, cb?: Callback<number>): Promise<number>; getCode(address: string, defaultBlock?: BlockType, cb?: Callback<string>): Promise<string>; getCoinbase(cb?: Callback<string>): Promise<string>; getCompilers(cb?: Callback<string[]>): Promise<string[]>; getGasPrice(cb?: Callback<number>): Promise<number>; getHashrate(cb?: Callback<number>): Promise<number>; getPastLogs( options: { fromBlock?: BlockType; toBlock?: BlockType; address: string; topics?: Array<string | Array<string>>; }, cb?: Callback<Array<Log>> ): Promise<Array<Log>>; getProtocolVersion(cb?: Callback<string>): Promise<string>; getStorageAt(address: string, defaultBlock?: BlockType, cb?: Callback<string>): Promise<string>; getTransactionReceipt(hash: string, cb?: Callback<TransactionReceipt>): Promise<TransactionReceipt>; getTransaction(hash: string, cb?: Callback<Transaction>): Promise<Transaction>; getTransactionCount(address: string, defaultBlock?: BlockType, cb?: Callback<number>): Promise<number>; getTransactionFromBlock(block: BlockType, index: number, cb?: Callback<Transaction>): Promise<Transaction>; // tslint:disable-next-line:max-line-length getUncle( blockHashOrBlockNumber: BlockType | string, uncleIndex: number, returnTransactionObjects?: boolean, cb?: Callback<Block> ): Promise<Block>; getWork(cb?: Callback<Array<string>>): Promise<Array<string>>; // tslint:disable-next-line:member-ordering givenProvider: Provider; isMining(cb?: Callback<boolean>): Promise<boolean>; isSyncing(cb?: Callback<boolean>): Promise<boolean>; // tslint:disable-next-line:member-ordering net: Net; // tslint:disable-next-line:member-ordering personal: Personal; sendSignedTransaction(data: string, cb?: Callback<string>): PromiEvent<TransactionReceipt>; sendTransaction(tx: Tx, cb?: Callback<string>): PromiEvent<TransactionReceipt>; submitWork(nonce: string, powHash: string, digest: string, cb?: Callback<boolean>): Promise<boolean>; sign(address: string, dataToSign: string, cb?: Callback<string>): Promise<string>; } export interface SyncingState { startingBlock: number; currentBlock: number; highestBlock: number; } export type SyncingResult = false | SyncingState; export interface Version0 { api: string; network: string; node: string; ethereum: string; whisper: string; getNetwork(callback: (err: Error, networkId: string) => void): void; getNode(callback: (err: Error, nodeVersion: string) => void): void; getEthereum(callback: (err: Error, ethereum: string) => void): void; getWhisper(callback: (err: Error, whisper: string) => void): void; } export interface Net {} export interface Personal { newAccount(password: string, cb?: Callback<boolean>): Promise<boolean>; getAccounts(cb?: Callback<Array<string>>): Promise<Array<string>>; importRawKey(); lockAccount(); unlockAccount(); sign(); } export interface Shh {} export interface Bzz {} export const duration = { seconds: function(val: number) { return val; }, minutes: function(val: number) { return val * this.seconds(60); }, hours: function(val: number) { return val * this.minutes(60); }, days: function(val: number) { return val * this.hours(24); }, weeks: function(val: number) { return val * this.days(7); }, years: function(val: number) { return val * this.days(365); } }; export interface CancellationToken { cancelled: boolean; } }
the_stack
import { resolve } from 'path' import matchRange from 'version-range' import { errtion, Errtion } from './util.js' import { versions as processVersions } from 'process' import { readFileSync } from 'fs' export type Range = string | boolean export type Engines = false | { [engine: string]: Range } export type Versions = { [engine: string]: string } /** * Edition entries must conform to the following specification. * @example * ``` json * { * "description": "esnext source code with require for modules", * "directory": "source", * "entry": "index.js", * "tags": [ * "javascript", * "esnext", * "require" * ], * "engines": { * "node": ">=6", * "browsers": "defaults" * } * } * ``` */ export interface Edition { /** * Use this property to describe the edition in human readable terms. Such as what it does and who it is for. It is used to reference the edition in user facing reporting, such as error messages. * @example * ``` json * "esnext source code with require for modules" * ``` */ description: string /** * The location to where this directory is located. It should be a relative path from the `package.json` file. * @example * ``` json * "source" * ``` */ directory: string /** * The default entry location for this edition, relative to the edition's directory. * @example * ``` json * "index.js" * ``` */ entry: string /** * Any keywords you wish to associate to the edition. Useful for various ecosystem tooling, such as automatic ESNext lint configuration if the `esnext` tag is present in the source edition tags. * @example * ``` json * ["javascript", "esnext", "require"] * ``` */ tags?: string[] /** * This field is used to specific which environments this edition supports. * If `false` this edition does not any environment. * If `deno` is a string, it should be a semver range of Deno versions that the edition targets. * If `node` is a string, it should be a semver range of Node.js versions that the edition targets. * If `browsers` is a string, it should be a [browserlist](https://github.com/browserslist/browserslist) value of the specific browser values the edition targets. If multiple engines are truthy, it indicates that this edition is compatible with those multiple environments. * @example * ``` json * { * "deno": ">=1", * "node": ">=6", * "browsers": "defaults" * } * ``` */ engines: Engines /** If this edition fails to load, then this property provides any accompanying information. */ debugging?: Errtion } /** Editions should be ordered from most preferable first to least desirable last. The source edition should always be first, proceeded by compiled editions. */ export type Editions = Array<Edition> export interface PathOptions { /** If provided, this edition entry is used instead of the default entry. */ entry: string /** If provided, edition loading will be resolved against this. */ cwd: string } export interface LoaderOptions extends Partial<PathOptions> { /** * The method that will load the entry of the edition. * For CJS files this should be set to the `require` method. * For MJS files this should be set to `(path: string) => import(path)`. */ loader: <T>(this: Edition, path: string) => T } export interface RangeOptions { /** If `true`, then ranges such as `x || y` are changed to `>=x`. */ broadenRange?: boolean } export interface VersionOptions extends RangeOptions { /** The versions of our current environment. */ versions: Versions } export interface SolicitOptions extends LoaderOptions, VersionOptions {} /** * Load the {@link Edition} with the loader. * @returns The result of the loaded edition. * @throws If failed to load, an error is thrown with the reason. */ export function loadEdition<T>(edition: Edition, opts: LoaderOptions): T { const entry = resolve( opts.cwd || '', edition.directory, opts.entry || edition.entry || '' ) if (opts.loader == null) { throw errtion({ message: `Could not load the edition [${edition.description}] as no loader was specified. This is probably due to a testing misconfiguration.`, code: 'editions-autoloader-loader-missing', level: 'fatal', }) } try { return opts.loader.call(edition, entry) as T } catch (loadError) { // Note the error with more details throw errtion( { message: `Failed to load the entry [${entry}] of edition [${edition.description}].`, code: 'editions-autoloader-loader-failed', level: 'fatal', }, loadError ) } } /** * Verify the {@link Edition} has all the required properties. * @returns if valid * @throws if invalid */ export function isValidEdition(edition: Edition): true { if ( !edition.description || !edition.directory || !edition.entry || edition.engines == null ) { throw errtion({ message: `An edition must have its [description, directory, entry, engines] fields defined, yet all this edition defined were [${Object.keys( edition ).join(', ')}]`, code: 'editions-autoloader-invalid-edition', level: 'fatal', }) } // valid return true } /** * Is this {@link Edition} suitable for these versions? * @returns if compatible * @throws if incompatible */ export function isCompatibleVersion( range: Range, version: string, opts: RangeOptions ): true { // prepare const { broadenRange } = opts if (!version) throw errtion({ message: `No version was specified to compare the range [${range}] against`, code: 'editions-autoloader-engine-version-missing', level: 'fatal', }) if (range == null || range === '') throw errtion({ message: `The edition range was not specified, so unable to compare against the version [${version}]`, code: 'editions-autoloader-engine-range-missing', }) if (range === false) throw errtion({ message: `The edition range does not support this engine`, code: 'editions-autoloader-engine-unsupported', }) if (range === true) return true // original range try { if (matchRange(version, range)) return true } catch (error) { throw errtion( { message: `The range [${range}] was invalid, something is wrong with the Editions definition.`, code: 'editions-autoloader-invalid-range', level: 'fatal', }, error ) } // broadened range // https://github.com/bevry/editions/blob/master/HISTORY.md#v210-2018-november-15 // If none of the editions for a package match the current node version, editions will try to find a compatible package by converting strict version ranges likes 4 || 6 || 8 || 10 to looser ones like >=4, and if that fails, then it will attempt to load the last edition for the environment. // This brings editions handling of engines closer in line with how node handles it, which is as a warning/recommendation, rather than a requirement/enforcement. // This has the benefit that edition authors can specify ranges as the specific versions that they have tested the edition against that pass, rather than having to omit that information for runtime compatibility. // As such editions will now automatically select the edition with guaranteed support for the environment, and if there are none with guaranteed support, then editions will select the one is most likely supported, and if there are none that are likely supported, then it will try the last edition, which should be the most compatible edition. // This is timely, as node v11 is now the version most developers use, yet if edition authors specified only LTS releases, then the editions autoloader would reject loading on v11, despite compatibility being likely with the most upper edition. // NOTE: That there is only one broadening chance per package, once a broadened edition has been returned, a load will be attempted, and if it fails, then the package failed. This is intentional. if (broadenRange === true) { // check if range can be broadened, validate it and extract const broadenedRangeRegex = /^\s*([0-9.]+)\s*(\|\|\s*[0-9.]+\s*)*$/ const broadenedRangeMatch = range.match(broadenedRangeRegex) const lowestVersion: string = (broadenedRangeMatch && broadenedRangeMatch[1]) || '' // ^ can't do number conversion, as 1.1.1 is not a number // this also converts 0 to '' which is what we want for the next check // confirm the validation if (lowestVersion === '') throw errtion({ message: `The range [${range}] is not able to be broadened, only ranges in format of [lowest] or [lowest || ... || ... ] can be broadened. Update the Editions definition and try again.`, code: 'editions-autoloader-unsupported-broadened-range', level: 'fatal', }) // create the broadened range, and attempt that const broadenedRange = `>= ${lowestVersion}` try { if (matchRange(version, broadenedRange)) return true } catch (error) { throw errtion( { message: `The broadened range [${broadenedRange}] was invalid, something is wrong within Editions.`, code: 'editions-autoloader-invalid-broadened-range', level: 'fatal', }, error ) } // broadened range was incompatible throw errtion({ message: `The edition range [${range}] does not support this engine version [${version}], even when broadened to [${broadenedRange}]`, code: 'editions-autoloader-engine-incompatible-broadened-range', }) } // give up throw errtion({ message: `The edition range [${range}] does not support this engine version [${version}]`, code: 'editions-autoloader-engine-incompatible-original', }) } /** * Checks that the provided engines are compatible against the provided versions. * @returns if compatible * @throws if incompatible */ export function isCompatibleEngines( engines: Engines, opts: VersionOptions ): true { // PRepare const { versions } = opts // Check engines exist if (!engines) { throw errtion({ message: `The edition had no engines to compare against the environment`, code: 'editions-autoloader-invalid-engines', }) } // Check versions exist if (!versions) { throw errtion({ message: `No versions were supplied to compare the engines against`, code: 'editions-autoloader-invalid-versions', level: 'fatal', }) } // Check each version let compatible = false for (const key in engines) { if (engines.hasOwnProperty(key)) { // deno's std/node/process provides both `deno` and `node` keys // so we don't won't to compare node when it is actually deno if (key === 'node' && versions.deno) continue // prepare const engine = engines[key] const version = versions[key] // skip for engines this edition does not care about if (version == null) continue // check compatibility against all the provided engines it does care about try { isCompatibleVersion(engine, version, opts) compatible = true // if any incompatibility, it is thrown, so no need to set to false } catch (rangeError) { throw errtion( { message: `The engine [${key}] range of [${engine}] was not compatible against version [${version}].`, code: 'editions-autoloader-engine-error', }, rangeError ) } } } // if there were no matching engines, then throw if (!compatible) { throw errtion({ message: `There were no supported engines in which this environment provides.`, code: 'editions-autoloader-engine-mismatch', }) } // valid return true } /** * Checks that the {@link Edition} is compatible against the provided versions. * @returns if compatible * @throws if incompatible */ export function isCompatibleEdition( edition: Edition, opts: VersionOptions ): true { try { return isCompatibleEngines(edition.engines, opts) } catch (compatibleError) { throw errtion( { message: `The edition [${edition.description}] is not compatible with this environment.`, code: 'editions-autoloader-edition-incompatible', }, compatibleError ) } } /** * Determine which edition should be loaded. * If {@link VersionOptions.broadenRange} is unspecified (the default behavior), then we attempt to determine a suitable edition without broadening the range, and if that fails, then we try again with the range broadened. * @returns any suitable editions * @throws if no suitable editions */ export function determineEdition( editions: Editions, opts: VersionOptions ): Edition { // Prepare const { broadenRange } = opts // Check if (!editions || editions.length === 0) { throw errtion({ message: 'No editions were specified.', code: 'editions-autoloader-editions-missing', }) } // Cycle through the editions determining the above let failure: Errtion | null = null for (let i = 0; i < editions.length; ++i) { const edition = editions[i] try { isValidEdition(edition) isCompatibleEdition(edition, opts) // Success! Return the edition return edition } catch (error) { if (error.level === 'fatal') { throw errtion( { message: `Unable to determine a suitable edition due to failure.`, code: 'editions-autoloader-fatal', level: 'fatal', }, error ) } else if (failure) { failure = errtion(error, failure) } else { failure = error } } } // Report the failure from above if (failure) { // try broadened if (broadenRange == null) try { // return if broadening successfully returned an edition const broadenedEdition = determineEdition(editions, { ...opts, broadenRange: true, }) return { ...broadenedEdition, // bubble the circumstances up in case the loading of the broadened edition fails and needs to be reported debugging: errtion({ message: `The edition ${broadenedEdition.description} was selected to be force loaded as its range was broadened.`, code: 'editions-autoloader-attempt-broadened', }), } } catch (error) { throw errtion( { message: `Unable to determine a suitable edition, even after broadening.`, code: 'editions-autoloader-none-broadened', }, error ) } // fail throw errtion( { message: `Unable to determine a suitable edition, as none were suitable.`, code: 'editions-autoloader-none-suitable', }, failure ) } // this should never reach here throw errtion({ message: `Unable to determine a suitable edition, as an unexpected pathway occurred.`, code: 'editions-autoloader-never', }) } /** * Determine which edition should be loaded, and attempt to load it. * @returns the loaded result of the suitable edition * @throws if no suitable editions, or the edition failed to load */ export function solicitEdition<T>(editions: Editions, opts: SolicitOptions): T { const edition = determineEdition(editions, opts) try { return loadEdition<T>(edition, opts) } catch (error) { throw errtion(error, edition.debugging) } } /** * Cycle through the editions for a package, determine the compatible edition, and load it. * @returns the loaded result of the suitable edition * @throws if no suitable editions, or if the edition failed to load */ export function requirePackage<T>( cwd: PathOptions['cwd'], loader: LoaderOptions['loader'], entry: PathOptions['entry'] ): T { const packagePath = resolve(cwd || '', 'package.json') try { // load editions const { editions } = JSON.parse(readFileSync(packagePath, 'utf8')) // load edition return solicitEdition<T>(editions, { versions: processVersions as any as Versions, cwd, loader, entry, }) } catch (error) { throw errtion( { message: `Unable to determine a suitable edition for the package [${packagePath}] and entry [${entry}]`, code: 'editions-autoloader-package', }, error ) } }
the_stack
import { Equaler, Comparer } from "@esfx/equatable"; /** * Throws the provided value. */ export function fail(value: unknown): never { throw value; } /** * Does nothing. */ export function noop(...args: any[]): unknown; export function noop() { } /** * Returns the provided value. */ export function identity<T>(value: T) { return value; } /** * A function that always returns `true`. */ export function alwaysTrue(): true { return true; } export { alwaysTrue as T }; /** * A function that always returns `false`. */ export function alwaysFalse(): false { return false; } export { alwaysFalse as F }; /** * Returns a function that always throws the provided error. */ export function alwaysFail(error: unknown) { return () => fail(error); } /** * Returns a function that returns the provided value. */ export function always<T>(value: T) { return () => value; } export declare namespace always { export { alwaysTrue as true, alwaysFalse as false, alwaysFail as fail }; } /** @internal */ export namespace always { always.true = alwaysTrue; always.false = alwaysFalse; always.fail = alwaysFail; } /** * Returns a function that produces a monotonically increasing number value each time it is called. */ export function incrementer(start = 0) { return () => start++; } export namespace incrementer { /** * Returns a function that produces a monotonically increasing number value each time it is called. */ export function step(count: number, start = 0) { return count > 0 ? (() => start += count) : fail(new Error("Count must be a positive number")); } } /** * Returns a function that produces a monotonically increasing number value each time it is called. */ export function decrementer(start = 0) { return () => start--; } export namespace decrementer { /** * Returns a function that produces a monotonically decreasing number value each time it is called. */ export function step(count: number, start = 0) { return count > 0 ? (() => start -= count) : fail(new Error("Count must be a positive number")); } } /** * Makes a "tuple" from the provided arguments. */ export function tuple<A extends readonly [unknown?, ...unknown[]]>(...args: A): A { return args; } /** * Truncates a function's arguments to a fixed length. */ export function nAry<T, R>(f: (this: T) => R, length: 0): (this: T) => R; export function nAry<T, A, R>(f: (this: T, a: A) => R, length: 1): (this: T, a: A) => R; export function nAry<T, A, B, R>(f: (this: T, a: A, b: B) => R, length: 2): (this: T, a: A, b: B) => R; export function nAry<T, A, B, C, R>(f: (this: T, a: A, b: B, c: C) => R, length: 3): (this: T, a: A, b: B, c: C) => R; export function nAry<T, A, B, C, D, R>(f: (this: T, a: A, b: B, c: C, d: D) => R, length: 4): (this: T, a: A, b: B, c: C, d: D) => R; export function nAry<T, A, R>(f: (this: T, ...args: A[]) => R, length: number): (this: T, ...args: A[]) => R { return function(...args) { return f.call(this, ...args.slice(0, length)); }; } /** * Right-to-left composition of functions (i.e. `compose(g, f)` is `x => g(f(x))`). */ export function compose<A extends unknown[], B, C>(fb: (b: B) => C, fa: (...a: A) => B): (...a: A) => C; export function compose<A extends unknown[], B, C, D>(fc: (c: C) => D, fb: (b: B) => C, fa: (...a: A) => B): (...a: A) => D; export function compose<A extends unknown[], B, C, D, E>(fd: (d: D) => E, fc: (c: C) => D, fb: (b: B) => C, fa: (...a: A) => B): (...a: A) => E; export function compose<A extends unknown[], B, C, D, E, F>(fe: (e: E) => F, fd: (d: D) => E, fc: (c: C) => D, fb: (b: B) => C, fa: (...a: A) => B): (...a: A) => F; export function compose<T>(...rest: ((t: T) => T)[]): (t: T) => T; export function compose<T>(...rest: ((t: T) => T)[]): (t: T) => T { const last = rest.pop()!; return (...args) => rest.reduceRight((a, f) => f(a), last(...args)); } /** * Left-to-right composition of functions (i.e. `pipe(g, f)` is `x => f(g(x))`). */ export function pipe<A extends unknown[], B, C>(fa: (...a: A) => B, fb: (b: B) => C): (...a: A) => C; export function pipe<A extends unknown[], B, C, D>(fa: (...a: A) => B, fb: (b: B) => C, fc: (c: C) => D): (...a: A) => D; export function pipe<A extends unknown[], B, C, D, E>(fa: (...a: A) => B, fb: (b: B) => C, fc: (c: C) => D, fd: (d: D) => E): (...a: A) => E; export function pipe<A extends unknown[], B, C, D, E, F>(fa: (...a: A) => B, fb: (b: B) => C, fc: (c: C) => D, fd: (d: D) => E, fe: (e: E) => F): (...a: A) => F; export function pipe<A extends unknown[], B>(first: (...a: A) => B, ...rest: ((b: B) => B)[]): (...a: A) => B; export function pipe<A extends unknown[], B>(first: (...a: A) => B, ...rest: ((b: B) => B)[]): (...a: A) => B { return (...args) => rest.reduce((a, f) => f(a), first(...args)); } /** * Returns a function that reads the value of a property from an object provided as the function's first argument. * @param key The key for the property. */ export function property<K extends PropertyKey>(key: K): <T extends Record<K, T[K]>>(object: T) => T[K] { return object => object[key]; } /** * Returns a function that writes a value to a property on an object provided as the function's first argument. * @param key The key for the property. */ export function propertyWriter<K extends PropertyKey>(key: K): <T extends Record<K, T[K]>>(object: T, value: T[K]) => void { return (object, value) => { object[key] = value; }; } /** * Returns a function that invokes a method on the object provided as the function's first argument. * * ```ts * const fn = invoker("sayHello", "Bob"); * fn({ sayHello(name) { console.log(`Hello, ${name}!`); } }); // prints: "Hello, Bob!" * ``` */ export function invoker<K extends PropertyKey>(key: K): <T extends Record<K, (...args: A) => ReturnType<T[K]>>, A extends unknown[]>(object: T, ...args: A) => ReturnType<T[K]>; export function invoker<K extends PropertyKey, A0>(key: K, a0: A0): <T extends Record<K, (a0: A0, ...args: A) => ReturnType<T[K]>>, A extends unknown[]>(object: T, ...args: A) => ReturnType<T[K]>; export function invoker<K extends PropertyKey, A0, A1>(key: K, a0: A0, a1: A1): <T extends Record<K, (a0: A0, a1: A1, ...args: A) => ReturnType<T[K]>>, A extends unknown[]>(object: T, ...args: A) => ReturnType<T[K]>; export function invoker<K extends PropertyKey, A0, A1, A2>(key: K, a0: A0, a1: A1, a2: A2): <T extends Record<K, (a0: A0, a1: A1, a2: A2, ...args: A) => ReturnType<T[K]>>, A extends unknown[]>(object: T, ...args: A) => ReturnType<T[K]>; export function invoker<K extends PropertyKey, A0, A1, A2, A3>(key: K, a0: A0, a1: A1, a2: A2, a3: A3): <T extends Record<K, (a0: A0, a1: A1, a2: A2, a3: A3, ...args: A) => ReturnType<T[K]>>, A extends unknown[]>(object: T, ...args: A) => ReturnType<T[K]>; export function invoker<K extends PropertyKey, A extends unknown[]>(key: K, ...args: A): <T extends Record<K, (...args: A) => ReturnType<T[K]>>>(object: T) => ReturnType<T[K]>; export function invoker<K extends PropertyKey, AX>(key: K, ...args: AX[]): <T extends Record<K, (...args: AX[]) => ReturnType<T[K]>>>(object: T, ...args: AX[]) => ReturnType<T[K]>; export function invoker<K extends PropertyKey, AX>(key: K, ...args: AX[]): <T extends Record<K, (...args: AX[]) => ReturnType<T[K]>>>(object: T, ...args: AX[]) => ReturnType<T[K]> { return (object, ...rest) => object[key](...args, ...rest); } /** * Returns a function that calls the function provided as its first argument. * * ```ts * const fn = caller(1, 2); * fn((a, b) => a + b); // 3 * ``` */ export function caller(): <R, A extends unknown[]>(func: (...args: A) => R, ...args: A) => R; export function caller<A0>(a0: A0): <R, A extends unknown[]>(func: (a0: A0, ...args: A) => R, ...args: A) => R; export function caller<A0, A1>(a0: A0, a1: A1): <R, A extends unknown[]>(func: (a0: A0, a1: A1, ...args: A) => R, ...args: A) => R; export function caller<A0, A1, A2>(a0: A0, a1: A1, a2: A2): <R, A extends unknown[]>(func: (a0: A0, a1: A1, a2: A2, ...args: A) => R, ...args: A) => R; export function caller<A0, A1, A2, A3>(a0: A0, a1: A1, a2: A2, a3: A3): <R, A extends unknown[]>(func: (a0: A0, a1: A1, a2: A2, a3: A3, ...args: A) => R, ...args: A) => R; export function caller<A extends unknown[]>(...args: A): <R>(func: (...args: A) => R) => R; export function caller<AX>(...args: AX[]): <R>(func: (...args: AX[]) => R, ...args: AX[]) => R; export function caller<AX>(...args: AX[]): <R>(func: (...args: AX[]) => R, ...args: AX[]) => R { return (func, ...rest) => func(...args, ...rest); } /** * Returns a function that constructs an instance from a constructor provided as its first argument. * * ```ts * const fn = allocator("Bob"); * class Person { * constructor(name) { this.name = name; } * } * class Dog { * constructor(owner) { this.owner = owner; } * } * fn(Person).name; // "Bob" * fn(Dog).owner; // "Bob" * ``` */ export function allocator(): <R, A extends unknown[]>(ctor: new (...args: A) => R, ...args: A) => R; export function allocator<A0>(a0: A0): <R, A extends unknown[]>(ctor: new (a0: A0, ...args: A) => R, ...args: A) => R; export function allocator<A0, A1>(a0: A0, a1: A1): <R, A extends unknown[]>(ctor: new (a0: A0, a1: A1, ...args: A) => R, ...args: A) => R; export function allocator<A0, A1, A2>(a0: A0, a1: A1, a2: A2): <R, A extends unknown[]>(ctor: new (a0: A0, a1: A1, a2: A2, ...args: A) => R, ...args: A) => R; export function allocator<A0, A1, A2, A3>(a0: A0, a1: A1, a2: A2, a3: A3): <R, A extends unknown[]>(ctor: new (a0: A0, a1: A1, a2: A2, a3: A3, ...args: A) => R, ...args: A) => R; export function allocator<A extends unknown[]>(...args: A): <R>(ctor: new (...args: A) => R) => R; export function allocator<AX>(...args: AX[]): <R>(ctor: new (...args: AX[]) => R, ...args: AX[]) => R; export function allocator<AX>(...args: AX[]): <R>(ctor: new (...args: AX[]) => R, ...args: AX[]) => R { return (ctor, ...rest) => new ctor(...args, ...rest); } /** * Returns a function that constructs an instance of the provided constructor. * * ```ts * class Point { * constructor(x, y) { * this.x = x; * this.y = y; * } * } * const fn = factory(Point); * fn(1, 2); // Point { x: 1, y: 2 } * fn(3, 4); // Point { x: 3, y: 4 } * ``` */ export function factory<A extends unknown[], R>(ctor: new (...args: A) => R): (...args: A) => R; export function factory<A0, A extends unknown[], R>(ctor: new (a0: A0, ...args: A) => R, a0: A0): (...args: A) => R; export function factory<A0, A1, A extends unknown[], R>(ctor: new (a0: A0, a1: A1, ...args: A) => R, a0: A0, a1: A1): (...args: A) => R; export function factory<A0, A1, A2, A extends unknown[], R>(ctor: new (a0: A0, a1: A1, a2: A2, ...args: A) => R, a0: A0, a1: A1, a2: A2): (...args: A) => R; export function factory<A0, A1, A2, A3, A extends unknown[], R>(ctor: new (a0: A0, a1: A1, a2: A2, a3: A3, ...args: A) => R, a0: A0, a1: A1, a2: A2, a3: A3): (...args: A) => R; export function factory<A extends unknown[], R>(ctor: new (...args: A) => R, ...args: A): () => R; export function factory<AX, R>(ctor: new (...args: AX[]) => R, ...args: AX[]): (...args: AX[]) => R; export function factory<AX, R>(ctor: new (...args: AX[]) => R, ...args: AX[]): (...args: AX[]) => R { return (...rest) => new ctor(...args, ...rest); } /** * Returns a function that calls the provided function, but swaps the first and second arguments. * * ```ts * function compareNumbers(a, b) { return a - b }; * [3, 1, 2].sort(compareNumbers); // [1, 2, 3] * [3, 1, 2].sort(flip(compareNumbers)); // [3, 2, 1] * ``` */ export function flip<A, B, C extends unknown[], R>(f: (a: A, b: B, ...c: C) => R): (b: B, a: A, ...c: C) => R { return (b, a, ...c) => f(a, b, ...c); } function recursiveLazy(): never { throw new Error("Lazy factory recursively references itself during its own evaluation."); } /** * Returns a function that will evaluate once when called will subsequently always return the same result. * * ```ts * let count = 0; * const fn = lazy(() => count++); * fn(); // 0 * fn(); // 0 * count; // 1 * ``` */ export function lazy<T, A extends unknown[]>(factory: (...args: A) => T, ...args: A) { let f = (): T => { f = recursiveLazy; try { f = always(factory(...args)); } catch (e) { f = alwaysFail(e); } return f(); }; return () => f(); } const uncurryThis_ = Function.prototype.bind.bind(Function.prototype.call); /** * Returns a function whose first argument is passed as the `this` receiver to the provided function when called. * * ```ts * const hasOwn = uncurryThis(Object.prototype.hasOwnProperty); * const obj = { x: 1 }; * hasOwn(obj, "x"); // true * hasOwn(obj, "y"); // false * ``` */ export function uncurryThis<T, A extends unknown[], R>(f: (this: T, ...args: A) => R): (this_: T, ...args: A) => R { return uncurryThis_(f); } /** * Equates two values using the default `Equaler`. * @see {@link @esfx/equatable#Equaler.defaultEqualer} */ export function equate<T>(a: T, b: T) { return Equaler.defaultEqualer.equals(a, b); } export namespace equate { /** * Creates a copy of `equate` for a specific `Equaler`. */ export function withEqualer<T>(equaler: Equaler<T>): (a: T, b: T) => boolean { return (a, b) => equaler.equals(a, b); } } /** * Generates a hashcode from a value. */ export function hash(value: unknown): number { return Equaler.defaultEqualer.hash(value); } export namespace hash { /** * Creates a copy of `hash` for a specific `Equaler`. */ export function withEqualer<T>(equaler: Equaler<T>): (value: T) => number { return value => equaler.hash(value); } } /** * Compares two values using the default `Comparer`. * @see {@link @esfx/equatable#Comparer.defaultComparer} */ export function compare<T>(a: T, b: T) { return Comparer.defaultComparer.compare(a, b); } export namespace compare { /** * Creates a copy of `compare` for a specific `Comparer`. */ export function withComparer<T>(comparer: Comparer<T>): (a: T, b: T) => number { return (a, b) => comparer.compare(a, b); } } /** * Clamps a value to a set range using the default `Comparer`. * * ```ts * const fn = clamp(0, 10); * fn(-1); // 0 * fn(15); // 10 * fn(7); // 7 * ``` */ export function clamp<T>(min: T, max: T): (value: T) => T { return value => Comparer.defaultComparer.compare(value, min) < 0 ? min : Comparer.defaultComparer.compare(value, max) > 0 ? max : value; } export namespace clamp { /** * Creates a copy of `clamp` for a specific `Comparer`. */ export function withComparer<T>(comparer: Comparer<T>): (min: T, max: T) => (value: T) => T { return (min, max) => (value) => comparer.compare(value, min) < 0 ? min : comparer.compare(value, max) > 0 ? max : value; } } /** * Returns a function that returns the complement of calling `f`. * * ```ts * alwaysTrue(); // true * complement(alwaysTrue)(); // false * * alwaysFalse(); // false * complement(alwaysFalse)(); // true * ``` */ export function complement<A extends unknown[]>(f: (...args: A) => boolean): (...args: A) => boolean { return (...args) => !f(...args); } /** * Returns a function that returns the result of calling its first argument if that result is "falsy", otherwise returning the result of calling its second argument. * NOTE: This performs the same shortcutting as a logical AND (i.e. `a() && b()`) */ export function both<T, U extends T, V extends T>(a: (t: T) => t is U, b: (t: T) => t is V): (t: T) => t is U & V; export function both<A extends unknown[], R1, R2>(a: (...args: A) => R1, b: (...args: A) => R2): (...args: A) => R1 extends (null | undefined | false | 0 | 0n | '') ? R1 : R2 extends (null | undefined | false | 0 | 0n | '') ? R2 : R1 | R2; export function both<A extends unknown[], R1, R2>(a: (...args: A) => R1, b: (...args: A) => R2): (...args: A) => R1 | R2 { return (...args) => a(...args) && b(...args); } /** * Returns a function that returns the result of calling its first argument if that result is "truthy", otherwise returning the result of calling its second argument. * NOTE: This performs the same shortcutting as a logical OR (i.e. `a() || b()`). */ export function either<T, U extends T, V extends T>(a: (t: T) => t is U, b: (t: T) => t is V): (t: T) => t is U | V; export function either<A extends unknown[], R1, R2>(a: (...args: A) => R1, b: (...args: A) => R2): (...args: A) => R1 extends (null | undefined | false | 0 | 0n | '') ? R2 : R1; export function either<A extends unknown[], R1, R2>(a: (...args: A) => R1, b: (...args: A) => R2): (...args: A) => R1 | R2 { return (...args) => a(...args) || b(...args); } /** * Returns a function that returns the result of calling the first callback, if that result is neither `null` nor `undefined`; otherwise, returns the result of calling the second callback with the same arguments. * NOTE: This performs the same shortcutting as nullish-coalesce (i.e. `a() ?? b()`). */ export function fallback<A extends unknown[], T, U>(a: (...args: A) => T, b: (...args: A) => U): (...args: A) => NonNullable<T> | U { return (...args) => { const result = a(...args); return result !== null && result !== undefined ? result! : b(...args); }; } /** * Returns `true` if a value is neither `null` nor `undefined`. */ export function isDefined<T>(value: T): value is NonNullable<T> { return value !== null && value !== undefined; }
the_stack
import { ChildProcessWithoutNullStreams, execFile, spawn } from "child_process"; import { Logging, StreamRequestCallback } from "homebridge"; import { Readable, Writable } from "stream"; import { EventEmitter } from "events"; import { ProtectCamera } from "./protect-camera"; import { ProtectNvr } from "./protect-nvr"; import util from "util"; // Port and IP version information. export interface PortInterface { addressVersion: string, port: number } // Base class for all FFmpeg process management. export class FfmpegProcess extends EventEmitter { protected callback: StreamRequestCallback | null; protected commandLineArgs: string[]; protected readonly debug: (message: string, ...parameters: unknown[]) => void; private stderrLog: string[]; public isEnded: boolean; private isLogging: boolean; private isPrepared: boolean; public isStarted: boolean; protected isVerbose: boolean; private ffmpegTimeout?: NodeJS.Timeout; protected readonly log: Logging; protected readonly name: () => string; protected readonly nvr: ProtectNvr; protected process: ChildProcessWithoutNullStreams | null; protected protectCamera: ProtectCamera; // Create a new FFmpeg process instance. constructor(protectCamera: ProtectCamera, commandLineArgs?: string[], callback?: StreamRequestCallback) { // Initialize our parent. super(); this.callback = null; this.commandLineArgs = []; this.debug = protectCamera.platform.debug.bind(protectCamera.platform); this.stderrLog = []; this.isLogging = false; this.isPrepared = false; this.isEnded = false; this.isStarted = false; this.log = protectCamera.platform.log; this.name = protectCamera.name.bind(protectCamera); this.nvr = protectCamera.nvr; this.process = null; this.protectCamera = protectCamera; // Toggle FFmpeg logging, if configured. this.isVerbose = protectCamera.platform.verboseFfmpeg || protectCamera.stream.verboseFfmpeg; // If we've specified a command line or a callback, let's save them. if(commandLineArgs) { this.commandLineArgs = commandLineArgs; } if(callback) { this.callback = callback; } } // Prepare and start our FFmpeg process. protected prepareProcess(commandLineArgs?: string[], callback?: StreamRequestCallback): void { // If we've specified a new command line or callback, let's save them. if(commandLineArgs) { this.commandLineArgs = commandLineArgs; } // No command line arguments - we're done. if(!this.commandLineArgs) { this.log.error("%s: No FFmpeg command line specified.", this.name()); return; } // Save the callback, if we have one. if(callback) { this.callback = callback; } // See if we should display ffmpeg command output. this.isLogging = false; // Track if we've started or ended FFmpeg. this.isStarted = false; this.isEnded = false; // If we've got a loglevel specified, ensure we display it. if(this.commandLineArgs.indexOf("-loglevel") !== -1) { this.isLogging = true; } // Inform the user, if we've been asked to do so. if(this.isLogging || this.isVerbose || this.protectCamera.platform.config.debugAll) { this.log.info("%s: ffmpeg command: %s %s", this.name(), this.protectCamera.stream.videoProcessor, this.commandLineArgs.join(" ")); } else { this.debug("%s: ffmpeg command: %s %s", this.name(), this.protectCamera.stream.videoProcessor, this.commandLineArgs.join(" ")); } this.isPrepared = true; } // Start our FFmpeg process. protected start(commandLineArgs?: string[], callback?: StreamRequestCallback, errorHandler?: (errorMessage: string) => Promise<void>): void { // If we haven't prepared our FFmpeg process, do so now. if(!this.isPrepared) { this.prepareProcess(commandLineArgs, callback); if(!this.isPrepared) { this.log.error("%s: Error preparing to run FFmpeg.", this.name()); return; } } // Execute the command line based on what we've prepared. this.process = spawn(this.protectCamera.stream.videoProcessor, this.commandLineArgs); // Configure any post-spawn listeners and other plumbing. this.configureProcess(errorHandler); } // Configure our FFmpeg process, once started. protected configureProcess(errorHandler?: (errorMessage: string) => Promise<void>): void { let dataListener: (data: Buffer) => void; let errorListener: (error: Error) => void; // Handle errors emitted during process creation, such as an invalid command line. this.process?.once("error", (error: Error) => { this.log.error("%s: FFmpeg failed to start: %s", this.name(), error.message); // Execute our error handler, if one is provided. if(errorHandler) { void errorHandler(error.name + ": " + error.message); } }); // Handle errors on stdin. this.process?.stdin?.on("error", errorListener = (error: Error): void => { if(!error.message.includes("EPIPE")) { this.log.error("%s: FFmpeg error: %s.", this.name(), error.message); } }); // Handle logging output that gets sent to stderr. this.process?.stderr?.on("data", dataListener = (data: Buffer): void => { // Inform us when we start receiving data back from FFmpeg. We do this here because it's the only // truly reliable place we can check on FFmpeg. stdin and stdout may not be used at all, depending // on the way FFmpeg is called, but stderr will always be there. if(!this.isStarted) { this.isStarted = true; this.isEnded = false; this.debug("%s: Received the first frame.", this.name()); this.emit("ffmpegStarted"); // Always remember to execute the callback once we're setup to let homebridge know we're streaming. if(this.callback) { this.callback(); this.callback = null; } } // Debugging and additional logging collection. for(const line of data.toString().split(/\n/)) { // Don't output not-printable characters to ensure the log output is readable. const cleanLine = line.replace(/[\p{Cc}\p{Cn}\p{Cs}]+/gu, ""); // Don't print the FFmpeg progress bar to give clearer insights into what's going on. if(cleanLine.length && ((cleanLine.indexOf("frame=") === -1) || (cleanLine.indexOf("size=") === -1))) { this.stderrLog.push(cleanLine + "\n"); // Show it to the user if it's been requested. if(this.isLogging || this.isVerbose || this.protectCamera.platform.config.debugAll) { this.log.info("%s: %s", this.name(), cleanLine); } } } }); // Handle our process termination. this.process?.once("exit", (exitCode: number, signal: NodeJS.Signals) => { // Clear out our canary. if(this.ffmpegTimeout) { clearTimeout(this.ffmpegTimeout); } this.isStarted = false; this.isEnded = true; // Some utilities to streamline things. const logPrefix = this.name() + ": FFmpeg process ended "; // FFmpeg ended normally and our canary didn't need to enforce FFmpeg's extinction. if(this.ffmpegTimeout && exitCode === 0) { this.debug(logPrefix + "(Normal)."); } else if(((exitCode === null) || (exitCode === 255)) && this.process?.killed) { // FFmpeg has ended. Let's figure out if it's because we killed it or whether it died of natural causes. this.debug(logPrefix + (signal === "SIGKILL" ? "(Killed)." : "(Expected).")); } else { // Something else has occurred. Inform the user, and stop everything. this.log.error(logPrefix + "unexpectedly with %s%s%s.", (exitCode !== null) ? "an exit code of " + exitCode.toString() : "", ((exitCode !== null) && signal) ? " and " : "", signal ? "a signal received of " + signal : ""); this.log.error("%s: FFmpeg command line that errored out was: %s %s", this.name(), this.protectCamera.stream.videoProcessor, this.commandLineArgs.join(" ")); this.stderrLog.map(x => this.log.error(x)); // Execute our error handler, if one is provided. if(errorHandler) { void errorHandler(util.format(logPrefix + " unexpectedly with exit code %s and signal %s.", exitCode, signal)); } } // Cleanup after ourselves. this.process?.stdin?.removeListener("error", errorListener); this.process?.stderr?.removeListener("data", dataListener); this.process = null; this.stderrLog = []; }); } // Stop the FFmpeg process and complete any cleanup activities. protected stopProcess(): void { // Check to make sure we aren't using stdin for data before telling FFmpeg we're done. if(!this.commandLineArgs.includes("pipe:0")) { this.process?.stdin.end("q"); } // Close our input and output. this.process?.stdin.destroy(); this.process?.stdout.destroy(); // In case we need to kill it again, just to be sure it's really dead. this.ffmpegTimeout = setTimeout(() => { this.process?.kill("SIGKILL"); }, 5000); // Send the kill shot. this.process?.kill(); } // Cleanup after we're done. public stop(): void { this.stopProcess(); } // Return the standard input for this process. public get stdin(): Writable | null { return this.process?.stdin ?? null; } // Return the standard output for this process. public get stdout(): Readable | null { return this.process?.stdout ?? null; } // Return the standard error for this process. public get stderr(): Readable | null { return this.process?.stderr ?? null; } // Validate whether or not we have a specific codec available to us in FFmpeg. public static async codecEnabled(videoProcessor: string, codec: string, log: Logging): Promise<boolean> { try { // Promisify exec to allow us to wait for it asynchronously. const execAsync = util.promisify(execFile); // Check for the codecs in FFmpeg. const { stdout } = await execAsync(videoProcessor, ["-codecs"]); // See if we can find the codec. return stdout.includes(codec); } catch(error) { // It's really a SystemError, but Node hides that type from us for esoteric reasons. if(error instanceof Error) { interface SystemError { cmd: string, code: string, errno: number, path: string, spawnargs: string[], stderr: string, stdout: string, syscall: string } const execError = error as unknown as SystemError; if(execError.code === "ENOENT") { log.error("Unable to find FFmpeg at: '%s'. Please make sure that you have a working version of FFmpeg installed.", execError.path); } else { log.error("Error running FFmpeg: %s", error.message); } } } return false; } }
the_stack
// Minimum TypeScript Version: 3.2 /** * Dummy type alias for a VML element (vector markup language). Might be replaced with the actual API at some point. * * Vector Markup Language (VML) was an XML-based file format for two-dimensional vector graphics. It was specified in * Part 4 of the Office Open XML standards ISO/IEC 29500 and ECMA-376. According to the specification, VML is a * deprecated format included in Office Open XML for legacy reasons only. */ export type VMLElement = Element; /** * Dummy type alias for a VML circle element. Might be replaced with the actual API at some point. */ export type VMLCircleElement = VMLElement; /** * Dummy type alias for a VML ellipse element. Might be replaced with the actual API at some point. */ export type VMLEllipseElement = VMLElement; /** * Dummy type alias for a VML image element. Might be replaced with the actual API at some point. */ export type VMLImageElement = VMLElement; /** * Dummy type alias for a VML path element. Might be replaced with the actual API at some point. */ export type VMLPathElement = VMLElement; /** * Dummy type alias for a VML rect element. Might be replaced with the actual API at some point. */ export type VMLRectElement = VMLElement; /** * Dummy type alias for a VML text element. Might be replaced with the actual API at some point. */ export type VMLTextElement = VMLElement; /** * The names of the base shapes that can be created on the {@link RaphaelPaper|canvas}. Used, for example, by the * {@link RaphaelStatic|Raphael()} constructor. */ export type RaphaelShapeType = "circle" | "ellipse" | "image" | "rect" | "text" | "path" | "set"; /** * Represents the technology used by Raphaël, depending on the browser support. * - `SVG`: Scalable vector graphics are used. * - `VML`: Vector markup language is used. * - `(empty string)`: Neither technology can be used. Raphaël will not work. * * Vector Markup Language (VML) was an XML-based file format for two-dimensional vector graphics. It was specified in * Part 4 of the Office Open XML standards ISO/IEC 29500 and ECMA-376. According to the specification, VML is a * deprecated format included in Office Open XML for legacy reasons only. */ export type RaphaelTechnology = "" | "SVG" | "VML"; /** * Represents the base line of a piece of text. */ export type RaphaelFontOrigin = "baseline" | "middle"; /** * Represents the stroke dash types supported by Raphaël. */ export type RaphaelDashArrayType = "" | "-" | "." | "-." | "-.." | ". " | "- " | "--" | "- ." | "--." | "--.."; /** * Represents the line cap types supported by Raphaël. See {@link RaphaelBaseElement.attr}. */ export type RaphaelLineCapType = "butt" | "square" | "round"; /** * Represents the line join types supported by Raphaël. See {@link RaphaelBaseElement.attr}. */ export type RaphaelLineJoinType = "bevel" | "round" | "miter"; /** * Represents the text anchor types supported by Raphaël. See {@link RaphaelBaseElement.attr}. */ export type RaphaelTextAnchorType = "start" | "middle" | "end"; /** * Names of the easing {@link RaphaelBuiltinEasingFormula}s that are available by default. See also the * {@link RaphaelStatic.easing_formulas} object. */ export type RaphaelBuiltinEasingFormula = "linear" | "<" | ">" | "<>" | "backIn" | "backOut" | "elastic" | "bounce" | "ease-in" | "easeIn" | "ease-out" | "easeOut" | "ease-in-out" | "easeInOut" | "back-in" | "back-out"; // see https://github.com/microsoft/TypeScript/issues/29729 /** * Names of the easing {@link RaphaelBuiltinEasingFormula}s that may be added by the user. See also the * {@link RaphaelStatic.easing_formulas} object. */ export type RaphaelCustomEasingFormula = string & {}; /** * Represents a single command of an SVG path string, such as a `moveto` or `lineto` command. * * Please note that Raphaël splits path strings such as `H 10 20` into two segments: `["H", 10]` and `["H", 20]`. */ export type RaphaelPathSegment = // move to ["M", number, number] | ["m", number, number] // line to | ["L", number, number] | ["l", number, number] // horizontal line to | ["H", number] | ["h", number] // vertical line to | ["V", number] | ["v", number] // quadratic bezier curve to | ["Q", number, number, number, number] | ["q", number, number, number, number] // smooth quadratic bezier curve to | ["T", number, number] | ["t", number, number] // curve to | ["C", number, number, number, number, number, number] | ["c", number, number, number, number, number, number] // smooth curve to | ["S", number, number, number, number] | ["s", number, number, number, number] // arc | ["A", number, number, number, number, number, number, number] | ["a", number, number, number, number, number, number, number] // Catmull-Rom curveto | ["R", number, number] | ["r", number, number] // close | ["Z"] | ["z"]; /** * Represents a single transform operation: * * - `t`: A translation operation. Parameters are [deltaX, deltaY] * - `s`: A scaling operation. Parameters are [scaleX, scaleY, originX, originY] * - `r`: A rotation operation: Parameters are [angleInDegrees, originX, originY] * - `m`: A general matrix transform. Parameters are [a, b, c, d, e, f], see {@link RaphaelMatrix}. */ export type RaphaelTransformSegment = // translate ["t", number, number] // scale (scale-x, scale-y, origin-x, origin-y) | ["s", number, number, number, number] | ["s", number, number] // rotate | ["r", number, number, number] | ["r", number] // general matrix transform | ["m", number, number, number, number, number, number] ; /** * Array that can be passed to the {@link RaphaelStatic|Raphael()} constructor. The first three arguments in the * array are, in order: * * - `containerID`: ID of the element which is going to be a parent for drawing surface. * - `width`: Width for the canvas. * - `height`: Height for the canvas. * * The remaining items are {@link RaphaelShapeDescriptor|descriptor objects} for the shapes that are created * initially. */ export type RaphaelConstructionOptionsArray4 = [ string, number, number, ...RaphaelShapeDescriptor[] ]; /** * Array that can be passed to the {@link RaphaelStatic|Raphael()} constructor. The first four arguments in the * array are, in order: * * - `x`: x coordinate of the viewport where the canvas is created. * - `y`: y coordinate of the viewport where the canvas is created. * - `width`: Width for the canvas. * - `height`: Height for the canvas. * * The remaining items are {@link RaphaelShapeDescriptor|descriptor objects} for the shapes that are created * initially. */ export type RaphaelConstructionOptionsArray5 = [ number, number, number, number, ...RaphaelShapeDescriptor[] ]; /** * An easing formula for smoothly interpolating between two values. The formula is passed the normalized animation * time and should return the relative animation position at that time. */ export type RaphaelEasingFormula = /** * @param normalizedAnimationTime A percentage between `0` and `1`, with `0` representing the beginning and `1` * representing the end of the animation time. * @return The relative animation position, a percentage between `0` and `1` for where the animation should be at * the given animation time. */ (normalizedAnimationTime: number) => number; /** * Distinguishes between a {@link RaphaelSet} and other {@link RaphaelElement}s. When an event handler is added to * a set, it is called with the this context set to the elements contained in the set. Otherwise, when the handler * is added to an element, it is called with the this context set to that element. * @param TTechnology Type of the technology used by this paper, either `SVG` or `VML`. * @param TBase A raphael element or set to unwrap. * @return If the element to unwrap is a {@link RaphaelSet}, a {@link RaphaelElement}. Otherwise, the given element. */ export type RaphaelUnwrapElement< TTechnology extends RaphaelTechnology, TBase extends RaphaelBaseElement<TTechnology> > = TBase extends RaphaelSet<TTechnology> ? RaphaelElement<TTechnology> : TBase; /** * Callback that is invoked once an animation is complete. * @param ThisContext Type of the argument passed as the this context. */ export type RaphaelOnAnimationCompleteHandler<ThisContext> = (this: ThisContext) => void; /** * A basic event handler for some common events on {@link RaphaelElement}s, such as `click` and `dblclick`. * @param ThisContext Type of the this context of the handler. * @param TEvent Type of the event passed to the handler. */ export type RaphaelBasicEventHandler<ThisContext, TEvent extends Event> = /** * @param event The original DOM event that triggered the event this handler was registered for. * @return A value that is returned as the return value of the `document.addEventListener` callback. */ (this: ThisContext, event: TEvent) => any; /** * Represents the handler callback that is called when dragging starts. See {@link RaphaelBaseElement.drag}. * @param ThisContext The type of the this context of the handler. */ export type RaphaelDragOnStartHandler<ThisContext> = /** * @param x position of the mouse * @param y position of the mouse * @param event DOM event object * @return A value that is returned as the return value of the `document.addEventListener` callback. */ (this: ThisContext, x: number, y: number, event: DragEvent) => any; /** * Represents the handler callback that is called when the pointer is moved while dragging. See * {@link RaphaelBaseElement.drag}. * @param ThisContext The type of the this context of the handler. */ export type RaphaelDragOnMoveHandler<ThisContext> = /** * @param deltaX How much the pointer has moved in the horizontal direction compared to when this handler was most * recently invoked. * @param deltaY How much the pointer has moved in the vertical direction compared to when this handler was most * recently invoked. * @param mouseX The current horizontal position of the mouse. * @param mouseY The current vertical position of the mouse. * @return A value that is returned as the return value of the `document.addEventListener` callback. */ (this: ThisContext, deltaX: number, deltaY: number, mouseX: number, mouseY: number, event: DragEvent) => any; /** * Represents an event handler for when the pointer moves over another element while dragging. See also * {@link RaphaelBaseElement.onDragOver}. * @param TTechnology Type of the technology used by this paper, either `SVG` or `VML`. * @param ThisContext Type of the this context of the callback. */ export type RaphaelDragOnOverHandler< TTechnology extends RaphaelTechnology = "SVG" | "VML", ThisContext = RaphaelElement<TTechnology> > = /** * @param targetElement The element you are dragging over. * @return A value that is returned as the return value of the `document.addEventListener` callback. */ (this: ThisContext, targetElement: RaphaelElement<TTechnology>) => any; /** * Represents the handler callback that is called when dragging ends. See {@link RaphaelBaseElement.drag}. * @param ThisContext The type of the this context of the handler. */ export type RaphaelDragOnEndHandler<ThisContext> = /** * @param event DOM event object * @return A value that is returned as the return value of the `document.addEventListener` callback. */ (this: ThisContext, event: DragEvent) => any; /** * You can add your own method to elements, see {@link RaphaelStatic.el} for more details. * * Plugin methods may take any arbitrary number of parameters and may return any value. When possible, consider * return `this` to allow for chaining. * * @param TTechnology Type of the technology used by this paper, either `SVG` or `VML`. * @param TArgs Type of the arguments required by this element method plugin. These arguments need to be passed * when the method is called on an {@link RaphaelElement}. * @param TRetVal Type of the value that is returned by this element method plugin. This is also the value that * is returned when the method is called on a {@link RaphaelElement}. */ export type RaphaelElementPluginMethod< TTechnology extends RaphaelTechnology = "SVG" | "VML", TArgs extends any[] = any, TRetVal = any > = /** * @param args The arguments, as required by this element plugin. They need to be passed when the plugin method * is called on a {@link RaphaelElement}. * @return The value that should be returned by this plugin method. This is also the value that is returned when * this plugin method is called on a {@link RaphaelElement}. */ (this: RaphaelElement<TTechnology>, ...args: TArgs) => TRetVal; /** * You can add your own method to set, see {@link RaphaelStatic.st} for more details. * * Plugin methods may take any arbitrary number of parameters and may return any value. When possible, consider * return `this` to allow for chaining. * * @param TTechnology Type of the technology used by this paper, either `SVG` or `VML`. * @param TArgs Type of the arguments required by this set method plugin. These arguments need to be passed * when the method is called on an {@link RaphaelSet}. * @param TRetVal Type of the value that is returned by this set method plugin. This is also the value that * is returned when the method is called on a {@link RaphaelSet}. */ export type RaphaelSetPluginMethod< TTechnology extends RaphaelTechnology = "SVG" | "VML", TArgs extends any[] = any, TRetVal = any > = /** * @param args The arguments, as required by this set plugin. They need to be passed when the plugin method * is called on a {@link RaphaelSet}. * @return The value that should be returned by this plugin method. This is also the value that is returned when * this plugin method is called on a {@link RaphaelSet}. */ (this: RaphaelSet<TTechnology>, ...args: TArgs) => TRetVal; /** * You can add your own method to the canvas, see {@link RaphaelStatic.fn} for more details. * * Plugin methods may take any arbitrary number of parameters and may return any value. When possible, consider * return `this` to allow for chaining. * * @param TTechnology Type of the technology used by this paper, either `SVG` or `VML`. * @param TArgs Type of the arguments required by this paper method plugin. These arguments need to be passed * when the method is called on an {@link RaphaelPaper}. * @param TRetVal Type of the value that is returned by this paper method plugin. This is also the value that * is returned when the method is called on a {@link RaphaelPaper}. */ export type RaphaelPaperPluginMethod< TTechnology extends RaphaelTechnology = "SVG" | "VML", TArgs extends any[] = any, TRetVal = any > = /** * @param args The arguments, as required by this paper plugin. They need to be passed when the plugin method * is called on a {@link RaphaelPaper}. * @return The value that should be returned by this plugin method. This is also the value that is returned when * this plugin method is called on a {@link RaphaelPaper}. */ (this: RaphaelPaper<TTechnology>, ...args: TArgs) => TRetVal; /** * If you have a set of attributes that you would like to represent as a function of some number you can do it * easily with custom attributes, see {@link RaphaelPaper.customAttributes} for more details. * * @param TTechnology Type of the technology used by this paper, either `SVG` or `VML`. */ export type RaphaelCustomAttribute< TTechnology extends RaphaelTechnology = "SVG" | "VML", TArgs extends number[] = any > = /** * @param values Numerical values for this custom attribute. * @return The SVG attributes for the given values. */ (this: RaphaelElement<TTechnology>, ...values: TArgs) => Partial<RaphaelAttributes>; /** * Represents a result or return value of an operation that can fail, such as due to illegal arguments. For example, * {@link RaphaelStatic.getRGB} returns an error if the string could not be parsed. * * This adds an `error` property. When it is set to to `true`, the operation was not successful - such as when an * input string could not be parsed or the arguments are out of range. * * @param T Type of the result when the operation did not fail. */ export type RaphaelPotentialFailure<T extends {}> = T & { /** * If present and set to `1`, indicates that the operation that produced this result failed. Other fields * properties in this object may not be valid. */ error?: number | undefined; }; /** * You can add your own method to the canvas. Please note that you can create your own namespaces inside the * {@link RaphaelStatic.fn} object - methods will be run in the context of {@link RaphaelPaper|canvas} anyway: * * ```javascript * Raphael.fn.arrow = function (x1, y1, x2, y2, size) { * return this.path( ... ); * }; * // or create namespace * Raphael.fn.mystuff = { * arrow: function () {…}, * star: function () {…}, * // etc... * }; * * var paper = Raphael(10, 10, 630, 480); * // then use it * paper.arrow(10, 10, 30, 30, 5).attr({fill: "#f00"}); * paper.mystuff.arrow(); * paper.mystuff.star(); * ``` * * @param TTechnology Type of the technology used by this paper, either `SVG` or `VML`. * @param T Type of the paper or sub namespace in the paper. */ export type RaphaelPaperPluginRegistry< TTechnology extends RaphaelTechnology = "SVG" | "VML", T extends {} = RaphaelPaper<TTechnology>> = { /** * Either the paper plugin method or a new namespace with methods. */ [P in keyof T]: T[P] extends (...args: any) => any ? RaphaelPaperPluginMethod<TTechnology, Parameters<T[P]>, ReturnType<T[P]>> : RaphaelPaperPluginRegistry<TTechnology, T[P]>; }; /** * You can add your own method to elements. This is useful when you want to hack default functionality or want * to wrap some common transformation or attributes in one method. In contrast to canvas methods, you can * redefine element method at any time. Expending element methods would not affect set. * * ```javascript * Raphael.el.red = function () { * this.attr({fill: "#f00"}); * }; * // then use it * paper.circle(100, 100, 20).red(); * ``` * * @param TTechnology Type of the technology used by this paper, either `SVG` or `VML`. */ export type RaphaelElementPluginRegistry< TTechnology extends RaphaelTechnology = "SVG" | "VML" > = { [P in keyof RaphaelElement<TTechnology>]: RaphaelElement<TTechnology>[P] extends (...args: any) => any ? RaphaelElementPluginMethod< TTechnology, Parameters<RaphaelElement<TTechnology>[P]>, ReturnType<RaphaelElement<TTechnology>[P]> > : never; }; /** * You can add your own method to elements and sets. It is wise to add a set method for each element method you * added, so you will be able to call the same method on sets too. See also {@link el}. * * ```javascript * Raphael.el.red = function() { * this.attr({fill: "#f00"}); * }; * * Raphael.st.red = function() { * this.forEach(function () { * this.red(); * }); * }; * * // then use it * paper.set(paper.circle(100, 100, 20), paper.circle(110, 100, 20)).red(); * ``` * * @param TTechnology Type of the technology used by this paper, either `SVG` or `VML`. */ export type RaphaelSetPluginRegistry< TTechnology extends RaphaelTechnology = "SVG" | "VML" > = { [P in keyof RaphaelSet<TTechnology>]: RaphaelSet<TTechnology>[P] extends (...args: any) => any ? RaphaelSetPluginMethod< TTechnology, Parameters<RaphaelSet<TTechnology>[P]>, ReturnType<RaphaelSet<TTechnology>[P]>> : never; }; /** * Represents the SVG and VML native elements that implement a particular abstract element, such as circle and paths. * @typeparam TSvg Type of the native SVG element. * @typeparam TVml Type of the native VML element. */ export interface RaphaelElementByTechnologyMap< TSvg extends SVGElement = SVGElement, TVml extends VMLElement = VMLElement > { SVG: TSvg; VML: TVml; "": never; } /** * A map between the abstract element shapes and their implementation for each supported {@link RaphaelTechnology}. */ export interface RaphaelElementImplementationMap { /** The elements that implement the {@link RaphaelPaper.circle} shape. */ circle: RaphaelElementByTechnologyMap<SVGCircleElement, VMLCircleElement>; /** The elements that implement the {@link RaphaelPaper.ellipse} shape. */ ellipse: RaphaelElementByTechnologyMap<SVGEllipseElement, VMLEllipseElement>; /** The elements that implement the {@link RaphaelPaper.image} shape. */ image: RaphaelElementByTechnologyMap<SVGImageElement, VMLImageElement>; /** The elements that implement the {@link RaphaelPaper.path} shape. */ path: RaphaelElementByTechnologyMap<SVGPathElement, VMLPathElement>; /** The elements that implement the {@link RaphaelPaper.rect} shape. */ rect: RaphaelElementByTechnologyMap<SVGRectElement, VMLRectElement>; /** The elements that implement the {@link RaphaelPaper.text} shape. */ text: RaphaelElementByTechnologyMap<SVGTextElement, VMLTextElement>; } /** * Represents a two dimensional point, with a cartesian x and y coordinate. */ export interface RaphaelCartesianPoint { /** The x coordinate of the point. */ x: number; /** The y coordinate of the point. */ y: number; } /** * Represents a two dimensional point on a curve, with a cartesian x and y coordinate, and the derivate of that * point on the curve. */ export interface RaphaelCartesianCurvePoint extends RaphaelCartesianPoint { /** * Angle of the curve derivative of the curve at the point. */ alpha: number; } /** * Represents a point on a cubic bezier curve, the result of {@link RaphaelStatic.findDotsAtSegment}. */ export interface RaphaelCubicBezierCurvePointInfo extends RaphaelCartesianCurvePoint { /** * The end point of the cubic bezier curve. */ end: RaphaelCartesianPoint; /** * The left anchor point of the cubic bezier curve. */ m: RaphaelCartesianPoint; /** * The right anchor point of the cubic bezier curve. */ n: RaphaelCartesianPoint; /** * The start point of the cubic bezier curve. */ start: RaphaelCartesianPoint; } /** * Represents a parsed RGB color, such as the result of {@link RaphaelStatic.getRGB}. */ export interface RaphaelRgbComponentInfo { /** Hex string of the color, in the format `#XXXXXX`. */ hex: string; /** The RGB red channel */ r: number; /** The RGB green channel */ g: number; /** The RGB blue channel */ b: number; } /** * Represents a parsed HSB color, such as the result of {@link RaphaelStatic.rgb2hsb}. */ export interface RaphaelHsbComponentInfo { /** * The HSB or HSL hue channel. */ h: number; /** * The HSB or HSL saturation channel. */ s: number; /** * The HSB brightness channel. */ b: number; } /** * Represents a parsed HSL color, such as the result of {@link RaphaelStatic.rgb2hsl}. */ export interface RaphaelHslComponentInfo { /** * The HSB or HSL hue channel. */ h: number; /** * The HSB or HSL saturation channel. */ s: number; /** * The HSL luminosity channel. */ l: number; } /** * Represents the result of a call to {@link RaphaelStatic.color}, i.e. information about the RGB and HSV/L color * channels. */ export interface RaphaelFullComponentInfo extends RaphaelRgbComponentInfo, RaphaelHsbComponentInfo, RaphaelHslComponentInfo { } /** * Represents an axis aligned bounding box, see {@link RaphaelBaseElement.getBBox}. */ export interface RaphaelAxisAlignedBoundingBox { /** * Horizontal coordinate of the top left corner. */ x: number; /** * Horizontal coordinate of the bottom right corner. */ x2: number; /** * Vertical coordinate of the top left corner. */ y: number; /** * Vertical coordinate of the bottom right corner. */ y2: number; /** * Horizontal coordinate of the center of the box. */ cx: number; /** * Vertical coordinate of the center of the box. */ cy: number; /** * Width of the bounding box. */ width: number; /** * Height of the bounding box. */ height: number; } /** * Represents the settings for a glow-like effect. See also {@link RaphaelBaseElement.glow}. */ export interface RaphaelGlowSettings { /** The glow color, default is `black`. */ color: string; /** Whether the glow effect will be filled, default is `false`. */ fill: boolean; /** Horizontal offset, default is `0`. */ offsetx: number; /** Vertical offset, default is `0`. */ offsety: number; /** Opacity of the glow effect, default is `0.5`. */ opacity: number; /** size of the glow, default is `10`. */ width: number; } /** * Represents the status of a {@link RaphaelAnimation}, i.e. the progress of the animation. */ export interface RaphaelAnimationStatus { /** The animation to which the status applies. */ anim: RaphaelAnimation; /** The current status of the animation, i.e. the normalized animation time, a value between `0` and `1`. */ status: number; } /** * Represents the SVG attributes that can be set on an SVG element, such as `stroke`, `width`, or `height`. See also * {@link RaphaelBaseElement.attr}. * * ## Gradients * * ### Linear gradient format * * ``` * <angle>-<colour>[-<colour>[:<offset>]]*-<colour> * ``` * * For example, valid gradient are: * - `90-#fff-#000`: 90° gradient from white to black * - `0-#fff-#f00:20-#000`: 0° gradient from white via red (at 20%) to black. * * ### Radial gradient format * * ``` * r[(<fx>, <fy>)]<colour>[-<colour>[:<offset>]]*-<colour> * ``` * * For example, valid radial gradient are: * * - `r#fff-#000`: gradient from white to black * - `r(0.25, 0.75)#fff-#000`: gradient from white to black with focus point at 0.25, 0.75. * * Focus point coordinates are in the range [0,1]. Radial gradients can only be applied to circles and ellipses. * * ## Colour Parsing * * The following are all recognized as valid colors: * * - Colour name, such as "red", "green", "cornflowerblue", etc) * - `#RGB`: shortened HTML colour: ("#000", "#fc0", etc) * - `#RRGGBB`: full length HTML colour: ("#000000", "#bd2300") * - `rgb(RRR, GGG, BBB)`: red, green and blue channels’ values: ("rgb(200, 100, 0)") * - `rgb(RRR%, GGG%, BBB%)`: same as above, but in %: ("rgb(100%, 175%, 0%)") * - `rgba(RRR, GGG, BBB, AAA)`: red, green and blue channels’ values: ("rgba(200, 100, 0, .5)") * - `rgba(RRR%, GGG%, BBB%, AAA%)`: same as above, but in %: ("rgba(100%, 175%, 0%, 50%)") * - `hsb(HHH, SSS, BBB)`: hue, saturation and brightness values: ("hsb(0.5, 0.25, 1)") * - `hsb(HHH%, SSS%, BBB%)`: same as above, but in % * - `hsba(HHH, SSS, BBB, AAA)`: same as above, but with opacity * - `hsl(HHH, SSS, LLL)`: almost the same as hsb, see Wikipedia page * - `hsl(HHH%, SSS%, LLL%)`: same as above, but in % * - `hsla(HHHH, SSS, LLL, AAA)`: same as above, but with opacity * * Optionally for hsb and hsl you could specify hue as a degree: "hsl(240deg, 1, .5)" or, if you want to go fancy, "hsl(240°, 1, .5)" */ export interface RaphaelAttributes { /** * Arrowhead on the end of the path. The format for the string is `<type>[-<width>[-<length>]]`. * * Possible value for `type` are: * - classic * - block * - open * - oval * - diamond * - none * * Possible value for `width` are: * - wide * - narrow * - medium * * Possible values for `length` are * - long * - short * - medium */ "arrow-end": string; /** * Comma or space separated values: `x`, `y`, `width` and `height`. */ "clip-rect": string; /** * CSS type of the cursor. */ cursor: string; /** * Horizontal coordinate of the origin of the circle. */ cx: number; /** * Vertical coordinate of the origin of the circle. */ cy: number; /** * Colour, gradient or image. */ fill: string; /** * Opacity of the fill color. */ "fill-opacity": number; /** * The combined font family and font size, e.g. `10px "Arial"`. */ font: string; /** * Name of the font family to use. */ "font-family": string; /** * Font size in pixels. */ "font-size": number | string; /** * Font weight as a number, usually between `100` to `900`. Can also be `"bold"` etc. */ "font-weight": string; /** * The height of e.g. a rectangle in pixels. */ height: number; /** * URL, if specified element behaves as hyperlink. */ href: string; /** * Opacity of the element, usually between `0` and `1`. */ opacity: number; /** * An SVG path string, e.g. `M 10 10 L 20 10 Z`. */ path: string; /** * Radius of the circle in pixels. */ r: number; /** * Horizontal half-axis of the ellipse in pixels. */ rx: number; /** * Vertical half-axis of the ellipse in pixels. */ ry: number; /** * Image URL, only works for {@link RaphaelPaper.image} elements. */ src: string; /** * CSS stroke color. */ stroke: string; /** * Controls the pattern of dashes and gaps used to form the shape of a path's stroke. */ "stroke-dasharray": RaphaelDashArrayType; /** * Specifies the shape to be used at the end of open subpaths when they are stroked, and the shape to be drawn * for zero length subpaths whether they are open or closed. */ "stroke-linecap": RaphaelLineCapType; /** * Specifies the shape to be used at the corners of paths or basic shapes when they are stroked. */ "stroke-linejoin": RaphaelLineJoinType; /** * When two line segments meet at a sharp angle and a value of `miter`, `miter-clip`, or `arcs` has been * specified for `stroke-linejoin`, it is possible for the join to extend far beyond the thickness of the line * stroking the path. The `stroke-miterlimit` imposes a limit on the extent of the line join. */ "stroke-miterlimit": number; /** * Opacity of the stroke, usually between `0` and `1`. */ "stroke-opacity": number; /** * Width of the stroke in pixels. */ "stroke-width": number; /** * Used with {@link href}. */ target: string; /** * Contents of the text element. */ text: string; /** * Used to align (start-, middle- or end-alignment) a string of pre-formatted text or auto-wrapped text where * the wrapping area is determined from the `inline-size` property relative to a given point. */ "text-anchor": RaphaelTextAnchorType; /** * Will create a tooltip with a given text. */ title: string; /** * The transform property of this element. */ transform: string | RaphaelTransformSegment | RaphaelTransformSegment[]; /** * The width of e.g. a rectangle in pixels. */ width: number; /** * The horizontal x coordinate in pixels. */ x: number; /** * The vertical y coordinate in pixels. */ y: number; } /** * Represents the {@link RaphaelAttributes} returned when reading the value of an attribute via * {@link RaphaelBaseElement.attr}. Writing to an attribute allows different types for some attributes that are * normalized to canonical type. */ export interface RaphaelReadAttributes extends RaphaelAttributes { /** * The transform property of this element. */ transform: RaphaelTransformSegment[]; } /** * Represents the primitive transformations that, when applied successively, result in a given matrix. See * {@link RaphaelMatrix.split}. */ export interface RaphaelMatrixTransformInfo { /** Translation in the horizontal direction. */ dx: number; /** Translation in the vertical direction. */ dy: number; /** Scaling factor in the horizontal direction. */ scalex: number; /** Scaling factor in the vertical direction. */ scaley: number; /** Shearing coefficient. */ shear: number; /** Rotation in degree. */ rotate: number; /** * Whether the matrix can be represented via simple transformations. If this set to `false` the other properties * of this instance are devoid of meaning and should not be accessed. */ isSimple: boolean; } /** * Represents an animation, i.e. a function that interpolates between two or more values. */ export interface RaphaelAnimation { /** * Creates a copy this existing animation object with the given delay. * @param delay Number of milliseconds that represent the delay between the start of the animation start and * the actual animation. * @return A copy of this animation with the given delay. */ delay(delay: number): RaphaelAnimation; /** * Creates a copy of existing animation object with given repetition. * @param repeat Number iterations of animation. For a never-ending animation pass `Infinity`. * @return A copy of this animation that repeats the given number of times. */ repeat(repeat: number): RaphaelAnimation; } /** * Represents the characteristics of a {@link RaphaelFont}. */ export interface RaphaelFontFace { /** * The ascent property of this font, such as `270`. * * The ascent is the recommended distance above the baseline for singled spaced text. */ ascent: number | string; /** * The axis aligned bounding box of all glyphs, such as `-11 -274 322 94` (top left corner and width and height). */ bbox: string; /** * The descent property of this font, such as `-90`. * * The ascent is the recommended distance below the baseline for singled spaced text */ descent: number | string; /** * The font family property of this font. */ "font-family": string; /** * The font stretch property of this font, such as `normal`. */ "font-stretch": string; /** * The font style property of this font. */ "font-style": string; /** * The weight of this font, such as `200`. */ "font-weight": number | string; /** * The units-per-em property of this font. * * The units-per-em attribute specifies the number of coordinate units on the "em square", an abstract square whose * height is the intended distance between lines of type in the same type size. */ "units-per-em": number | string; /** * The panose-1 classification of this font. * * Panose-1 is a system for describing characteristics of Latin fonts that is based on calculable quantities: * dimensions, angles, shapes, etc. It is based on a set of 10 numbers, which take values between 0 and 15. A font * thus becomes a vector in a 10-dimensional space, and one can calculate the distance between two fonts as a * Cartesian distance. */ "panose-1": string; /** * When an underline is drawn below a glyph, the vertical offset of that underline. Usually negative, such as `36`. */ "underline-position": number | string; /** * The thickness of the underline, when a glyph is underlined, such as `18`. */ "underline-thickness": number | string; /** * The range of characters this font contains, such as `U+0020-U+00F3`. */ "unicode-range": string; /** * The x-height property of this font. * * The x-height, or corpus size, is the distance between the baseline and the mean line of lower-case letters. */ "x-height": number | string; } /** * Represents a glyph (character) in a {@link RaphaelFont}. */ export interface RaphaelFontGlyph { /** An SVG path string for drawing this glyph. */ d: string; /** The width of this glyph. */ w: number; } /** * Represents a font object as used by Raphaël. * * This needs to be a Cufon font object, see https://github.com/sorccu/cufon. */ export interface RaphaelFont { /** The font faces that are available in this font. */ face: Partial<RaphaelFontFace>; /** The glyphs that are available in this font. */ glyphs: Record<string, Partial<RaphaelFontGlyph>>; /** The width of this font. */ w: number; } /** * Base interface implemented by all elements: {@link RaphaelElement}, {@link RaphaelPath}, and {@link RaphaelSet}. * * An element is an object that can be drawn on the screen, such as via SVG or VML. * @typeparam TTechnology The target {@link RaphaelTechnology}. */ export interface RaphaelBaseElement< TTechnology extends RaphaelTechnology = "SVG" | "VML" > { /** * Creates and starts animation for given element. * @param targetAttributes Final attributes for the element, see also {@link attr}. * @param durationMilliseconds Number of milliseconds for the animation to run. * @param easing Easing type. Accept one of {@link RaphaelStatic.easing_formulas} or CSS forms such as * `cubic‐bezier(XX, XX, XX, XX)`. * @param onAnimationComplete Callback function. Will be called at the end of animation. * @return this element for chaining. */ animate( targetAttributes: Partial<RaphaelAttributes>, durationMilliseconds: number, easing?: RaphaelBuiltinEasingFormula | RaphaelCustomEasingFormula, onAnimationComplete?: RaphaelOnAnimationCompleteHandler<this> ): this; /** * Creates and starts animation for given element. * @param animation The animation to apply to this element. Use {@link RaphaelStatic.animation} to create an * animation. * @return this element for chaining. */ animate(animation: RaphaelAnimation): this; /** * Acts similar to {@link animate}, but ensures that the given animation runs in sync with another given * element. * @param otherElement Element to sync with. * @param otherAnimation animation to sync with. * @param targetAttributes Final attributes for the element, see also {@link attr}. * @param durationMilliseconds Number of milliseconds for the animation to run. * @param easing Easing type. Accept one of RaphaelStatic.easing_formulas or CSS forma such as * `cubic‐bezier(XX, XX, XX, XX)`. * @param onAnimationComplete Callback function. Will be called at the end of animation. * @return this element for chaining. */ animateWith( otherElement: RaphaelElement<TTechnology>, otherAnimation: RaphaelAnimation, targetAttributes: Partial<RaphaelAttributes>, durationMilliseconds: number, easing?: RaphaelBuiltinEasingFormula | RaphaelCustomEasingFormula, onAnimationComplete?: RaphaelOnAnimationCompleteHandler<this> ): this; /** * Acts similar to {@link animate}, but ensures that the given animation runs in sync with another given element. * @param otherElement Element to sync with. * @param otherAnimation animation to sync with. * @param animation The animation to apply to this element. Use {@link RaphaelStatic.animation} to create an * animation. * @return this element for chaining. */ animateWith( otherElement: RaphaelElement<TTechnology>, otherAnimation: RaphaelAnimation, animation: RaphaelAnimation ): this; /** * Set the given attribute of this element to the given value. * @typeparam K Type of the attribute name to set. * @param attributeName Name of an attribute to set. * @param attributeValue New value for the attribute. * @return this element for chaining. */ attr<K extends keyof RaphaelAttributes>(attributeName: K, attributeValue: RaphaelAttributes[K] | undefined): this; /** * Finds the current value of the given attribute. * @typeparam K Type of the attribute name to read. * @param attributeName Name of the attribute to read. * @return The value of the given attribute, or `undefined` if the attribute is unset or does not exist. */ attr<K extends keyof RaphaelReadAttributes>(attributeName: K): RaphaelReadAttributes[K] | undefined; /** * Finds the current value of the given attributes. * @typeparam K Type of the attribute names to read. * @param attributeNames Names of the attributes to read. * @return A tuple with the values of the given attribute names. */ attr< // Trick compiler into inferring a tuple type without the consumer having to specify the tuple type explicitly // https://github.com/microsoft/TypeScript/issues/22679 K extends (Array<keyof RaphaelReadAttributes> & { "0"?: keyof RaphaelReadAttributes | undefined }) >(attributeNames: K): { [P in keyof K]: K[P] extends keyof RaphaelReadAttributes ? RaphaelReadAttributes[K[P]] | undefined : never }; /** * Writes the given attributes to this element. * @param attributes Attributes to set on this element. * @return this element for chaining. */ attr(attributes: Partial<RaphaelAttributes>): this; /** * Adds an event handler for the click event to this element. * @param handler Handler for the event. * @return this element for chaining. */ click(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, MouseEvent>): this; /** * Create a new element with all properties and attributes of this element. * @return A clone of this element. */ clone(): this; /** * Retrieves the value associated with the given key. See also {@link removeData}. * @param key Key of the datum to retrieve. * @return The data associated with the given key. */ data(key: string): any; /** * Adds the given value associated with the given key. See also {@link removeData}. * @param key Key of the datum to store. * @param value Datum to store. */ data(key: string, value: any): this; /** * Adds an event handler for the double click event to this element. * @param handler Handler for the event. * @return this element for chaining. */ dblclick(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, MouseEvent>): this; /** * Adds the event handlers for a drag of this element. * @typeparam MoveThisContext Type of the this context for the `onMove` handler. * @typeparam StartThisContext Type of the this context for the `onStart` handler. * @typeparam EndThisContext Type of the this context for the `onEnd` handler. * @param onMoveHandler Handler for when the pointer is moved while dragging. * @param onStartHandler Handler for when the dragging starts. * @param onEndHandler Handler for when the dragging ends. * @param moveThisContext The this context with which the `onMove` handler is invoked. * @param startThisContext The this context with which the `onStart` handler is invoked. * @param endThisContext The this context with which the `onEnd` handler is invoked. * @return this element for chaining. */ drag< MoveThisContext = RaphaelUnwrapElement<TTechnology, this>, StartThisContext = RaphaelUnwrapElement<TTechnology, this>, EndThisContext = RaphaelUnwrapElement<TTechnology, this> >( onMoveHandler: RaphaelDragOnMoveHandler<MoveThisContext>, onStartHandler: RaphaelDragOnStartHandler<StartThisContext>, onEndHandler: RaphaelDragOnEndHandler<EndThisContext>, moveThisContext?: MoveThisContext, startThisContext?: StartThisContext, endThisContext?: EndThisContext ): this; /** * Returns a bounding box for this element. * @param isWithoutTransform `true` if you want to have bounding box before transformations are applied. * Default is `false`. * @return The smallest bounding box that contains this element. */ getBBox(isWithoutTransform?: boolean): RaphaelAxisAlignedBoundingBox; /** * Determine if given point is inside this element’s shape * @param x x coordinate of the point * @param y y coordinate of the point * @return `true` if point inside the shape */ isPointInside(x: number, y: number): boolean; /** * Return a set of elements that create a glow-like effect around this element. * * Note: Glow is not connected to the element. If you change element attributes it will not adjust itself. * @param glow Optional settings for the glow effect. * @return A set of elements that produce the given glow effect. */ glow(glow?: Partial<RaphaelGlowSettings>): RaphaelSet<TTechnology>; /** * Makes this element invisible. See also {@link RaphaelElement.show}. * @return this element for chaining. */ hide(): this; /** * Adds event handlers for the hover events to this element. * @typeparam HoverInThisContext Type of the this context for the `onHoverIn` handler. * @typeparam HoverOutThisContext Type of the this context for the `onHoverOut` handler. * @param onHoverInHandler Handler for when the pointer enters this element. * @param onHoverOutHandler Handler for when the pointer leaves this element. * @param hoverInThisContext The this context with which the `onHoverIn` handler is invoked. * @param hoverOutThisContext The this context with which the `onHoverOut` handler is invoked. * @return this element for chaining. */ hover< HoverInThisContext = RaphaelUnwrapElement<TTechnology, this>, HoverOutThisContext = RaphaelUnwrapElement<TTechnology, this>, >( onHoverInHandler: RaphaelBasicEventHandler<HoverInThisContext, MouseEvent>, onHoverOutHandler: RaphaelBasicEventHandler<HoverOutThisContext, MouseEvent>, hoverInThisContext?: HoverInThisContext, hoverOutThisContext?: HoverOutThisContext ): this; /** * Inserts current object after the given one in the DOM. * @param element Element to insert. * @return this element for chaining. */ insertAfter(element: RaphaelElement<TTechnology>): this; /** * Inserts current object before the given one. * @param element Element to insert. * @return this element for chaining. */ insertBefore(element: RaphaelElement<TTechnology>): this; /** * The current transform matrix representing the total transform of this element. */ matrix: RaphaelMatrix; /** * Adds an event handler for the mousedown event to this element. * @param handler Handler for the event. * @return this element for chaining. */ mousedown(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, MouseEvent>): this; /** * Adds an event handler for the mousemove event to this element. * @param handler Handler for the event. * @return this element for chaining. */ mousemove(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, MouseEvent>): this; /** * Adds an event handler for the mouseout event to this element. * @param handler Handler for the event. * @return this element for chaining. */ mouseout(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, MouseEvent>): this; /** * Adds an event handler for the mouseover event to this element. * @param handler Handler for the event. * @return this element for chaining. */ mouseover(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, MouseEvent>): this; /** * Adds an event handler for the mouseup event to this element. * @param handler Handler for the event. * @return this element for chaining. */ mouseup(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, MouseEvent>): this; /** * Shortcut for assigning an event handler for the `drag.over.<id>` event, where `id` is the ID of the element, * see {@link RaphaelElement.id}. * @param onDragOverHandler Handler for event, first argument would be the element you are dragging over * @return this element for chaining. */ onDragOver(onDragOverHandler: RaphaelDragOnOverHandler<TTechnology, RaphaelUnwrapElement<TTechnology, this>>): this; /** * Stops an animation of this element with the ability to resume it later on. * @param anim Animation to pause. If not given, pauses all current animations. * @return this element for chaining. */ pause(anim?: RaphaelAnimation): this; /** * Removes this element from the paper. */ remove(): void; /** * Removes the value associated with this element by the given key. If the key is not provided, removes all the * data of this element. * @param key Key of the datum to remove. * @return this element for chaining. */ removeData(key?: string): this; /** * Resumes animation if it was paused with {@link RaphaelElement.pause} method. * @param anim The animation that was paused. If not given, resumes all currently paused animations. * @return this element for chaining. */ resume(anim?: RaphaelAnimation): this; /** * Rotates this element by the given angle around the given point. * @param degrees Angle in degrees by which to rotate. * @param centerX Horizontal coordinate of the center of rotation. * @param centerY Vertical coordinate of the center of rotation. * @return this element for chaining. */ rotate(degrees: number, centerX: number, centerY: number): this; /** * Rotates this element by the given angle around the center of this shape. * @param degrees Angle in degrees by which to rotate. * @return this element for chaining. */ rotate(degrees: number): this; /** * Scales this element by the given scale factor, relative to the given center. * @param scaleFactorX Horizontal part of the scale factor. * @param scaleFactorY Vertical part of the scale factor. * @param centerX Horizontal coordinate of the center of the scaling operation. * @param centerY Vertical coordinate of the center of the scaling operation. * @return this element for chaining. */ scale(scaleFactorX: number, scaleFactorY: number, centerX: number, centerY: number): this; /** * Scales this element by the given scale factor. The center of this * shape is used as the center of the scaling operation. * @param scaleFactorX Horizontal part of the scale factor. * @param scaleFactorY Vertical part of the scale factor. If not given, defaults to `scaleFactorX`. * @return this element for chaining. */ scale(scaleFactorX: number, scaleFactorY?: number): this; /** * Sets the status of animation of the element in milliseconds. Similar to {@link status} method. * @param animation Animation for which to set the status. * @param value Number of milliseconds from the beginning of the animation. * @return this element for chaining. */ setTime(animation: RaphaelAnimation, value: number): this; /** * Makes this element visible. See also {@link RaphaelElement.hide}. * @return this element for chaining. */ show(): this; /** * Gets the status (normalized animation time) of the current animations of this element. * @return The status of all animations currently playing. */ status(): RaphaelAnimationStatus[]; /** * Gets the status of the given animation of this element. * @param animation Animation object for which to retrieve the status. * @return The current value (normalized animation time) of the given animation. */ status(animation: RaphaelAnimation): number; /** * Sets the status of the given animation of this element to the given value. This will cause the animation to * jump to the given position. * @param animation Animation object for which to set the status. * @param value New value (normalized animation time) for the animation, between `0` and `1`. * @return this element for chaining. */ status(animation: RaphaelAnimation, value: number): this; /** * Stops all or the the given animation of this element. * @param animation An animation to stop. If not given, stops all animations currently playing. * @return this element for chaining. */ stop(animation?: RaphaelAnimation): this; /** * Moves this element so it is the furthest from the viewer’s eyes, behind other elements. * @return this element for chaining. */ toBack(): this; /** * Moves this element so it is the closest to the viewer’s eyes, on top of other elements. * @return this element for chaining. */ toFront(): this; /** * Adds an event handler for the touchcancel event to this element. * @param handler Handler for the event. * @return this element for chaining. */ touchcancel(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, TouchEvent>): this; /** * Adds an event handler for the touchend event to this element. * @param handler Handler for the event. * @return this element for chaining. */ touchend(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, TouchEvent>): this; /** * Adds an event handler for the touchmove event to this element. * @param handler Handler for the event. * @return this element for chaining. */ touchmove(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, TouchEvent>): this; /** * Adds an event handler for the touchstart event to this element. * @param handler Handler for the event. * @return this element for chaining. */ touchstart(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, TouchEvent>): this; /** * Returns the current transformation of this element. This transformation is separate to other attributes, i.e. * translation does not change x or y of the rectangle. The format of transformation string is similar to the * path string syntax: * * ``` * "t100,100r30,100,100s2,2,100,100r45s1.5" * ``` * * Each letter is a command. There are four commands: * - `t` is for translate * - `r` is for rotate, * - `s` is for scale * - `m` is for matrix. * * So, the example line above could be read like * * ``` * translate by 100, 100; * rotate 30° around 100, 100; * scale twice around 100, 100; * rotate 45° around centre; * scale 1.5 times relative to centre * ``` * * As you can see rotate and scale commands have origin coordinates as optional parameters, the default is the * centre point of the element. Matrix accepts six parameters. * * ```javascript * // to get current value call it without parameters * console.log(el.transform()); * ``` * * @return The current transformation of this element. */ transform(): string; /** * Adds transformation to this element which is separate to other attributes, i.e. translation does not change x * or y of the rectangle. The format of transformation string is similar to the path string syntax: * * ``` * "t100,100r30,100,100s2,2,100,100r45s1.5" * ``` * * Each letter is a command. There are four commands: * - `t` is for translate * - `r` is for rotate, * - `s` is for scale * - `m` is for matrix. * * So, the example line above could be read like * * ``` * translate by 100, 100; * rotate 30° around 100, 100; * scale twice around 100, 100; * rotate 45° around centre; * scale 1.5 times relative to centre * ``` * * As you can see rotate and scale commands have origin coordinates as optional parameters, the default is the * centre point of the element. Matrix accepts six parameters. * * ```javascript * var el = paper.rect(10, 20, 300, 200); * * // translate 100, 100, rotate 45°, translate -100, 0 * el.transform("t100,100r45t-100,0"); * * // if you want you can append or prepend transformations * el.transform("...t50,50"); * el.transform("s2..."); * * // or even wrap * el.transform("t50,50...t-50-50"); * * // to reset transformation call method with empty string * el.transform(""); * ``` * * @param A transform string by which to transform this element. * @return this element for chaining. */ transform(transformString: string): this; /** * Translates this element by the given amount. * @param deltaX Amount by which to translate in the horizontal direction. * @param deltaY Amount by which to translate in the vertical direction. * @return this element for chaining. */ translate(deltaX: number, deltaY: number): this; /** * Removes an event handler for the click event from this element. See {@link click}. * @param handler A handler to remove. * @return this element for chaining. */ unclick(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, MouseEvent>): this; /** * Removes an event handler for the double click event from this element. See {@link dblclick}. * @param handler A handler to remove. * @return this element for chaining. */ undblclick(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, MouseEvent>): this; /** * Removes all drag event handlers from this element. * @return this element for chaining. */ undrag(): this; /** * Removes the event handlers for the hover event from this element. See {@link hover}. * @param onHoverInHandler Hover-in handler to remove. * @param onHoverOutHandler Hover-out handler to remove. * @return this element for chaining. */ unhover( onHoverInHandler: RaphaelBasicEventHandler<any, MouseEvent>, onHoverOutHandler: RaphaelBasicEventHandler<any, MouseEvent>, ): this; /** * Removes an event handler for the mousedown event from this element. See {@link mousedown}. * @param handler A handler to remove. * @return this element for chaining. */ unmousedown(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, MouseEvent>): this; /** * Removes an event handler for the mousemove event from this element. See {@link mousemove}. * @param handler A handler to remove. * @return this element for chaining. */ unmousemove(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, MouseEvent>): this; /** * Removes an event handler for the mouseout event from this element. See {@link mouseout}. * @param handler A handler to remove. * @return this element for chaining. */ unmouseout(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, MouseEvent>): this; /** * Removes an event handler for the mouseover event from this element. See {@link mouseover}. * @param handler A handler to remove. * @return this element for chaining. */ unmouseover(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, MouseEvent>): this; /** * Removes an event handler for the mouseup event from this element. See {@link mouseup}. * @param handler A handler to remove. * @return this element for chaining. */ unmouseup(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, MouseEvent>): this; /** * Removes an event handler for the touchcancel event from this element. See {@link touchcancel}. * @param handler A handler to remove. * @return this element for chaining. */ untouchcancel(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, TouchEvent>): this; /** * Removes an event handler for the touchend event from this element. See {@link touchend}. * @param handler A handler to remove. * @return this element for chaining. */ untouchend(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, TouchEvent>): this; /** * Removes an event handler for the touchmove event from this element. See {@link touchmove}. * @param handler A handler to remove. * @return this element for chaining. */ untouchmove(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, TouchEvent>): this; /** * Removes an event handler for the touchstart event from this element. See {@link touchstart}. * @param handler A handler to remove. * @return this element for chaining. */ untouchstart(handler: RaphaelBasicEventHandler<RaphaelUnwrapElement<TTechnology, this>, TouchEvent>): this; } /** * Abstracts the elements that can be created by Raphaël, such as circles, rectangles, and paths. * * Elements are implemented either via SVG or VML, see {@link RaphaelTechnology}. * * @typeparam TTechnology Type of the technology used by this paper, either `SVG` or `VML`. * @typeparam TNode Type of the native DOM element used by this element, such as {@link SVGRectElement}. */ export interface RaphaelElement< TTechnology extends RaphaelTechnology = "SVG" | "VML", TNode extends RaphaelElementByTechnologyMap[TTechnology] = RaphaelElementByTechnologyMap[TTechnology] > extends RaphaelBaseElement<TTechnology> { /** * Unique id of the element. Especially useful when you want to listen to events of the element, because all * events are fired in format `<module>.<action>.<id>`. Also useful for the {@link RaphaelPaper.getById} method. */ id: number; /** Reference to the next element in the hierarchy. */ next: RaphaelElement<TTechnology> | null; /** * Gives you a reference to the DOM object, so you can assign event handlers or just mess around. * * Note: __Don’t mess with it.__ */ node: TNode; /** Internal reference to paper where object drawn. Mainly for use in plugins and element extensions. */ paper: RaphaelPaper<TTechnology>; /** Reference to the previous element in the hierarchy. */ prev: RaphaelElement<TTechnology> | null; /** Internal reference to Raphaël object, in case it is not available. */ raphael: RaphaelStatic | undefined; /** The type of this element, e.g. `circle` or `path`. */ type: RaphaelShapeType | string; } /** * Represents a specific type of {@link RaphaelElement}, a path element. This element has got some additional * methods. * @typeparam TTechnology The target {@link RaphaelTechnology}. */ export interface RaphaelPath< TTechnology extends RaphaelTechnology = "SVG" | "VML" > extends RaphaelElement<TTechnology, RaphaelElementImplementationMap["path"][TTechnology]> { /** * The type of this element, i.e. `path`. */ type: "path"; /** * Finds the coordinates of the point located at the given length on this path. * @param length Length at which to get the point. * @return The point located at the given length on this path. */ getPointAtLength(length: number): RaphaelCartesianCurvePoint; /** * Return a sub path of this path from the given length to the given length. * @param from Position of the start of the segment. * @param to Position of the end of the segment * @return An SVG path string for the segment. */ getSubpath(from: number, to: number): string; /** * Finds the total length of this path. * @return The length of this path in pixels */ getTotalLength(): number; } /** * A set represents a collection of {@link RaphaelElement}s in a fixed order. * @typeparam TTechnology Type of the technology used by this paper, either `SVG` or `VML`. */ export interface RaphaelSet< TTechnology extends RaphaelTechnology = "SVG" | "VML" > extends ArrayLike<RaphaelElement<TTechnology>>, RaphaelBaseElement<TTechnology> { /** * Removes all elements from the set */ clear(): void; /** * Removes given element from the set * @param element An element to remove from the set. * @return `true` if object was found and removed from the set */ exclude(element: RaphaelElement<TTechnology>): boolean; /** * Executes given function for each element in the set. * * If callback function returns `false` it will stop the loop running. * * @typeparam ThisContext Type of the this context for the callback. * @param callback Callback that is invoked with each element in this set. * @param thisContext Optional this context that is passed to the callback. * @return this set for chaining. */ forEach<ThisContext = Window>( callback: (this: ThisContext, element: RaphaelElement<TTechnology>) => boolean | void, thisArg?: ThisContext ): this; /** * Removes last element and returns it. * @return The last element in this set, if any. */ pop(): RaphaelElement<TTechnology> | undefined; /** * Adds each argument to the current set. * @return this set for chaining. */ push(...elements: Array<RaphaelElement<TTechnology>>): this; /** * Removes given element from the set. * @param index Position of the deletion * @param count Number of element to remove * @param elementsToAdd Elements to insert at the given position. * @return The set elements that were deleted. */ splice(index: number, count: number, ...elementsToAdd: Array<RaphaelElement<TTechnology>>): RaphaelSet<TTechnology>; } /** * Represents a 2x3 matrix for affine transformations in homogenous coordinates. This allows for translations as * well as rotations, scaling, and shearing. * * The six components a-f of a matrix are arranged like this: * * ``` * +---+---+---+ * | a | c | e | * | b | d | f | * +---+---+---+ * ``` */ export interface RaphaelMatrix { /** * The matrix component at the first row, first column. */ a: number; /** * The matrix component at the second row, first column. */ b: number; /** * The matrix component at the first row, second column. */ c: number; /** * The matrix component at the second row, second column. */ d: number; /** * The matrix component at the third row, first column. */ e: number; /** * The matrix component at the third row, second column. */ f: number; /** * Adds the given matrix to this matrix component-wise. * * The parameters a-f form a 2x3 matrix and are arranged like this. * * ``` * +---+---+---+ * | a | c | e | * | b | d | f | * +---+---+---+ * ``` * * @param a The matrix component at the first row, first column. * @param b The matrix component at the second row, first column. * @param c The matrix component at the first row, second column. * @param d The matrix component at the second row, second column. * @param e The matrix component at the third row, first column. * @param f The matrix component at the third row, second column. */ add(a: number, b: number, c: number, d: number, e: number, f: number): void; /** * Creates a copy of this matrix and returns it. * @return A new matrix that is equal to this matrix. */ clone(): RaphaelMatrix; /** * Creates a new matrix that represents the inverse affine transformation of this matrix. * @return A new matrix that represents the inverse affine transformation of this matrix. */ invert(): RaphaelMatrix; /** * Applies a rotation to this matrix. * @param a The angle of the rotation, in degrees. * @param x Horizontal coordinate of the origin of the rotation. * @param y Vertical coordinate of the origin of the rotation. */ rotate(a: number, x: number, y: number): void; /** * Applies a scaling operation to this matrix. * @param x Horizontal coordinate of the origin of the scaling. * @param y Vertical coordinate of the origin of the scaling. If not specified, default to same value as `x`. */ scale(x: number, y?: number): void; /** * Applies a scaling operation to this matrix. * @param x Horizontal coordinate of the origin of the scaling. * @param y Vertical coordinate of the origin of the scaling. * @param cx Amount by which to scale in the horizontal direction. * @param cy Amount by which to scale in the vertical direction. */ scale(x: number, y: number, cx: number, cy: number): void; /** * Splits matrix into primitive transformations. * @return Information regarding how this matrix can be produced by applying a chain of primitive transformations. */ split(): RaphaelMatrixTransformInfo; /** * Creates a transform string that represents given matrix, such as `t0,0s1,1,0,0r0,0,0`. * @return A CSS transform string that represents given matrix. */ toTransformString(): string; /** * Applies a translation to this matrix. * @param dx Amount by which to translate in the horizontal direction. * @param dy Amount by which to translate in the vertical direction. */ translate(x: number, y: number): void; /** * Applies this transformation matrix to the given point and returns the x coordinate of that transformed point. * See also {@link y}. * @param x Horizontal coordinate of a point to transform. * @param y Vertical coordinate of a point to transform. */ x(x: number, y: number): number; /** * Applies this transformation matrix to the given point and returns the y coordinate of that transformed point. * See also {@link x}. * @param x Horizontal coordinate of a point to transform. * @param y Vertical coordinate of a point to transform. */ y(x: number, y: number): number; } /** * Interface for a paper that may be implemented either via VML or SVG, see {@link RaphaelTechnology}. * * The paper that represents a drawing surface, implemented via SVG. * * You can use the paper to draw shapes such as circles or paths. * * @typeparam TTechnology Type of the technology used by this paper, either `SVG` or `VML`. */ export interface RaphaelPaper< TTechnology extends RaphaelTechnology = "SVG" | "VML", > { /** * Points to the bottom element on the paper. `null` when there is no element. */ bottom: RaphaelElement<TTechnology> | null; /** * The SVG element used by this paper. */ canvas: RaphaelElementByTechnologyMap[TTechnology]; /** * Draws a circle. * @param x x coordinate of the center. * @param y y coordinate of the center. * @param radius Radius of the circle. * @return The newly created element representing the circle. */ circle(x: number, y: number, radius: number): RaphaelElement<TTechnology, RaphaelElementImplementationMap["circle"][TTechnology]>; /** * Clears the paper, i.e. removes all the elements. */ clear(): void; /** * If you have a set of attributes that you would like to represent as a function of some number you can do it * easily with custom attributes: * * ```javascript * paper.customAttributes.hue = function (num) { * num = num % 1; * return {fill: "hsb(" + num + ", .75, 1)"}; * }; * * // Custom attribute "hue" will change fill * // to be given hue with fixed saturation and brightness. * // Now you can use it like this: * var c = paper.circle(10, 10, 10).attr({hue: .45}); * // or even like this: * c.animate({hue: 1}, 1e3); * * // You could also create custom attribute * // with multiple parameters: * paper.customAttributes.hsb = function (h, s, b) { * return {fill: "hsb(" + [h, s, b].join(",") + ")"}; * }; * c.attr({hsb: ".5 .8 1"}); * c.animate({hsb: "1 0 .5"}, 1e3); * ``` * * __Note to TypeScript users__ * * To declare your plugin, you should extend the `raphael` module and add to the {@link RaphaelAttributes}: * * ```typescript * import { RaphaelAttributes } from "raphael" * declare module "raphael" { * interface RaphaelAttributes { * hue: number; * hsb: string; * } * } * ``` */ customAttributes: Record<keyof RaphaelAttributes, RaphaelCustomAttribute<TTechnology>>; /** * Draws an ellipse. * @param x x coordinate of the center. * @param y y coordinate of the center. * @param radiusX Horizontal half-axis of the ellipse. * @param radiusY Vertical half-axis of the ellipse. * @return The newly created element representing the ellipse. */ ellipse(x: number, y: number, radiusX: number, radiusY: number): RaphaelElement<TTechnology, RaphaelElementImplementationMap["ellipse"][TTechnology]>; /** * Executes given function for each element on the paper * * If callback function returns `false` it will stop the loop running. * @typeparam Type of the this context for the callback. * @param callback Callback that is invoked with each element on the paper. * @param thisContext Optional this context that is passed to the callback. * @return this paper for chaining. */ forEach<T = Window>(callback: (this: T, element: RaphaelElement<TTechnology>) => boolean | void, thisContext?: T): this; /** * Returns an element by its internal ID. * @param id ID of an element to fetch. * @return The element with the given ID, or `null` if no such element exists. */ getById(id: number): RaphaelElement<TTechnology> | null; /** * Return the topmost element at given point. * * ```javascript * paper.getElementByPoint(mouseX, mouseY).attr({stroke: "#f00"}); * ``` * * @param x x coordinate from the top left corner of the window. * @param y y coordinate from the top left corner of the window. * @return The topmost element at given point, `null` if no such element exists.. */ getElementByPoint(x: number, y: number): RaphaelElement<TTechnology> | null; /** * Finds font object in the registered fonts by given parameters. You could specify only one word from the font * name, like `Myriad` for `Myriad Pr`. * * ```javascript * paper.print(100, 100, "Test string", paper.getFont("Times", 800), 30); * ``` * * @param family Font family name or any word from it * @param weight Font weight * @param style Font style * @param stretch Font stretch * @return The font object with the given options, or `undefined` if no such font exists. */ getFont(family: string, weight?: string | number, style?: string, stretch?: string): RaphaelFont | undefined; /** * The height of this pager. */ height: number; /** * Embeds an image into this paper. * * ```javascript * var c = paper.image("apple.png", 10, 10, 80, 80); * ``` * * @param src URI of the source image. * @param x x coordinate position * @param y y coordinate position * @param width Width of the image * @param height Height of the image * @return The newly created element representing the image. */ image(src: string, x: number, y: number, width: number, height: number): RaphaelElement<TTechnology, RaphaelElementImplementationMap["image"][TTechnology]>; /** * Creates a path element by given path data string. * * Path string consists of one-letter commands, followed by comma separated arguments in numerical form: * * ``` * "M10,20L30,40" * ``` * * For example: * * ```javascript * var c = paper.path("M10 10L90 90"); * // draw a diagonal line: * // move to 10,10, line to 90,90 * ``` * * @param pathString Path string in SVG format. * @return The newly created element representing the path. */ path(pathString?: string | RaphaelPathSegment | ReadonlyArray<RaphaelPathSegment>): RaphaelPath<TTechnology>; /** * Creates set of shapes to represent given font at given position with given size. Result of the method is set * object (see {@link set}) which contains each letter as separate path object. * * ```javascript * var txt = r.print(10, 50, "print", r.getFont("Arial"), 30).attr({fill: "#fff"}); * // following line will paint first letter in red * txt[0].attr({fill: "#f00"}); * ``` * * @param x x Position of the text * @param y y Position of the text * @param str Text to print * @param font Font object, see {@link getFont}. * @param size Size of the font, default is 16. * @param origin Whether the text is centered on the baseline or middle line. * @param letterSpacing Number between `-1` and `1`, default is `0`. * @return Each letter as separate {@link RaphaelPath|path object}. */ print(x: number, y: number, str: string, font: RaphaelFont, size?: number, origin?: RaphaelFontOrigin, letterSpacing?: number): RaphaelSet<TTechnology>; /** * Points to the {@link RaphaelStatic|Raphael} object/function. */ raphael: RaphaelStatic<TTechnology>; /** * Draws a rectangle. * @param x x coordinate of the top left corner. * @param y y coordinate of the top left corner * @param width Width of th rectangle. * @param height Height of th rectangle. * @param r Radius for rounded corners, default is `0`. * @return The newly created element representing the rectangle. */ rect(x: number, y: number, width: number, height: number, r?: number): RaphaelElement<TTechnology, RaphaelElementImplementationMap["rect"][TTechnology]>; /** * Removes this paper from the DOM. */ remove(): void; /** * Fixes the issue of Firefox and IE9 regarding subpixel rendering. If paper is dependant on other elements * after reflow it could shift half pixel which cause for lines to lost their crispness. This method fixes the * issue. */ renderfix(): void; /** * There is an inconvenient rendering bug in Safari (WebKit): sometimes the rendering should be forced. This * method should help with dealing with this bug. */ safari(): void; /** * Creates array-like object to keep and operate several elements at once. Warning: it doesn't create any * elements for itself in the page, it just groups existing elements. Sets act as pseudo elements - all methods * available to an element can be used on a set. * @param elements Elements to add to the set. * @return A newly created set with the given elements. */ set(elements: Array<RaphaelElement<TTechnology>>): RaphaelSet<TTechnology>; /** * Creates array-like object to keep and operate several elements at once. Warning: it doesn't create any * elements for itself in the page, it just groups existing elements. Sets act as pseudo elements - all methods * available to an element can be used on a set. * * ```javascript * var st = paper.set(); * st.push( * paper.circle(10, 10, 5), * paper.circle(30, 10, 5) * ); * st.attr({fill: "red"}); // changes the fill of both circles * ``` * * @param elements Elements to add to the set. * @return A newly created set with the given elements. */ set(...elements: Array<RaphaelElement<TTechnology>>): RaphaelSet<TTechnology>; /** * See {@link setStart}. This method finishes catching elements and returns the resulting set. * @return A set with all the elements added to this paper since {@link setStart} was called. */ setFinish(): RaphaelSet<TTechnology>; /** * If you need to change dimensions of the canvas, call this method. * @param width New width of the canvas. * @param height New height of the canvas. * @return this paper for chaining. */ setSize(width: number, height: number): this; /** * Creates a {@link set}. All elements that will be created after calling this method and before calling * {@link setFinish} will be added to the set. * * ```javascript * paper.setStart(); * paper.circle(10, 10, 5), * paper.circle(30, 10, 5) * var st = paper.setFinish(); * st.attr({fill: "red"}); // changes the fill of both circles * ``` */ setStart(): void; /** * Sets the view box of the paper. Practically it gives you ability to zoom and pan whole paper surface by * specifying new boundaries. * @param x New x position, default is `0`. * @param y New y position, default is `0`. * @param w New width of the canvas. * @param h New height of the canvas. * @param fit `true` if you want graphics to fit into new boundary box * @return this paper for chaining. */ setViewBox(x: number, y: number, w: number, h: number, fit?: boolean): this; /** * Draws a text string. If you need line breaks, put `\n` in the string. * @param x x coordinate position. * @param y y coordinate position. * @param text The text string to draw. * @return The newly created element representing the drawn text. */ text(x: number, y: number, text: string): RaphaelElement<TTechnology, RaphaelElementImplementationMap["text"][TTechnology]>; /** * Points to the topmost element on the paper. `null` when there is no element. */ top: RaphaelElement<TTechnology> | null; /** * The width of this paper. */ width: number; } /** * Describes a shape that can be created on the canvas. */ export interface RaphaelShapeDescriptor extends Partial<RaphaelAttributes> { /** Type of the shape, e.g. `circle` or `rect`. Could also be a custom plugin shape. */ type: RaphaelShapeType | string; } /** * Represents the type of the {@link RaphaelStatic.getColor} property. It is both callable and has got an additional * property with a utility method. */ export interface RaphaelStaticGetColor { /** * On each call returns next colour in the spectrum. To reset it back to red call * {@link RaphaelStaticGetColor.reset|Raphael.getColor.reset}. * @param Brightness, default is `0.75`. * @return Hex representation of the color. */ (brightness?: number): string; /** * Resets spectrum position for {@link RaphaelStaticGetColor|Raphael.getColor} back to red. */ reset(): void; } /** * Interface for the main object exported by the Raphaël library. * * Raphaël is a small JavaScript library that should simplify your work with vector graphics on the web. If you want to * create your own specific chart or image crop and rotate widget, for example, you can achieve it simply and easily * with this library. * * You use this library via the globally available {@link RaphaelStatic|Raphael} object: * * ```javascript * // Creates canvas 320 × 200 at 10, 50 * var paper = Raphael(10, 50, 320, 200); * * // Creates circle at x = 50, y = 40, with radius 10 * var circle = paper.circle(50, 40, 10); * * // Sets the fill attribute of the circle to red (#f00) * circle.attr("fill", "#f00"); * * // Sets the stroke attribute of the circle to white * circle.attr("stroke", "#fff"); * ``` * * See https://dmitrybaranovskiy.github.io/raphael/ * * @typeparam TTechnology The target {@link RaphaelTechnology}. */ export interface RaphaelStatic< TTechnology extends RaphaelTechnology = "SVG" | "VML" > { /** * Creates a canvas object on which to draw. You must do this first, as all future calls to drawing methods * from this instance will be bound to this canvas. * * @param container DOM element or its ID which is going to be a parent for drawing surface. * @param width Width for the canvas. * @param height Height for the canvas. * @param callback Callback function which is going to be executed in the context of newly created paper. * @return A new raphael paper that can be used for drawing shapes to the canvas. */ (container: HTMLElement | string, width: number, height: number, callback?: (this: RaphaelPaper<TTechnology>) => void): RaphaelPaper<TTechnology>; /** * Creates a canvas object on which to draw. You must do this first, as all future calls to drawing methods * from this instance will be bound to this canvas. * * @param x x coordinate of the viewport where the canvas is created. * @param y y coordinate of the viewport where the canvas is created. * @param width Width for the canvas. * @param height Height for the canvas. * @param callback Callback function which is going to be executed in the context of newly created paper. * @return A new raphael paper that can be used for drawing shapes to the canvas. */ (x: number, y: number, width: number, height: number, callback?: (this: RaphaelPaper<TTechnology>) => void): RaphaelPaper<TTechnology>; /** * Creates a canvas object on which to draw. You must do this first, as all future calls to drawing methods * from this instance will be bound to this canvas. * * @param The first 3 or 4 elements in the array are equal to `[containerID, width, height]` or * `[x, y, width, height]`. The rest are element descriptions in format `{type: type, <attributes>}`. * @param callback Callback function which is going to be executed in the context of newly created paper. * @return A new raphael paper that can be used for drawing shapes to the canvas. */ (all: RaphaelConstructionOptionsArray4 | RaphaelConstructionOptionsArray5, callback?: (this: RaphaelPaper<TTechnology>) => void): RaphaelSet<TTechnology>; /** * @param onReadyCallback Function that is going to be called on DOM ready event. You can also subscribe to this * event via Eve's `DOMLoad` event. In this case the method returns `undefined`. * @return A new raphael paper that can be used for drawing shapes to the canvas. */ (onReadyCallback?: (this: Window) => void): RaphaelPaper<TTechnology>; /** * Creates a canvas object on which to draw. You must do this first, as all future calls to drawing methods * from this instance will be bound to this canvas. * * @param container DOM element or its ID which is going to be a parent for drawing surface. * @param width Width for the canvas. * @param height Height for the canvas. * @param callback Callback function which is going to be executed in the context of newly created paper. * @return A new raphael paper that can be used for drawing shapes to the canvas. */ new(container: HTMLElement | string, width: number, height: number, callback?: (this: RaphaelPaper<TTechnology>) => void): RaphaelPaper<TTechnology>; /** * Creates a canvas object on which to draw. You must do this first, as all future calls to drawing methods * from this instance will be bound to this canvas. * * @param x x coordinate of the viewport where the canvas is created. * @param y y coordinate of the viewport where the canvas is created. * @param width Width for the canvas. * @param height Height for the canvas. * @param callback Callback function which is going to be executed in the context of newly created paper. * @return A new raphael paper that can be used for drawing shapes to the canvas. */ new(x: number, y: number, width: number, height: number, callback?: (this: RaphaelPaper<TTechnology>) => void): RaphaelPaper<TTechnology>; /** * Creates a canvas object on which to draw. You must do this first, as all future calls to drawing methods * from this instance will be bound to this canvas. * * @param The first 3 or 4 elements in the array are equal to `[containerID, width, height]` or * `[x, y, width, height]`. The rest are element descriptions in format `{type: type, <attributes>}`. * @param callback Callback function which is going to be executed in the context of newly created paper. * @return A new raphael paper that can be used for drawing shapes to the canvas. */ new(all: RaphaelConstructionOptionsArray4 | RaphaelConstructionOptionsArray5, callback?: (this: RaphaelPaper<TTechnology>) => void): RaphaelSet<TTechnology>; /** * @param onReadyCallback Function that is going to be called on DOM ready event. You can also subscribe to this * event via Eve's `DOMLoad` event. In this case the method returns `undefined`. * @return A new raphael paper that can be used for drawing shapes to the canvas. */ new(onReadyCallback?: (this: Window) => void): RaphaelPaper<TTechnology>; /** * Returns angle between two or three points * @param x1 x coordinate of first point * @param y1 y coordinate of first point * @param x2 x coordinate of second point * @param y2 y coordinate of second point * @param x3 x coordinate of third point * @param y3 y coordinate of third point * @return The angle in degrees. */ angle(x1: number, y1: number, x2: number, y2: number, x3?: number, y3?: number): number; /** * Creates an animation object that can be passed to the {@link RaphaelElement.animate} or * {@link RaphaelElement.animateWith} methods. See also the {@link RaphaelAnimation.delay} and * {@link RaphaelAnimation.repeat} methods. * @param params * @param milliseconds Number of milliseconds for animation to run * @param easing easing type. Accept one of {@link RaphaelStatic.easing_formulas} or CSS format: * `cubic‐bezier(XX, XX, XX, XX)` * @param callback Callback function. Will be called at the end of animation. */ animation( params: Partial<RaphaelAttributes>, milliseconds: number, easing?: RaphaelBuiltinEasingFormula | RaphaelCustomEasingFormula, callback?: (this: RaphaelElement<TTechnology>) => void ): RaphaelAnimation; /** * Parses the color string and returns object with all values for the given color. * @param color Color string in one of the supported formats, see {@link RaphaelStatic.getRGB}. * @return Combined RGB & HSB object with the information about the color. */ color(color: string): RaphaelPotentialFailure<RaphaelFullComponentInfo>; /** * Transform angle from radians to degrees. * @param radians An angle in radians. * @return The given angle in degrees. */ deg(radians: number): number; /** * Object that contains easing formulas for animation. You could extend it with your own. By default it has * the easing methods as defined in {@link RaphaelBuiltinEasingFormula}. */ easing_formulas: Record<RaphaelBuiltinEasingFormula | RaphaelCustomEasingFormula, RaphaelEasingFormula>; /** * You can add your own method to elements. This is useful when you want to hack default functionality or want * to wrap some common transformation or attributes in one method. In contrast to canvas methods, you can * redefine element method at any time. Expending element methods would not affect set. * * ```javascript * Raphael.el.red = function () { * this.attr({fill: "#f00"}); * }; * // then use it * paper.circle(100, 100, 20).red(); * ``` * * __Note to TypeScript users__ * * To declare your plugin, you should extend the `raphael` module and add to the {@link RaphaelElement}: * * ```typescript * import { RaphaelElement } from "raphael" * declare module "raphael" { * interface RaphaelElement { * red(): void; * colored(r: number, g: number, b: number): this; * } * } * ``` */ el: RaphaelElementPluginRegistry<TTechnology>; /** * Utility method to find dot coordinates on the given cubic bezier curve at the given position. * @param startPointX x of the first point of the curve. * @param startPointY y of the first point of the curve. * @param anchor1X x of the first anchor of the curve. * @param anchor1Y y of the first anchor of the curve. * @param anchor2X x of the second anchor of the curve. * @param anchor2Y y of the second anchor of the curve. * @param endPointX x of the second point of the curve. * @param endPointY y of the second point of the curve. * @param positionOnCurve Position on the curve, between `0` and `1`. * @return The point at the specified cubic bezier curve at the given position. */ findDotsAtSegment( startPointX: number, startPointY: number, anchor1X: number, anchor1Y: number, anchor2X: number, anchor2Y: number, endPointX: number, endPointY: number, positionOnCurve: number ): RaphaelCubicBezierCurvePointInfo; /** * You can add your own method to the canvas. For example if you want to draw a pie chart, you can create your * own pie chart function and ship it as a Raphaël plugin. To do this you need to extend the `Raphael.fn` * object. * * Please note that you can create your own namespaces inside the fn object, methods will be run in the context * of the canvas. You should alter the fn object before a Raphaël instance is created, otherwise it will take no * effect. * * ```javascript * Raphael.fn.arrow = function (x1, y1, x2, y2, size) { * return this.path( ... ); * }; * // or create namespace * Raphael.fn.mystuff = { * arrow: function () {…}, * star: function () {…}, * // etc... * }; * * var paper = Raphael(10, 10, 630, 480); * // then use it * paper.arrow(10, 10, 30, 30, 5).attr({fill: "#f00"}); * paper.mystuff.arrow(); * paper.mystuff.star(); * ``` * * __Note to TypeScript users__ * * To declare your plugin, you should extend the `raphael` module and add to the {@link RaphaelPaper}: * * ```typescript * import { RaphaelPaper, RaphaelPath } from "raphael" * declare module "raphael" { * interface RaphaelPaper { * arrow(x1: number, y1: number, x2: number, y2: number, size: number): RaphaelPath; * mystuff: { * arrow(flag: boolean): number; * star(): void; * }; * } * } * ``` */ fn: RaphaelPaperPluginRegistry<TTechnology>; /** * Simple format function. Replaces construction of type `{<number>}` with the corresponding argument. * * ```javascript * var x = 10; * var y = 20; * var width = 40; * var height = 50; * * // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z" * paper.path(Raphael.format("M{1},{2}h{3}v{4}h{5}z", x, y, width, height, -width)); * ``` * * See also {@link format}. * * @param token String to format. * @param parameters Arguments that will be treated as parameters for replacement. They will be coerced to type * `string`. * @return The formatted string. */ format(token: string, ...parameters: any[]): string; /** * A little bit more advanced format function than {@link format}. Replaces construction of type `{<name>}` * with the corresponding argument. * * ```javascript * // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z" * paper.path(Raphael.format("M{x},{y}h{dim.width}v{dim.height}h{dim['negative width']}z", { * x: 10, * y: 20, * dim: { * width: 40, * height: 50, * "negative width": -40 * } * })); * ``` * * @param token String to format. * @param json Object with properties that will be used as a replacement. * @return The formatted string. */ fullfill(token: string, json: Record<string, any>): string; /** * On each call returns next colour in the spectrum. Also contains a utility method to reset it back to red via * {@link RaphaelStaticGetColor.reset|Raphael.getColor.reset} */ getColor: RaphaelStaticGetColor; /** * Return coordinates of the point located at the given length on the given path. * @param path SVG path string. * @param length Length at which to get the point. * @return The point located at the given length on the given path. */ getPointAtLength(path: string, length: number): RaphaelCartesianCurvePoint; /** * Parses a color string as an RGB object. Takes a color string in one of the following formats: * * - Colour name (`red`, `green`, `cornflowerblue`, etc) * - `#RGB` - shortened HTML colour: (`#000`, `#fc0`, etc) * - `#RRGGBB` - full length HTML colour: (`#000000`, `#bd2300`) * - `rgb(RRR, GGG, BBB)` - red, green and blue channels' values: (`rgb(200, 100, 0)`) * - `rgb(RRR%, GGG%, BBB%)` - same as above, but in %: (`rgb(100%, 175%, 0%)`) * - `hsb(HHH, SSS, BBB)` - hue, saturation and brightness values: (`hsb(0.5, 0.25, 1)`) * - `hsb(HHH%, SSS%, BBB%)` - same as above, but in % * - `hsl(HHH, SSS, LLL)` - same as hsb * - `hsl(HHH%, SSS%, LLL%)` - same as hsb * * @param color Color string to be parsed. * @return The RGB components of the parsed color string. */ getRGB(color: string): RaphaelPotentialFailure<RaphaelRgbComponentInfo>; /** * Return sub path of a given path from given length to given length. * @param path SVG path string * @param from Position of the start of the segment * @param to Position of the end of the segment * @return Path string for the segment. */ getSubpath(path: string, from: number, to: number): string; /** * Returns length of the given path in pixels. * @param path SVG path string. * @return The length of the path. */ getTotalLength(path: string): number; /** * Converts HSB values to hex representation of the color. * @param hue Hue channel * @param saturation Saturation channel. * @param brightness Brightness channel. * @return Hex representation of the color. */ hsb(hue: number, saturation: number, brightness: number): string; /** * Converts HSB values to RGB object. * @param hue Hue channel. * @param saturation Saturation channel. * @param brightness Brightness channel. * @return The color in the RGB color system. */ hsb2rgb(hue: number, saturation: number, brightness: number): RaphaelRgbComponentInfo; /** * Converts HSL values to hex representation of the colour. * @param hue Hue channel. * @param saturation Saturation channel. * @param luminosity Luminosity channel. * @return Hex representation of the color. */ hsl(hue: number, saturation: number, luminosity: number): string; /** * Converts HSL values to RGB object. * @param hue Hue channel. * @param saturation Saturation channel. * @param luminosity Luminosity channel. * @return The color in the RGB color system. */ hsl2rgb(hue: number, saturation: number, luminosity: number): RaphaelRgbComponentInfo; /** * Handy replacement for typeof operator. * @param object An object whose type to check. * @param type Type to check. * @return `true` if the object is of the given type, or `false` otherwise. */ is(object: any, type: "undefined"): object is undefined; /** * Handy replacement for typeof operator. * @param object An object whose type to check. * @param type Type to check. * @return `true` if the object is of the given type, or `false` otherwise. */ is(object: any, type: "null"): object is null; /** * Handy replacement for typeof operator. * @param object An object whose type to check. * @param type Type to check. * @return `true` if the object is of the given type, or `false` otherwise. */ is(object: any, type: "boolean"): object is boolean; /** * Handy replacement for typeof operator. * @param object An object whose type to check. * @param type Type to check. * @return `true` if the object is of the given type, or `false` otherwise. */ is(object: any, type: "number"): object is number; /** * Handy replacement for typeof operator. * @param object An object whose type to check. * @param type Type to check. * @return `true` if the object is of the given type, or `false` otherwise. */ is(object: any, type: "symbol"): object is symbol; /** * Handy replacement for typeof operator. * @param object An object whose type to check. * @param type Type to check. * @return `true` if the object is of the given type, or `false` otherwise. */ is(object: any, type: "string"): object is string; /** * Handy replacement for typeof operator. * @param object An object whose type to check. * @param type Type to check. * @return `true` if the object is of the given type, or `false` otherwise. */ is(object: any, type: "object"): object is object | null; /** * Handy replacement for typeof operator. * @param object An object whose type to check. * @param type Type to check. * @return `true` if the object is of the given type, or `false` otherwise. */ is(object: any, type: "function"): object is (...args: any[]) => any; /** * Handy replacement for typeof operator. * @param object An object whose type to check. * @param type Type to check. * @return `true` if the object is of the given type, or `false` otherwise. */ is(object: any, type: "array"): object is any[]; /** * Handy replacement for typeof operator. * @param object An object whose type to check. * @param type Type to check for. * @return `true` if the object is of the given type, or `false` otherwise. */ is(object: any, type: string): boolean; /** * Utility method for creating a 2x3 matrix based on given parameters: * * ``` * +---+---+---+ * | a | c | e | * | b | d | f | * +---+---+---+ * ``` * * @param a The matrix component at the first row, first column. * @param b The matrix component at the second row, first column. * @param c The matrix component at the first row, second column. * @param d The matrix component at the second row, second column. * @param e The matrix component at the third row, first column. * @param f The matrix component at the third row, second column. * @return A matrix based on the given parameters. */ matrix(a: number, b: number, c: number, d: number, e: number, f: number): RaphaelMatrix; /** * If you want to leave no trace of Raphaël (Well, Raphaël creates only one global variable `Raphael`, but * anyway.) You can use ninja method. Beware, that in this case plugins could stop working, because they are * depending on the existence of the global variable. * @return The Raphael object with all available methods. */ ninja(): this; /** * Utility method that parses given path string into an array of arrays of path segments. * @param pathString Path string or array of segments (in the last case it will be returned straight away). * @return Array of path segments. */ parsePathString(pathString: string | RaphaelPathSegment | ReadonlyArray<RaphaelPathSegment>): RaphaelPathSegment[]; /** * Utility method that parses given path string into an array of transformations. * @param transformString Transform string or array of transformations (in the last case it will be returned * straight away). * @return Array of transformations. */ parseTransformString(transformString: string | RaphaelTransformSegment | ReadonlyArray<RaphaelTransformSegment>): RaphaelTransformSegment[]; /** * Utility method that converts path to a new path where all segments are cubic bezier curves. * @param pathString A path string or array of segments. * @return Array of path segments. */ path2curve(pathString: string | RaphaelPathSegment | ReadonlyArray<RaphaelPathSegment>): RaphaelPathSegment[]; /** * Utility method that converts a path to its relative form. * @param pathString A path string or array of segments. * @return Array of path segments. */ pathToRelative(pathString: string | RaphaelPathSegment | ReadonlyArray<RaphaelPathSegment>): RaphaelPathSegment[]; /** * Transform angle from degrees to radians. * @param degrees An angle in degrees. * @return The given angle in radians. */ rad(degrees: number): number; /** * Adds given font to the registered set of fonts for Raphaël. Should be used as an internal call from within * Cufón's font file. Returns original parameter, so it could be used with chaining. * * See http://wiki.github.com/sorccu/cufon/about * * @param font The font to register. * @return The font you passed in */ registerFont(font: RaphaelFont): RaphaelFont; /** * Converts RGB values to hex representation of the colour. * @param red The red channel. * @param green The green channel. * @param blue The blue channel. * @return Hex representation of the color. */ rgb(red: number, green: number, blue: number): string; /** * Converts RGB values to HSB values. * @param red The red channel. * @param green The green channel. * @param blue The blue channel. * @return The given color in the HSB color format. */ rgb2hsb(red: number, green: number, blue: number): RaphaelHsbComponentInfo; /** * Converts RGB values to HSB values. * @param red The red channel. * @param green The green channel. * @param blue The blue channel. * @return The given color in the HSL color format. */ rgb2hsl(red: number, green: number, blue: number): RaphaelHslComponentInfo; /** * Used when you need to draw in IFRAME. Switches window to the iframe one. * @param newWindow The new window object */ setWindow(newWindow: Window): void; /** * Snaps the given value to the given grid. * @param values Array of grid values or step of the grid. * @param value Value to adjust. * @param tolerance Tolerance for snapping. Default is `10`. * @return The adjusted value. */ snapTo(values: number | ReadonlyArray<number>, value: number, tolerance?: number): number; /** * Returns `true` if given point is inside the bounding box. * @param bbox bounding box * @param x x coordinate of the point * @param y y coordinate of the point * @return `true` if point the point is inside */ isPointInsideBBox(bbox: RaphaelAxisAlignedBoundingBox, x: number, y: number): boolean; /** * Returns `true` if two bounding boxes intersect * @param bbox1 first bounding box * @param bbox2 second bounding box * @return `true` if they intersect */ isBBoxIntersect(bbox1: RaphaelAxisAlignedBoundingBox, bbox2: RaphaelAxisAlignedBoundingBox): boolean; /** * You can add your own method to elements and sets. It is wise to add a set method for each element method you * added, so you will be able to call the same method on sets too. See also {@link el}. * * ```javascript * Raphael.el.red = function() { * this.attr({fill: "#f00"}); * }; * * Raphael.st.red = function() { * this.forEach(function () { * this.red(); * }); * }; * * // then use it * paper.set(paper.circle(100, 100, 20), paper.circle(110, 100, 20)).red(); * ``` * * __Note to TypeScript users__ * * To declare your plugin, you should extend the `raphael` module and add to the {@link RaphaelSet}: * * ```typescript * import { RaphaelSet } from "raphael" * declare module "raphael" { * interface RaphaelSet { * green(): void; * colorized(r: number, g: number, b: number): this; * } * } * ``` */ st: RaphaelSetPluginRegistry<TTechnology>; /** * `true` if browser supports SVG (scalable vector graphics), or `false` otherwise. */ svg: boolean; /** * The technology used by Raphaël for the graphics. */ type: TTechnology; /** * True if browser supports VML (vector markup language). */ vml: boolean; } declare const R: RaphaelStatic; export default R; declare global { /** * The global entry point for all features offered by the Raphaël library. * * Raphaël is a small JavaScript library that should simplify your work with vector graphics on the web. If you want * to create your own specific chart or image crop and rotate widget, for example, you can achieve it simply and * easily with this library. * * You use this library via the globally available {@link RaphaelStatic|Raphael} object: * * ```javascript * // Creates canvas 320 × 200 at 10, 50 * var paper = Raphael(10, 50, 320, 200); * * // Creates circle at x = 50, y = 40, with radius 10 * var circle = paper.circle(50, 40, 10); * * // Sets the fill attribute of the circle to red (#f00) * circle.attr("fill", "#f00"); * * // Sets the stroke attribute of the circle to white * circle.attr("stroke", "#fff"); * ``` * * See https://dmitrybaranovskiy.github.io/raphael/ */ const Raphael: RaphaelStatic; }
the_stack
import * as tape from 'tape'; import {MockEnvironment} from "../../../../../../../mock/environment"; import {MockLoader} from "../../../../../../../mock/loader"; import {escape} from "../../../../../../../../src/lib/extension/core/filters/escape"; import {TwingEnvironment} from "../../../../../../../../src/lib/environment"; import {MockTemplate} from "../../../../../../../mock/template"; function foo_escaper_for_test(env: TwingEnvironment, string: string, charset: string) { return (string ? string : '') + charset; } /** * All character encodings supported by htmlspecialchars(). */ let htmlSpecialChars: { [k: string]: string } = { '\'': '&#039;', '"': '&quot;', '<': '&lt;', '>': '&gt;', '&': '&amp;', }; let htmlAttrSpecialChars: { [k: string]: string } = { '\'': '&#x27;', /* Characters beyond ASCII value 255 to unicode escape */ 'Ā': '&#x0100;', '😀': '&#x1F600;', /* Immune chars excluded */ ',': ',', '.': '.', '-': '-', '_': '_', /* Basic alnums excluded */ 'a': 'a', 'A': 'A', 'z': 'z', 'Z': 'Z', '0': '0', '9': '9', /* Basic control characters and null */ "\r": '&#x0D;', "\n": '&#x0A;', "\t": '&#x09;', "\0": '&#xFFFD;', // should use Unicode replacement char /* Encode chars as named entities where possible */ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', /* Encode spaces for quoteless attribute protection */ ' ': '&#x20;', }; let jsSpecialChars: { [k: string]: string } = { /* HTML special chars - escape without exception to hex */ '<': '\\u003C', '>': '\\u003E', '\'': '\\u0027', '"': '\\u0022', '&': '\\u0026', '/': '\\/', /* Characters beyond ASCII value 255 to unicode escape */ 'Ā': '\\u0100', '😀': '\\uD83D\\uDE00', /* Immune chars excluded */ ',': ',', '.': '.', '_': '_', /* Basic alnums excluded */ 'a': 'a', 'A': 'A', 'z': 'z', 'Z': 'Z', '0': '0', '9': '9', /* Basic control characters and null */ "\r": '\\r', "\n": '\\n', "\x08": '\\b', "\t": '\\t', "\x0C": '\\f', "\0": '\\u0000', /* Encode spaces for quoteless attribute protection */ ' ': '\\u0020', }; let urlSpecialChars: { [k: string]: string } = { /* HTML special chars - escape without exception to percent encoding */ '<': '%3C', '>': '%3E', '\'': '%27', '"': '%22', '&': '%26', /* Characters beyond ASCII value 255 to hex sequence */ 'Ā': '%C4%80', /* Punctuation and unreserved check */ ',': '%2C', '.': '.', '_': '_', '-': '-', ':': '%3A', ';': '%3B', '!': '%21', /* Basic alnums excluded */ 'a': 'a', 'A': 'A', 'z': 'z', 'Z': 'Z', '0': '0', '9': '9', /* Basic control characters and null */ "\r": '%0D', "\n": '%0A', "\t": '%09', "\0": '%00', /* PHP quirks from the past */ ' ': '%20', '~': '~', '+': '%2B', }; let cssSpecialChars: { [k: string]: string } = { /* HTML special chars - escape without exception to hex */ '<': '\\3C ', '>': '\\3E ', '\'': '\\27 ', '"': '\\22 ', '&': '\\26 ', /* Characters beyond ASCII value 255 to unicode escape */ 'Ā': '\\100 ', /* Immune chars excluded */ ',': '\\2C ', '.': '\\2E ', '_': '\\5F ', /* Basic alnums excluded */ 'a': 'a', 'A': 'A', 'z': 'z', 'Z': 'Z', '0': '0', '9': '9', /* Basic control characters and null */ "\r": '\\D ', "\n": '\\A ', "\t": '\\9 ', "\0": '\\0 ', /* Encode spaces for quoteless attribute protection */ ' ': '\\20 ', }; /** * Convert a Unicode Codepoint to a literal UTF-8 character. * * @param {number} codepoint Unicode codepoint in hex notation * * @return string UTF-8 literal string */ let codepointToUtf8 = function (codepoint: number) { if (codepoint < 0x110000) { return String.fromCharCode(codepoint); } throw new Error('Codepoint requested outside of Unicode range.'); }; let getTemplate = function () { return new MockTemplate(new MockEnvironment(new MockLoader())); }; tape('escaping', (test) => { test.test('htmlEscapingConvertsSpecialChars', async (test) => { for (let key in htmlSpecialChars) { let value = htmlSpecialChars[key]; test.same(await escape(getTemplate(), key, 'html'), value, 'Succeed at escaping: ' + key); } test.end(); }); test.test('htmlAttributeEscapingConvertsSpecialChars', async (test) => { for (let key in htmlAttrSpecialChars) { let value = htmlAttrSpecialChars[key]; test.same(await escape(getTemplate(), key, 'html_attr'), value, 'Succeed at escaping: ' + key); } test.end(); }); test.test('javascriptEscapingConvertsSpecialChars', async (test) => { for (let key in jsSpecialChars) { let value = jsSpecialChars[key]; test.same(await escape(getTemplate(), key, 'js'), value, 'Succeed at escaping: ' + key); } test.end(); }); test.test('javascriptEscapingReturnsStringIfZeroLength', async (test) => { test.same(await escape(getTemplate(), '', 'js'), '', 'Succeed at escaping: ""'); test.end(); }); test.test('javascriptEscapingReturnsStringIfContainsOnlyDigits', async (test) => { test.same(await escape(getTemplate(), '123', 'js'), '123', 'Succeed at escaping: "123"'); test.end(); }); test.test('cssEscapingConvertsSpecialChars', async (test) => { for (let key in cssSpecialChars) { let value = cssSpecialChars[key]; test.same(await escape(getTemplate(), key, 'css'), value, 'Succeed at escaping: ' + key); } test.end(); }); test.test('cssEscapingReturnsStringIfZeroLength', async (test) => { test.same(await escape(getTemplate(), '', 'css'), '', 'Succeed at escaping: ""'); test.end(); }); test.test('cssEscapingReturnsStringIfContainsOnlyDigits', async (test) => { test.same(await escape(getTemplate(), '123', 'css'), '123', 'Succeed at escaping: "123"'); test.end(); }); test.test('urlEscapingConvertsSpecialChars', async (test) => { for (let key in urlSpecialChars) { let value = urlSpecialChars[key]; test.same(await escape(getTemplate(), key, 'url'), value, 'Succeed at escaping: ' + key); } test.end(); }); /** * Range tests to confirm escaped range of characters is within OWASP recommendation. */ /** * Only testing the first few 2 ranges on this prot. function as that's all these * other range tests require. */ test.test('unicodeCodepointConversionToUtf8', async (test) => { let expected = ' ~ޙ'; let codepoints = [0x20, 0x7e, 0x799]; let result = ''; for (let value of codepoints) { result += codepointToUtf8(value); } test.same(result, expected); test.end(); }); test.test('javascriptEscapingEscapesOwaspRecommendedRanges', async (test) => { let immune = [',', '.', '_']; // Exceptions to escaping ranges for (let chr = 0; chr < 0xFF; ++chr) { if (chr >= 0x30 && chr <= 0x39 || chr >= 0x41 && chr <= 0x5A || chr >= 0x61 && chr <= 0x7A) { let literal = codepointToUtf8(chr); test.same(await escape(getTemplate(), literal, 'js'), literal); } else { let literal = codepointToUtf8(chr); if (immune.includes(literal)) { test.same(await escape(getTemplate(), literal, 'js'), literal); } else { test.notSame(await escape(getTemplate(), literal, 'js'), literal); } } } test.end(); }); test.test('htmlAttributeEscapingEscapesOwaspRecommendedRanges', async (test) => { let immune = [',', '.', '-', '_']; // Exceptions to escaping ranges for (let chr = 0; chr < 0xFF; ++chr) { if (chr >= 0x30 && chr <= 0x39 || chr >= 0x41 && chr <= 0x5A || chr >= 0x61 && chr <= 0x7A) { let literal = codepointToUtf8(chr); test.same(await escape(getTemplate(), literal, 'html_attr'), literal); } else { let literal = codepointToUtf8(chr); if (immune.includes(literal)) { test.same(await escape(getTemplate(), literal, 'html_attr'), literal); } else { test.notSame(await escape(getTemplate(), literal, 'html_attr'), literal); } } } test.end(); }); test.test('cssEscapingEscapesOwaspRecommendedRanges', async (test) => { for (let chr = 0; chr < 0xFF; ++chr) { if (chr >= 0x30 && chr <= 0x39 || chr >= 0x41 && chr <= 0x5A || chr >= 0x61 && chr <= 0x7A) { let literal = codepointToUtf8(chr); test.same(await escape(getTemplate(), literal, 'css'), literal); } else { let literal = codepointToUtf8(chr); test.notSame(await escape(getTemplate(), literal, 'css'), literal); } } test.end(); }); test.test('customEscaper', async (test) => { let customEscaperCases: [string, string | number, string, string][] = [ ['fooUTF-8', 'foo', 'foo', 'UTF-8'], ['UTF-8', null, 'foo', 'UTF-8'], ['42UTF-8', 42, 'foo', undefined], ]; for (let customEscaperCase of customEscaperCases) { let template = getTemplate(); template.environment.getCoreExtension().setEscaper('foo', foo_escaper_for_test); test.same(await escape(template, customEscaperCase[1], customEscaperCase[2], customEscaperCase[3]), customEscaperCase[0]); } test.end(); }); test.test('customUnknownEscaper', async (test) => { try { await escape(getTemplate(), 'foo', 'bar'); test.fail(); } catch (e) { test.same(e.message, 'Invalid escaping strategy "bar" (valid ones: html, js, url, css, html_attr).'); } test.end(); }); test.end(); });
the_stack
import * as ts from 'typescript'; import { Symbols } from './typescripts'; import { Type as JsonType, Request as JsonRequest, Notification as JsonNotification, Structure, Property, StructureLiteral, BaseTypes, TypeAlias, MetaModel, Enumeration, EnumerationEntry, EnumerationType } from './metaModel'; import path = require('path'); const LSPBaseTypes = new Set(['Uri', 'DocumentUri', 'integer', 'uinteger', 'decimal']); type BaseTypeInfoKind = 'string' | 'boolean' | 'Uri' | 'DocumentUri' | 'integer' | 'uinteger' | 'decimal' | 'void' | 'never' | 'unknown' | 'null' | 'undefined' | 'any' | 'object'; export type TypeInfoKind = 'base' | 'reference' | 'array' | 'map' | 'intersection' | 'union' | 'tuple' | 'literal' | 'stringLiteral' | 'integerLiteral' | 'booleanLiteral'; type MapKeyType = { kind: 'base'; name: 'Uri' | 'DocumentUri' | 'string' | 'integer' } | { kind: 'reference'; name: string; symbol: ts.Symbol }; namespace MapKeyType { export function is(value: TypeInfo): value is MapKeyType { return value.kind === 'reference' || (value.kind === 'base' && (value.name === 'string' || value.name === 'integer' || value.name === 'DocumentUri' || value.name === 'Uri')); } } type LiteralInfo = { type: TypeInfo; optional: boolean; documentation?: string; since?: string; proposed?: boolean }; type TypeInfo = { kind: TypeInfoKind; } & ({ kind: 'base'; name: BaseTypeInfoKind; } | { kind: 'reference'; name: string; symbol: ts.Symbol; } | { kind: 'array'; elementType: TypeInfo; } | { kind: 'map'; key: MapKeyType; value: TypeInfo; } | { kind: 'union'; items: TypeInfo[]; } | { kind: 'intersection'; items: TypeInfo[]; } | { kind: 'tuple'; items: TypeInfo[]; } | { kind: 'literal'; items: Map<string, LiteralInfo>; } | { kind: 'stringLiteral'; value: string; } | { kind: 'integerLiteral'; value: number; } | { kind: 'booleanLiteral'; value: boolean; }); namespace TypeInfo { export function isNonLSPType(info: TypeInfo): boolean { return info.kind === 'base' && (info.name === 'void' || info.name === 'undefined' || info.name === 'never' || info.name === 'unknown'); } export function isVoid(info: TypeInfo): info is { kind: 'base'; name: 'void' } { return info.kind === 'base' && info.name === 'void'; } const baseSet = new Set(['null', 'void', 'string', 'boolean', 'Uri', 'DocumentUri', 'integer', 'uinteger', 'decimal']); export function asJsonType(info: TypeInfo): JsonType { switch (info.kind) { case 'base': if (baseSet.has(info.name)) { return { kind: 'base', name: info.name as BaseTypes }; } if (info.name === 'object') { return { kind: 'reference', name: 'LSPAny' }; } break; case 'reference': return { kind: 'reference', name: info.name }; case 'array': return { kind: 'array', element: asJsonType(info.elementType) }; case 'map': return { kind: 'map', key: asJsonType(info.key) as MapKeyType, value: asJsonType(info.value) }; case 'union': return { kind: 'or', items: info.items.map(info => asJsonType(info)) }; case 'intersection': return { kind: 'and', items: info.items.map(info => asJsonType(info)) }; case 'tuple': return { kind: 'tuple', items: info.items.map(info => asJsonType(info)) }; case 'literal': const literal: StructureLiteral = { properties: [] }; for (const entry of info.items) { const property: Property = { name: entry[0], type: asJsonType(entry[1].type) }; const value = entry[1]; if (value.optional === true) { property.optional = true; } if (value.documentation !== undefined) { property.documentation = value.documentation; } if (value.since !== undefined) { property.since = value.since; } if (value.proposed === true) { property.proposed = true; } literal.properties.push(property); } return { kind: 'literal', value: literal }; case 'stringLiteral': return { kind: 'stringLiteral', value: info.value }; case 'integerLiteral': return { kind: 'integerLiteral', value: info.value }; case 'booleanLiteral': return { kind: 'booleanLiteral', value: info.value }; } throw new Error(`Can't convert type info ${JSON.stringify(info, undefined, 0)}`); } } type RequestTypes = { param?: TypeInfo; result: TypeInfo; partialResult: TypeInfo; errorData: TypeInfo; registrationOptions: TypeInfo; }; type NotificationTypes = { param?: TypeInfo; registrationOptions: TypeInfo; }; export default class Visitor { private readonly program: ts.Program; private readonly typeChecker: ts.TypeChecker; private readonly symbols: Symbols; #currentSourceFile: ts.SourceFile | undefined; private readonly requests: JsonRequest[]; private readonly notifications: JsonNotification[]; private readonly structures: Structure[]; private readonly enumerations: Enumeration[]; private readonly typeAliases: TypeAlias[]; private readonly symbolQueue: Map<string, ts.Symbol>; private readonly processedStructures: Map<string, ts.Symbol>; constructor(program: ts.Program) { this.program = program; this.typeChecker = this.program.getTypeChecker(); this.symbols = new Symbols(this.typeChecker); this.requests = []; this.notifications = []; this.structures = []; this.enumerations = []; this.typeAliases = []; this.symbolQueue = new Map(); this.processedStructures = new Map(); } protected get currentSourceFile(): ts.SourceFile { if (this.#currentSourceFile === undefined) { throw new Error(`Current source file not known`); } return this.#currentSourceFile; } public async visitProgram(): Promise<void> { for (const sourceFile of this.getSourceFilesToIndex()) { this.visit(sourceFile); } } public async endVisitProgram(): Promise<void> { while (this.symbolQueue.size > 0) { const toProcess = new Map(this.symbolQueue); for (const entry of toProcess) { const element = this.processSymbol(entry[0], entry[1]); if (element === undefined) { throw new Error(`Can't create structure for type ${entry[0]}`); } else if (Array.isArray((element as Structure).properties)) { this.structures.push(element as Structure); } else if (Array.isArray((element as Enumeration).values)) { this.enumerations.push(element as Enumeration); } else { this.typeAliases.push(element as TypeAlias); } this.symbolQueue.delete(entry[0]); this.processedStructures.set(entry[0], entry[1]); } } } public getMetaModel(): MetaModel { return { requests: this.requests, notifications: this.notifications, structures: this.structures, enumerations: this.enumerations, typeAliases: this.typeAliases }; } protected visit(node: ts.Node): void { switch (node.kind) { case ts.SyntaxKind.SourceFile: this.doVisit(this.visitSourceFile, this.endVisitSourceFile, node as ts.SourceFile); break; case ts.SyntaxKind.ModuleDeclaration: this.doVisit(this.visitModuleDeclaration, this.endVisitModuleDeclaration, node as ts.ModuleDeclaration); break; default: this.doVisit(this.visitGeneric, this.endVisitGeneric, node); break; } } private doVisit<T extends ts.Node>(visit: (node: T) => boolean, endVisit: (node: T) => void, node: T): void { if (visit.call(this, node)) { node.forEachChild(child => this.visit(child)); } endVisit.call(this, node); } private visitGeneric(): boolean { return true; } private endVisitGeneric(): void { } private visitSourceFile(node: ts.SourceFile): boolean { this.#currentSourceFile = node; // The file `protocol.$.ts` contains all definitions for things // that are not reference through the protocol module but part of // the LSP specification. So treat the definitions as such. They all need // to start with a $ to make this clear. if (path.basename(node.fileName) === 'protocol.$.ts') { for (const statement of node.statements) { if (ts.isTypeAliasDeclaration(statement) && statement.name.getText()[0] === '$') { this.visitTypeReference(statement); } if (ts.isVariableStatement(statement)) { for (const declaration of statement.declarationList.declarations) { if (declaration.name.getText()[0] !== '$' || declaration.initializer === undefined) { continue; } const symbol = this.typeChecker.getSymbolAtLocation(declaration.initializer); if (symbol === undefined) { continue; } this.queueSymbol(symbol.getName(), symbol); } } } } return true; } private endVisitSourceFile(): void { this.#currentSourceFile = undefined; } private visitModuleDeclaration(node: ts.ModuleDeclaration): boolean { const identifier = node.name.getText(); // We have a request or notification definition. if (identifier.endsWith('Request')) { const request = this.visitRequest(node); if (request === undefined) { throw new Error(`Creating meta data for request ${identifier} failed.`); } else { this.requests.push(request); } } else if (identifier.endsWith('Notification')) { const notification = this.visitNotification(node); if (notification === undefined) { throw new Error(`Creating meta data for notification ${identifier} failed.`); } else { this.notifications.push(notification); } } return true; } private visitRequest(node: ts.ModuleDeclaration): JsonRequest | undefined { const symbol = this.typeChecker.getSymbolAtLocation(node.name); if (symbol === undefined) { return; } const type = symbol.exports?.get('type' as ts.__String); if (type === undefined) { return; } const methodName = this.getMethodName(symbol, type); if (methodName === undefined) { return; } const requestTypes = this.getRequestTypes(type); if (requestTypes === undefined) { return; } requestTypes.param && this.queueTypeInfo(requestTypes.param); this.queueTypeInfo(requestTypes.result); this.queueTypeInfo(requestTypes.partialResult); this.queueTypeInfo(requestTypes.errorData); this.queueTypeInfo(requestTypes.registrationOptions); const asJsonType = (info: TypeInfo) => { if (TypeInfo.isNonLSPType(info)) { return undefined; } return TypeInfo.asJsonType(info); }; const result: JsonRequest = { method: methodName, result: TypeInfo.isVoid(requestTypes.result) ? TypeInfo.asJsonType({ kind: 'base', name: 'null' }) : TypeInfo.asJsonType(requestTypes.result) }; result.params = requestTypes.param !== undefined ? asJsonType(requestTypes.param) : undefined; result.partialResult = asJsonType(requestTypes.partialResult); result.errorData = asJsonType(requestTypes.errorData); result.registrationOptions = asJsonType(requestTypes.registrationOptions); this.fillDocProperties(node, result); return result; } private visitNotification(node: ts.ModuleDeclaration): JsonNotification | undefined { const symbol = this.typeChecker.getSymbolAtLocation(node.name); if (symbol === undefined) { return; } const type = symbol.exports?.get('type' as ts.__String); if (type === undefined) { return; } const methodName = this.getMethodName(symbol, type); if (methodName === undefined) { return; } const notificationTypes = this.getNotificationTypes(type); if (notificationTypes === undefined) { return undefined; } notificationTypes.param && this.queueTypeInfo(notificationTypes.param); this.queueTypeInfo(notificationTypes.registrationOptions); const asJsonType = (info: TypeInfo) => { if (TypeInfo.isNonLSPType(info)) { return undefined; } return TypeInfo.asJsonType(info); }; const result: JsonNotification = { method: methodName }; result.params = notificationTypes.param !== undefined ? asJsonType(notificationTypes.param) : undefined; result.registrationOptions = asJsonType(notificationTypes.registrationOptions); this.fillDocProperties(node, result); return result; } private visitTypeReference(node: ts.TypeAliasDeclaration): void { const type = node.type; if (!ts.isTypeReferenceNode(type)) { return; } const symbol = this.typeChecker.getSymbolAtLocation(type.typeName); if (symbol === undefined) { return; } this.queueSymbol(type.typeName.getText(), symbol); } private queueTypeInfo(typeInfo: TypeInfo): void { if (typeInfo.kind === 'reference') { this.queueSymbol(typeInfo.name, typeInfo.symbol); } else if (typeInfo.kind === 'array') { this.queueTypeInfo(typeInfo.elementType); } else if (typeInfo.kind === 'union' || typeInfo.kind === 'intersection' || typeInfo.kind === 'tuple') { typeInfo.items.forEach(item => this.queueTypeInfo(item)); } else if (typeInfo.kind === 'map') { this.queueTypeInfo(typeInfo.key); this.queueTypeInfo(typeInfo.value); } else if (typeInfo.kind === 'literal') { typeInfo.items.forEach(item => this.queueTypeInfo(item.type)); } } private queueSymbol(name: string, symbol: ts.Symbol): void { if (name !== symbol.getName()) { throw new Error(`Different symbol names [${name}, ${symbol.getName()}]`); } const existing = this.symbolQueue.get(name) ?? this.processedStructures.get(name); if (existing === undefined) { const aliased = Symbols.isAliasSymbol(symbol) ? this.typeChecker.getAliasedSymbol(symbol) : undefined; if (aliased !== undefined && aliased.getName() !== symbol.getName()) { throw new Error(`The symbol ${symbol.getName()} has a different name than the aliased symbol ${aliased.getName()}`); } this.symbolQueue.set(name, aliased ?? symbol); } else { const left = Symbols.isAliasSymbol(symbol) ? this.typeChecker.getAliasedSymbol(symbol) : symbol; const right = Symbols.isAliasSymbol(existing) ? this.typeChecker.getAliasedSymbol(existing) : existing; if (this.symbols.createKey(left) !== this.symbols.createKey(right)) { throw new Error(`The type ${name} has two different declarations`); } } } private endVisitModuleDeclaration(_node: ts.ModuleDeclaration): void { } private getSourceFilesToIndex(): ReadonlyArray<ts.SourceFile> { const result: ts.SourceFile[] = []; for (const sourceFile of this.program.getSourceFiles()) { if (this.program.isSourceFileFromExternalLibrary(sourceFile) || this.program.isSourceFileDefaultLibrary(sourceFile)) { continue; } result.push(sourceFile); } return result; } private getMethodName(namespace: ts.Symbol, type: ts.Symbol): string | undefined { const method = namespace.exports?.get('method' as ts.__String); let text: string; if (method !== undefined) { const declaration = this.getFirstDeclaration(method); if (declaration === undefined) { return undefined; } if (!ts.isVariableDeclaration(declaration)) { return undefined; } const initializer = declaration.initializer; if (initializer === undefined || (!ts.isStringLiteral(initializer) && !ts.isNoSubstitutionTemplateLiteral(initializer))) { return undefined; } text = initializer.getText(); } else { const declaration = this.getFirstDeclaration(type); if (declaration === undefined) { return undefined; } if (!ts.isVariableDeclaration(declaration)) { return undefined; } const initializer = declaration.initializer; if (initializer === undefined || !ts.isNewExpression(initializer)) { return undefined; } const args = initializer.arguments; if (args === undefined || args.length < 1) { return undefined; } text = args[0].getText(); } return this.removeQuotes(text); } private getRequestTypes(symbol: ts.Symbol): RequestTypes | undefined { const declaration = this.getFirstDeclaration(symbol); if (declaration === undefined) { return undefined; } if (!ts.isVariableDeclaration(declaration)) { return; } const initializer = declaration.initializer; if (initializer === undefined || !ts.isNewExpression(initializer)) { return undefined; } if (initializer.typeArguments === undefined) { return undefined; } const typeInfos: TypeInfo[] = []; for (const typeNode of initializer.typeArguments) { const info = this.getTypeInfo(typeNode); if (info === undefined) { return undefined; } typeInfos.push(info); } if (typeInfos.length !== initializer.typeArguments.length) { return undefined; } switch (initializer.typeArguments.length) { case 4: return { result: typeInfos[0], partialResult: typeInfos[1], errorData: typeInfos[2], registrationOptions: typeInfos[3] }; case 5: return { param: typeInfos[0], result: typeInfos[1], partialResult: typeInfos[2], errorData: typeInfos[3], registrationOptions: typeInfos[4] }; } return undefined; } private getNotificationTypes(symbol: ts.Symbol): NotificationTypes | undefined { const declaration = this.getFirstDeclaration(symbol); if (declaration === undefined) { return undefined; } if (!ts.isVariableDeclaration(declaration)) { return; } const initializer = declaration.initializer; if (initializer === undefined || !ts.isNewExpression(initializer)) { return undefined; } if (initializer.typeArguments === undefined) { return undefined; } const typeInfos: TypeInfo[] = []; for (const typeNode of initializer.typeArguments) { const info = this.getTypeInfo(typeNode); if (info === undefined) { return undefined; } typeInfos.push(info); } if (typeInfos.length !== initializer.typeArguments.length) { return undefined; } switch (initializer.typeArguments.length) { case 1: return { registrationOptions: typeInfos[0] }; case 2: return { param: typeInfos[0], registrationOptions: typeInfos[1] }; } return undefined; } private getTypeInfo(typeNode: ts.TypeNode | ts.Identifier, isLSPAny = false): TypeInfo | undefined { if (ts.isIdentifier(typeNode)) { const typeName = typeNode.text; if (LSPBaseTypes.has(typeName)) { return { kind: 'base', name: typeName as BaseTypeInfoKind }; } const symbol = this.typeChecker.getSymbolAtLocation(typeNode); if (symbol === undefined) { return undefined; } return { kind: 'reference', name: typeName, symbol }; } else if (ts.isTypeReferenceNode(typeNode)) { const typeName = ts.isIdentifier(typeNode.typeName) ? typeNode.typeName.text : typeNode.typeName.right.text; if (LSPBaseTypes.has(typeName)) { return { kind: 'base', name: typeName as BaseTypeInfoKind }; } const symbol = this.typeChecker.getSymbolAtLocation(typeNode.typeName); if (symbol === undefined) { return undefined; } return { kind: 'reference', name: typeName, symbol }; } else if (ts.isArrayTypeNode(typeNode)) { const elementType = this.getTypeInfo(typeNode.elementType); if (elementType === undefined) { return undefined; } return { kind: 'array', elementType: elementType }; } else if (ts.isUnionTypeNode(typeNode)) { const items: TypeInfo[] = []; for (const item of typeNode.types) { const typeInfo = this.getTypeInfo(item); if (typeInfo === undefined) { return undefined; } // We need to remove undefined from LSP Any since // it is not a valid type on the wire if (isLSPAny && typeInfo.kind === 'base' && typeInfo.name === 'undefined') { continue; } items.push(typeInfo); } return { kind: 'union', items }; } else if (ts.isIntersectionTypeNode(typeNode)) { const items: TypeInfo[] = []; for (const item of typeNode.types) { const typeInfo = this.getTypeInfo(item); if (typeInfo === undefined) { return undefined; } items.push(typeInfo); } return { kind: 'intersection', items }; } else if (ts.isTypeLiteralNode(typeNode)) { const type = this.typeChecker.getTypeAtLocation(typeNode); const info = this.typeChecker.getIndexInfoOfType(type, ts.IndexKind.String); if (info !== undefined) { const declaration = info.declaration; if (declaration === undefined || declaration.parameters.length < 1) { return undefined; } const keyTypeNode = declaration.parameters[0].type; if (keyTypeNode === undefined) { return undefined; } const key = this.getTypeInfo(keyTypeNode); const value = this.getTypeInfo(declaration.type); if (key === undefined || value === undefined) { return undefined; } if (!MapKeyType.is(key)) { return undefined; } return { kind: 'map', key: key, value: value }; } else { // We can't directly ask for the symbol since the literal has no name. const type = this.typeChecker.getTypeAtLocation(typeNode); const symbol = type.symbol; if (symbol === undefined) { return undefined; } if (symbol.members === undefined) { return { kind: 'literal', items: new Map() }; } const items = new Map<string, { type: TypeInfo; optional: boolean }>(); symbol.members.forEach((member) => { if (!Symbols.isProperty(member)) { return; } const declaration = this.getDeclaration(member, ts.SyntaxKind.PropertySignature); if (declaration === undefined || !ts.isPropertySignature(declaration) || declaration.type === undefined) { throw new Error(`Can't parse property ${member.getName()} of structure ${symbol.getName()}`); } const propertyType = this.getTypeInfo(declaration.type); if (propertyType === undefined) { throw new Error(`Can't parse property ${member.getName()} of structure ${symbol.getName()}`); } const literalInfo: LiteralInfo = { type: propertyType, optional: Symbols.isOptional(member) }; this.fillDocProperties(declaration, literalInfo); items.set(member.getName(), literalInfo); }); return { kind: 'literal', items }; } } else if (ts.isTupleTypeNode(typeNode)) { const items: TypeInfo[] = []; for (const item of typeNode.elements) { const typeInfo = this.getTypeInfo(item); if (typeInfo === undefined) { return undefined; } items.push(typeInfo); } return { kind: 'tuple', items }; } else if (ts.isTypeQueryNode(typeNode) && ts.isQualifiedName(typeNode.exprName)) { // Currently we only us the typeof operator to get to the type of a enum // value expressed by an or type (e.g. kind: typeof DocumentDiagnosticReportKind.full) // So we assume a qualifed name and turn it into a string literal type const typeNodeSymbol = this.typeChecker.getSymbolAtLocation(typeNode.exprName); if (typeNodeSymbol === undefined) { throw new Error(`Can't resolve symbol for right hand side of enum declaration`); } const declaration = this.getDeclaration(typeNodeSymbol, ts.SyntaxKind.VariableDeclaration); if (declaration === undefined || !ts.isVariableDeclaration(declaration) || declaration.initializer === undefined) { throw new Error(`Can't resolve variable declaration for right hand side of enum declaration`); } if (ts.isNumericLiteral(declaration.initializer)) { return { kind: 'integerLiteral', value: Number.parseInt(declaration.initializer.getText()) }; } else if (ts.isStringLiteral(declaration.initializer)) { return { kind: 'stringLiteral', value: this.removeQuotes(declaration.initializer.getText()) }; } return { kind: 'stringLiteral', value: typeNode.exprName.right.getText() }; } else if (ts.isParenthesizedTypeNode(typeNode)) { return this.getTypeInfo(typeNode.type); } else if (ts.isLiteralTypeNode(typeNode)) { return this.getBaseTypeInfo(typeNode.literal); } return this.getBaseTypeInfo(typeNode); } private getBaseTypeInfo(node: ts.Node): TypeInfo | undefined { switch (node.kind){ case ts.SyntaxKind.NullKeyword: return { kind: 'base', name: 'null' }; case ts.SyntaxKind.UnknownKeyword: return { kind: 'base', name: 'unknown' }; case ts.SyntaxKind.NeverKeyword: return { kind: 'base', name: 'never' }; case ts.SyntaxKind.VoidKeyword: return { kind: 'base', name: 'void' }; case ts.SyntaxKind.UndefinedKeyword: return { kind: 'base', name: 'undefined' }; case ts.SyntaxKind.AnyKeyword: return { kind: 'base', name: 'any' }; case ts.SyntaxKind.StringKeyword: return { kind: 'base', name: 'string' }; case ts.SyntaxKind.NumberKeyword: return { kind: 'base', name: 'integer' }; case ts.SyntaxKind.BooleanKeyword: return { kind: 'base', name: 'boolean' }; case ts.SyntaxKind.StringLiteral: return { kind: 'stringLiteral', value: this.removeQuotes(node.getText()) }; case ts.SyntaxKind.NumericLiteral: return { kind: 'integerLiteral', value: Number.parseInt(node.getText()) }; case ts.SyntaxKind.ObjectKeyword: return { kind: 'base', name: 'object' }; } return undefined; } private static readonly Mixins: Set<string> = new Set(['WorkDoneProgressParams', 'PartialResultParams', 'StaticRegistrationOptions', 'WorkDoneProgressOptions']); private static readonly PropertyFilters: Map<string, Set<string>> = new Map([ ['TraceValues', new Set(['Compact'])], ['ErrorCodes', new Set(['MessageWriteError', 'MessageReadError', 'PendingResponseRejected', 'ConnectionInactive'])] ]); private static readonly PropertyRenames: Map<string, Map<string, string>> = new Map([ ['MonikerKind', new Map([ ['$export', 'export'], ['$import', 'import'] ])] ]); private processSymbol(name: string, symbol: ts.Symbol): Structure | Enumeration | TypeAlias | undefined { // We can't define LSPAny in the protocol right now due to TS issues. // So we predefine it and emit it. if (name === 'LSPAny') { this.typeAliases.push(PreDefined.LSPArray); return PreDefined.LSPAny; } if (name === 'LSPArray') { // LSP Array is never reference via a indirect reference from // a request or notification. return undefined; } if (name === 'LSPObject') { return PreDefined.LSPObject; } if (Symbols.isInterface(symbol)) { const result: Structure = { name: name, properties: [] }; const declaration = this.getDeclaration(symbol, ts.SyntaxKind.InterfaceDeclaration); if (declaration !== undefined && ts.isInterfaceDeclaration(declaration) && declaration.heritageClauses !== undefined) { const mixins: JsonType[] = []; const extend: JsonType[] = []; for (const clause of declaration.heritageClauses) { for (const type of clause.types) { if (ts.isIdentifier(type.expression)) { const typeInfo = this.getTypeInfo(type.expression); if (typeInfo === undefined || typeInfo.kind !== 'reference') { throw new Error(`Can't create type info for extends clause ${type.expression.getText()}`); } if (Visitor.Mixins.has(typeInfo.name)) { mixins.push(TypeInfo.asJsonType(typeInfo)); } else { extend.push(TypeInfo.asJsonType(typeInfo)); } this.queueTypeInfo(typeInfo); } } } if (extend.length > 0) { result.extends = extend; } if (mixins.length > 0) { result.mixins = mixins; } } if (declaration !== undefined) { this.fillDocProperties(declaration, result); } this.fillProperties(result, symbol); return result; } else if (Symbols.isTypeAlias(symbol)) { const declaration = this.getDeclaration(symbol, ts.SyntaxKind.TypeAliasDeclaration); if (declaration === undefined ||!ts.isTypeAliasDeclaration(declaration)) { throw new Error (`No declaration found for type alias ${symbol.getName() }`); } if (ts.isTypeLiteralNode(declaration.type)) { // We have a single type literal node. So treat it as a structure const result: Structure = { name: name, properties: [] }; this.fillProperties(result, this.typeChecker.getTypeAtLocation(declaration.type).symbol); this.fillDocProperties(declaration, result); return result; } else if (ts.isIntersectionTypeNode(declaration.type)) { const split = this.splitIntersectionType(declaration.type); if (split.rest.length === 0) { const result: Structure = { name: name, properties: [] }; const mixins: JsonType[] = []; const extend: JsonType[] = []; for (const reference of split.references) { const typeInfo = this.getTypeInfo(reference); if (typeInfo === undefined || typeInfo.kind !== 'reference') { throw new Error(`Can't create type info for type reference ${reference.getText()}`); } if (Visitor.Mixins.has(typeInfo.name)) { mixins.push(TypeInfo.asJsonType(typeInfo)); } else { extend.push(TypeInfo.asJsonType(typeInfo)); } this.queueTypeInfo(typeInfo); } if (extend.length > 0) { result.extends = extend; } if (mixins.length > 0) { result.mixins = mixins; } if (split.literal !== undefined) { this.fillProperties(result, this.typeChecker.getTypeAtLocation(split.literal).symbol); } this.fillDocProperties(declaration, result); return result; } } const target = this.getTypeInfo(declaration.type, name === 'LSPAny'); if (target === undefined) { throw new Error(`Can't resolve target type for type alias ${symbol.getName()}`); } const namespace = this.getDeclaration(symbol, ts.SyntaxKind.ModuleDeclaration); if (namespace !== undefined && symbol.declarations !== undefined && symbol.declarations.length === 2) { const fixedSet = (target.kind === 'union' || target.kind === 'stringLiteral' || target.kind === 'integerLiteral'); const openSet = (target.kind === 'base' && (target.name === 'string' || target.name === 'integer' || target.name === 'uinteger')); if (openSet || fixedSet) { // Check if we have a enum declaration. const body = namespace.getChildren().find(node => node.kind === ts.SyntaxKind.ModuleBlock); if (body !== undefined && ts.isModuleBlock(body)) { const enumValues = this.getEnumValues(target); const variableStatements = body.statements.filter((statement => ts.isVariableStatement(statement))); if ((fixedSet && enumValues !== undefined && enumValues.length > 0 && variableStatements.length === enumValues.length) || (openSet && variableStatements.length > 0)) { // Same length and all variable statement. const enumValuesSet: Set<number | string> | undefined = enumValues ? new Set<any>(enumValues as any) : undefined; let isEnum = true; const enumerations: EnumerationEntry[] = []; for (const variable of variableStatements) { if (!ts.isVariableStatement(variable) || variable.declarationList.declarations.length !== 1) { isEnum = false; break; } const declaration = variable.declarationList.declarations[0]; if (!ts.isVariableDeclaration(declaration)) { isEnum = false; break; } const value: number | string | undefined = this.getEnumValue(declaration); if (value === undefined) { isEnum = false; break; } if (enumValuesSet && !enumValuesSet.has(value)) { isEnum = false; break; } let propertyName = declaration.name.getText(); if (Visitor.PropertyRenames.has(name) && Visitor.PropertyRenames.get(name)?.has(propertyName)) { propertyName = Visitor.PropertyRenames.get(name)!.get(propertyName)!; } if (Visitor.PropertyFilters.has(name) && Visitor.PropertyFilters.get(name)?.has(propertyName)) { continue; } const entry: EnumerationEntry = { name: propertyName, value: value }; this.fillDocProperties(variable, entry); enumerations.push(entry); } if (isEnum) { const type: EnumerationType | undefined = enumValues ? this.getEnumBaseType(enumValues) : openSet ? target as EnumerationType : undefined; if (type !== undefined) { const enumeration: Enumeration = { name: name, type: type, values: enumerations }; if (openSet && !fixedSet) { enumeration.supportsCustomValues = true; } // First fill the documentation from the namespace and then from the // type declaration. this.fillDocProperties(namespace, enumeration); if (enumeration.documentation === undefined) { this.fillDocProperties(namespace, enumeration); } return enumeration; } } } } } } // We have a single reference to another type. Treat is as an extend of // that structure if (target.kind === 'reference' && Visitor.Mixins.has(target.name)) { this.queueTypeInfo(target); const result: Structure = { name: name, mixins: [TypeInfo.asJsonType(target)], properties: [] }; this.fillDocProperties(declaration, result); return result; } else { this.queueTypeInfo(target); const result: TypeAlias = { name: name, type: TypeInfo.asJsonType(target) }; this.fillDocProperties(declaration, result); return result; } } else if (Symbols.isRegularEnum(symbol)) { const entries: EnumerationEntry[] = []; const exports = this.typeChecker.getExportsOfModule(symbol); let enumBaseType: 'string' | 'integer' | 'uinteger' | undefined = undefined; for (const item of exports) { const declaration = this.getDeclaration(item, ts.SyntaxKind.EnumMember); if (declaration === undefined || !ts.isEnumMember(declaration) || declaration.initializer === undefined) { continue; } let value: string | number | undefined; if (ts.isNumericLiteral(declaration.initializer)) { value = Number.parseInt(declaration.initializer.getText()); if (value >= 0 && enumBaseType === undefined) { enumBaseType = 'uinteger'; } else { enumBaseType = 'integer'; } } else if (ts.isStringLiteral(declaration.initializer)) { value = this.removeQuotes(declaration.initializer.getText()); enumBaseType = 'string'; } if (value === undefined) { continue; } const entry: EnumerationEntry = { name: item.getName(), value: value }; if (Visitor.PropertyFilters.has(name) && Visitor.PropertyFilters.get(name)?.has(entry.name)) { continue; } this.fillDocProperties(declaration, entry); entries.push(entry); } const type: EnumerationType = enumBaseType === undefined ? { kind: 'base', name: 'uinteger' } : { kind: 'base', name: enumBaseType }; const result: Enumeration = { name: name, type: type, values: entries }; const declaration = this.getDeclaration(symbol, ts.SyntaxKind.EnumDeclaration); if (declaration !== undefined) { this.fillDocProperties(declaration, result); } return result; } else { const result: Structure = { name: name, properties: [] }; this.fillProperties(result, symbol); const declaration = this.getFirstDeclaration(symbol); declaration !== undefined && this.fillDocProperties(declaration, result); return result; } } private fillProperties(result: Structure, symbol: ts.Symbol) { // Using the type here to navigate the properties will result in folding // all properties since the type contains all inherited properties. So we go // over the symbol to make things work. if (symbol.members === undefined) { return; } symbol.members.forEach((member) => { if (!Symbols.isProperty(member)) { return; } const declaration = this.getDeclaration(member, ts.SyntaxKind.PropertySignature); if (declaration === undefined || !ts.isPropertySignature(declaration) || declaration.type === undefined) { throw new Error(`Can't parse property ${member.getName()} of structure ${symbol.getName()}`); } const typeInfo = this.getTypeInfo(declaration.type); if (typeInfo === undefined) { throw new Error(`Can't parse property ${member.getName()} of structure ${symbol.getName()}`); } const isExperimentalProperty = (result.name === 'ServerCapabilities' && member.getName() === 'experimental' && typeInfo.kind === 'reference' && typeInfo.name === 'T'); const property: Property = isExperimentalProperty ? { name: member.getName(), type: TypeInfo.asJsonType({ kind: 'reference', name: 'LSPAny', symbol: typeInfo.symbol }) } : { name: member.getName(), type: TypeInfo.asJsonType(typeInfo) }; if (Symbols.isOptional(member)) { property.optional = true; } this.fillDocProperties(declaration, property); result.properties.push(property); if (!isExperimentalProperty) { this.queueTypeInfo(typeInfo); } }); } private splitIntersectionType(node: ts.IntersectionTypeNode): { literal: ts.TypeLiteralNode | undefined; references: ts.TypeReferenceNode[]; rest: ts.TypeNode[] } { let literal: ts.TypeLiteralNode | undefined; const rest: ts.TypeNode[] = []; const references: ts.TypeReferenceNode[] = []; for (const element of node.types) { if (ts.isTypeLiteralNode(element)) { if (literal === undefined) { literal = element; } else { rest.push(element); } } else if (ts.isTypeReferenceNode(element)) { references.push(element); } else { rest.push(element); } } return { literal, references, rest }; } private getFirstDeclaration(symbol: ts.Symbol): ts.Node | undefined { const declarations = symbol.getDeclarations(); return declarations !== undefined && declarations.length > 0 ? declarations[0] : undefined; } private getDeclaration(symbol: ts.Symbol, kind: ts.SyntaxKind): ts.Node | undefined { const declarations = symbol.getDeclarations(); if (declarations === undefined) { return undefined; } for (const declaration of declarations) { if (declaration.kind === kind) { return declaration; } } return undefined; } private getEnumValues(typeInfo: TypeInfo): string[] | number[] | undefined { if (typeInfo.kind === 'stringLiteral') { return [typeInfo.value]; } if (typeInfo.kind === 'integerLiteral') { return [typeInfo.value]; } if (typeInfo.kind !== 'union' || typeInfo.items.length === 0) { return undefined; } const first = typeInfo.items[0]; const item: [string, string] | [string, number] | undefined = first.kind === 'stringLiteral' ? [first.kind, first.value] : (first.kind === 'integerLiteral' ? [first.kind, first.value] : undefined); if (item === undefined) { return undefined; } const kind = item[0]; const result: (string | number)[] = []; result.push(item[1]); for (let i = 1; i < typeInfo.items.length; i++) { const info = typeInfo.items[i]; if (info.kind !== kind) { return undefined; } if (info.kind !== 'integerLiteral' && info.kind !== 'stringLiteral') { return undefined; } result.push(info.value); } return (result as string[] | number[]); } private getEnumValue(declaration: ts.VariableDeclaration): number | string | undefined { let enumValueNode: ts.Node | undefined; if (declaration.initializer !== undefined) { enumValueNode = declaration.initializer; } else if (declaration.type !== undefined && ts.isLiteralTypeNode(declaration.type)) { enumValueNode = declaration.type.literal; } if (enumValueNode === undefined) { return undefined; } if (ts.isNumericLiteral(enumValueNode) || (ts.isPrefixUnaryExpression(enumValueNode) && ts.isNumericLiteral(enumValueNode.operand))) { return Number.parseInt(enumValueNode.getText()); } else if (ts.isStringLiteral(enumValueNode)) { return this.removeQuotes(enumValueNode.getText()); } return undefined; } getEnumBaseType(values: string[] | number[]) : EnumerationType | undefined { if (values.length === 0) { return undefined; } const first = values[0]; if (typeof first === 'string') { return { kind: 'base', name: 'string' }; } for (const value of (values as number[])) { if (value < 0) { return { kind: 'base', name: 'integer' }; } } return { kind: 'base', name: 'uinteger' }; } private removeQuotes(text: string): string { const first = text[0]; if ((first !== '\'' && first !== '"' && first !== '`') || first !== text[text.length - 1]) { return text; } return text.substring(1, text.length - 1); } private fillDocProperties(node: ts.Node, value: JsonRequest | JsonNotification | Property | Structure | StructureLiteral | EnumerationEntry | Enumeration | TypeAlias | LiteralInfo): void { const filePath = node.getSourceFile().fileName; const fileName = path.basename(filePath); const tags = ts.getJSDocTags(node); const since = this.getSince(tags); const proposed = (fileName.startsWith('proposed.') || tags.some((tag) => { return ts.isJSDocUnknownTag(tag) && tag.tagName.text === 'proposed';})) ? true : undefined; value.documentation = this.getDocumentation(node); value.since = since; value.proposed = proposed; } private getDocumentation(node: ts.Node): string | undefined { const fullText = node.getFullText(); const ranges = ts.getLeadingCommentRanges(fullText, 0); if (ranges !== undefined && ranges.length > 0) { const start = ranges[ranges.length - 1].pos; const end = ranges[ranges.length -1 ].end; const text = fullText.substring(start, end).trim(); if (text.startsWith('/**')) { const buffer: string[] = []; const lines = text.split(/\r?\n/); for (let i= 0; i < lines.length; i++) { let noComment = lines[i].replace(/^\s*\/\*\*(.*)\s*\*\/\s*$|^(\s*\/\*\*)|^(\s*\*\/\s*)$|^(\s*\*)/, (_match, m1) => { if (m1) { return m1; } else { return ''; } }); // First line if (i === 0 || i === lines.length - 1) { noComment = noComment.trim(); if (noComment.length === 0) { continue; } } if (noComment.length > 0 && noComment[0] === ' ') { noComment = noComment.substring(1); } buffer.push(noComment); } return buffer.join('\n'); } } return undefined; } private getSince(tags: ReadonlyArray<ts.JSDocTag>): string | undefined { for (const tag of tags) { if (tag.tagName.text === 'since' && typeof tag.comment === 'string') { return tag.comment; } } return undefined; } } namespace PreDefined { export const LSPAny: TypeAlias = { 'name': 'LSPAny', 'type': { 'kind': 'or', 'items': [ { 'kind': 'reference', 'name': 'LSPObject' }, { 'kind': 'reference', 'name': 'LSPArray' }, { 'kind': 'base', 'name': 'string' }, { 'kind': 'base', 'name': 'integer' }, { 'kind': 'base', 'name': 'uinteger' }, { 'kind': 'base', 'name': 'decimal' }, { 'kind': 'base', 'name': 'boolean' }, { 'kind': 'base', 'name': 'null' } ] }, 'documentation': 'The LSP any type.\nPlease note that strictly speaking a property with the value `undefined`\ncan\'t be converted into JSON preserving the property name. However for\nconvenience it is allowed and assumed that all these properties are\noptional as well.\n@since 3.17.0', 'since': '3.17.0' }; export const LSPObject: Structure = { 'name': 'LSPObject', 'properties': [], 'documentation': 'LSP object definition.\n@since 3.17.0', 'since': '3.17.0' }; export const LSPArray: TypeAlias = { 'name': 'LSPArray', 'type': { 'kind': 'array', 'element': { 'kind': 'reference', 'name': 'LSPAny' } }, 'documentation': 'LSP arrays.\n@since 3.17.0', 'since': '3.17.0' }; }
the_stack
import ll=require("../lowLevelAST"); import jsyaml = require("../jsyaml/jsyaml2lowLevel"); import hl=require("../highLevelAST"); import hlimpl=require("../highLevelImpl"); import yaml=require("yaml-ast-parser"); import util=require("../../util/index"); import proxy=require("./LowLevelASTProxy"); import RamlWrapper=require("../artifacts/raml10parserapi"); import pluralize = require("pluralize") import _ = require("underscore"); import core = require("../wrapped-ast/parserCore"); import referencePatcher = require("./referencePatcherLL"); import referencePatcherHL = require("./referencePatcher"); import namespaceResolver = require("./namespaceResolver"); import def = require("raml-definition-system"); import universeHelpers = require("../tools/universeHelpers"); import linter=require("../ast.core/linter") let messageRegistry = require("../../../resources/errorMessages"); var mediaTypeParser = require("media-typer"); var changeCase = require('change-case'); export function expandTraitsAndResourceTypes<T>(api:T, merge=false):T{ if(!core.BasicNodeImpl.isInstance(api)){ // if(!((<any>api).kind // && ((<any>api).kind() == "Api" || (<any>api).kind() == "Overlay" || (<any>api).kind() == "Extension"))){ return null; } var apiNode = <core.BasicNodeImpl><any>api; var hlNode = expandTraitsAndResourceTypesHL(apiNode.highLevel(), merge); if(!hlNode){ return null; } var result = <core.BasicNodeImpl>hlNode.wrapperNode(); result.setAttributeDefaults(apiNode.getDefaultsCalculator().isEnabled()); return <T><any>result; } export function expandTraitsAndResourceTypesHL(api:hl.IHighLevelNode, merge=false):hl.IHighLevelNode{ if(api==null){ return null; } var definition = api.definition(); if(!(definition&&universeHelpers.isApiSibling(definition))){ return null; } var result = new TraitsAndResourceTypesExpander().expandTraitsAndResourceTypes(api, null, false, merge); return result; } export function expandLibraries(api:RamlWrapper.Api):RamlWrapper.Api{ if(!api){ return null; } var hlNode = expandLibrariesHL(api.highLevel()); if(!hlNode){ return null; } var result = <RamlWrapper.Api>hlNode.wrapperNode(); (<any>result).setAttributeDefaults((<any>api).getDefaultsCalculator().isEnabled()); return result; } export function expandLibrary(lib:RamlWrapper.Library):RamlWrapper.Library{ if(!lib){ return null; } var hlNode = expandLibraryHL(lib.highLevel()); if(!hlNode){ return null; } var result = <RamlWrapper.Library>hlNode.wrapperNode(); (<any>result).setAttributeDefaults((<any>lib).getDefaultsCalculator().isEnabled()); return result; } export function expandLibrariesHL(api:hl.IHighLevelNode):hl.IHighLevelNode{ return new LibraryExpander().expandLibraries(api); } export function expandLibraryHL(lib:hl.IHighLevelNode):hl.IHighLevelNode{ return new LibraryExpander().expandLibrary(lib); } export function mergeAPIs(masterUnit:ll.ICompilationUnit, extensionsAndOverlays:ll.ICompilationUnit[], mergeMode: hlimpl.OverlayMergeMode) : hl.IHighLevelNode { var masterApi = hlimpl.fromUnit(masterUnit); if(!masterApi) throw new Error("couldn't load api from " + masterUnit.absolutePath()); if (!extensionsAndOverlays || extensionsAndOverlays.length == 0) { return masterApi.asElement(); } var highLevelNodes:hlimpl.ASTNodeImpl[] = []; for(var i = 0 ; i < extensionsAndOverlays.length ; i++){ var unit = extensionsAndOverlays[i]; var hlNode = hlimpl.fromUnit(unit); if(!hlNode){ throw new Error("couldn't load api from " + unit.absolutePath()); } highLevelNodes.push(<hlimpl.ASTNodeImpl>hlNode); } var lastExtensionOrOverlay = mergeHighLevelNodes(masterApi.asElement(), highLevelNodes, mergeMode); return lastExtensionOrOverlay; } function mergeHighLevelNodes( masterApi:hl.IHighLevelNode, highLevelNodes:hl.IHighLevelNode[], mergeMode, rp:referencePatcher.ReferencePatcher = null, expand = false):hl.IHighLevelNode { var expander:TraitsAndResourceTypesExpander; var currentMaster = masterApi; for(var currentApi of highLevelNodes) { if(expand&&(proxy.LowLevelProxyNode.isInstance(currentMaster.lowLevel()))) { if(!expander){ expander = new TraitsAndResourceTypesExpander(); } expander.expandHighLevelNode(currentMaster, rp, masterApi,expand); } (<hlimpl.ASTNodeImpl>currentApi).overrideMaster(currentMaster); (<hlimpl.ASTNodeImpl>currentApi).setMergeMode(mergeMode); currentMaster = currentApi; } return currentMaster; }; export class TraitsAndResourceTypesExpander { private ramlVersion:string; private defaultMediaType:string; private namespaceResolver:namespaceResolver.NamespaceResolver; expandTraitsAndResourceTypes( api:hl.IHighLevelNode, rp:referencePatcher.ReferencePatcher = null, forceProxy:boolean=false, merge=false):hl.IHighLevelNode { this.init(api); var llNode = api.lowLevel(); if(!llNode) { return api; } if(llNode.actual().libExpanded){ return api; } var hlNode = this.createHighLevelNode(<hlimpl.ASTNodeImpl>api,merge,rp); if (api.definition().key()==def.universesInfo.Universe10.Overlay){ return hlNode; } let unit = api.lowLevel().unit(); var hasFragments = (<jsyaml.Project>unit.project()).namespaceResolver().hasFragments(unit); var result = this.expandHighLevelNode(hlNode, rp, api,hasFragments); if (!result){ return api; } return result; } init(api:hl.IHighLevelNode) { let llNode = api.lowLevel(); let firstLine = hlimpl.ramlFirstLine(llNode.unit().contents()); if(firstLine && firstLine.length >= 2 && firstLine[1]=="0.8"){ this.ramlVersion = "RAML08"; } else{ this.ramlVersion = "RAML10"; } let mediaTypeNodes = llNode.children().filter(x=> x.key()==def.universesInfo.Universe10.Api.properties.mediaType.name); if(mediaTypeNodes.length>0) { this.defaultMediaType = mediaTypeNodes[0].value(); } let unit = api.lowLevel().unit(); let project = <jsyaml.Project>unit.project(); project.setMainUnitPath(unit.absolutePath()); this.namespaceResolver = (<jsyaml.Project>project).namespaceResolver(); } expandHighLevelNode( hlNode:hl.IHighLevelNode, rp:referencePatcher.ReferencePatcher, api:hl.IHighLevelNode, forceExpand=false) { this.init(hlNode); (<hlimpl.ASTNodeImpl>hlNode).setMergeMode((<hlimpl.ASTNodeImpl>api).getMergeMode()); var templateApplied = false; var llNode = hlNode.lowLevel(); if(proxy.LowLevelCompositeNode.isInstance(llNode)) { var resources = extractResources(llNode); resources.forEach(x=> templateApplied = this.processResource(x) || templateApplied); } if(!(templateApplied||forceExpand||hlNode.getMaster()!=null)){ return null; } if(hlimpl.ASTNodeImpl.isInstance(hlNode)) { var hnode = <hlimpl.ASTNodeImpl>hlNode; if(hnode.reusedNode()!=null) { hnode.setReuseMode(true); } } if (this.ramlVersion=="RAML10") { rp = rp || new referencePatcher.ReferencePatcher(); rp.process(llNode); llNode.actual().referencePatcher = rp; } return hlNode; } // private getTemplate<T extends core.BasicNode>( // name:string, // context:hl.IHighLevelNode, // cache:{[key:string]:{[key:string]:T}}, // globalList:T[]):T{ // // var unitPath = context.lowLevel().unit().path(); // var unitCache = cache[unitPath]; // if(!unitCache){ // unitCache = {}; // cache[unitPath] = unitCache; // } // var val = unitCache[name]; // // if(val!==undefined){ // return val; // } // val = null; // val = _.find(globalList,x=>hlimpl.qName(x.highLevel(),context)==name); // if(!val){ // val = null; // } // unitCache[name] = val; // return val; // } public createHighLevelNode( _api:hl.IHighLevelNode, merge:boolean=true, rp:referencePatcher.ReferencePatcher = null, forceProxy=false, doInit=true):hl.IHighLevelNode { if(doInit) { this.init(_api); } var api = <hlimpl.ASTNodeImpl>_api; var highLevelNodes:hlimpl.ASTNodeImpl[] = []; var node = api; while(node) { var llNode:ll.ILowLevelASTNode = node.lowLevel(); var topComposite:ll.ILowLevelASTNode; var fLine = hlimpl.ramlFirstLine(llNode.unit().contents()); if ((fLine && (fLine.length<3 || fLine[2] != def.universesInfo.Universe10.Overlay.name)) || forceProxy){ if(proxy.LowLevelCompositeNode.isInstance(llNode)){ llNode = (<proxy.LowLevelCompositeNode>(<proxy.LowLevelCompositeNode>llNode).originalNode()).originalNode(); } topComposite = new proxy.LowLevelCompositeNode( llNode, null, null, this.ramlVersion); } else{ topComposite = llNode; } var nodeType = node.definition(); var newNode = new hlimpl.ASTNodeImpl(topComposite, null, <any>nodeType, null); newNode.setUniverse(node.universe()); highLevelNodes.push(newNode); if(!merge){ break; } var extNode = _.find(llNode.children(),x=>x.key()==def.universesInfo.Universe10.Overlay.properties.extends.name); if(extNode){} node = <hlimpl.ASTNodeImpl>node.getMaster(); } var masterApi = highLevelNodes.pop(); highLevelNodes = highLevelNodes.reverse(); var mergeMode = api.getMergeMode(); var result = mergeHighLevelNodes(masterApi,highLevelNodes, mergeMode, rp, forceProxy); (<hlimpl.ASTNodeImpl>result).setReusedNode(api.reusedNode()); return result; } private processResource(resource:proxy.LowLevelCompositeNode,_nodes:ll.ILowLevelASTNode[]=[]):boolean { var result = false; var nodes = _nodes.concat(resource); var resourceData:ResourceGenericData[] = this.collectResourceData(resource,resource,undefined,undefined,nodes); if(!proxy.LowLevelProxyNode.isInstance(resource)){ return result; } resource.preserveAnnotations(); resource.takeOnlyOriginalChildrenWithKey( def.universesInfo.Universe10.ResourceBase.properties.type.name); resource.takeOnlyOriginalChildrenWithKey( def.universesInfo.Universe10.FragmentDeclaration.properties.uses.name); resourceData.filter(x=>x.resourceType!=null).forEach(x=> { var resourceTypeLowLevel = <proxy.LowLevelCompositeNode>x.resourceType.node; var resourceTypeTransformer = x.resourceType.transformer; resourceTypeTransformer.owner = resource; resource.adopt(resourceTypeLowLevel, resourceTypeTransformer); result = true; }); let methods = resource.children().filter(x=>isPossibleMethodName(x.key())); for(var m of methods){ let name = m.key(); m.takeOnlyOriginalChildrenWithKey( def.universesInfo.Universe10.FragmentDeclaration.properties.uses.name); var allTraits:GenericData[]=[] resourceData.forEach(x=>{ var methodTraits = x.methodTraits[name]; if(methodTraits){ allTraits = allTraits.concat(methodTraits); methodTraits.forEach(x=>{ var traitLowLevel = x.node; var traitTransformer = x.transformer; traitTransformer.owner = m; m.adopt(traitLowLevel,traitTransformer); result = true; }); } else { } var resourceTraits = x.traits; if(resourceTraits){ allTraits = allTraits.concat(resourceTraits); resourceTraits.forEach(x=> { var traitLowLevel = x.node; var traitTransformer = x.transformer; traitTransformer.owner = m; m.adopt(traitLowLevel, traitTransformer); result = true; }); } }); // if(resource.definition().universe().version()=="RAML10") { // this.appendTraitReferences(m, allTraits); // } }; var resources = extractResources(resource); resources.forEach(x=>result = this.processResource(x,nodes) || result); methods.forEach(x=>this.mergeBodiesForMethod(x)); return result; } private mergeBodiesForMethod(method: proxy.LowLevelCompositeNode) { let llNode = method; if (!proxy.LowLevelCompositeNode.isInstance(llNode)) { return; } if (this.defaultMediaType == null) { return; } let bodyNode: proxy.LowLevelCompositeNode; let bodyNodesArray: proxy.LowLevelCompositeNode[] = []; let llChildren = llNode.children(); for(var ch of llChildren){ if(ch.key()==def.universesInfo.Universe10.Method.properties.body.name){ bodyNode = ch; } else if(ch.key()==def.universesInfo.Universe10.Method.properties.responses.name){ let responses = ch.children(); for(var response of responses){ let responseChildren = response.children(); for(var respCh of responseChildren){ if(respCh.key()==def.universesInfo.Universe10.Response.properties.body.name){ bodyNodesArray.push(respCh); } } } } } if(bodyNode){ bodyNodesArray.push(bodyNode); } for(var n of bodyNodesArray){ this.mergeBodies(n); } } private mergeBodies(bodyNode:proxy.LowLevelCompositeNode):boolean{ let explicitCh:proxy.LowLevelCompositeNode; let implicitPart:proxy.LowLevelCompositeNode[] = [], otherMediaTypes:proxy.LowLevelCompositeNode[] = []; let newAdopted:{node:ll.ILowLevelASTNode,transformer:proxy.ValueTransformer}[] = []; let map:ll.ILowLevelASTNode[] = []; let gotImplicitPart = false; for(let ch of bodyNode.children()){ let key = ch.key(); if(key==this.defaultMediaType){ explicitCh = ch; newAdopted.push({node:referencePatcher.toOriginal(ch),transformer:ch.transformer()}); } else { try{ parseMediaType(key); otherMediaTypes.push(ch); } catch(e){ let oParent = referencePatcher.toOriginal(ch).parent(); if(map.indexOf(oParent)<0) { newAdopted.push({node:oParent,transformer:ch.transformer()}); map.push(oParent); } if(sufficientTypeAttributes[ch.key()]){ gotImplicitPart = true; } implicitPart.push(ch); } } } if(implicitPart.length==0||(explicitCh==null&&otherMediaTypes.length==0)){ return false; } if(!gotImplicitPart) { return; } for(let ch of implicitPart){ bodyNode.removeChild(ch); } if(explicitCh==null){ let oNode = referencePatcher.toOriginal(bodyNode); let mapping = yaml.newMapping(yaml.newScalar(this.defaultMediaType),yaml.newMap([])); let newNode = new jsyaml.ASTNode(mapping,oNode.unit(),<jsyaml.ASTNode>oNode,null,null); explicitCh = bodyNode.replaceChild(null,newNode); } explicitCh.patchAdoptedNodes(newAdopted); return true; } private collectResourceData( original:ll.ILowLevelASTNode, obj:ll.ILowLevelASTNode, arr:ResourceGenericData[] = [], transformer?:ValueTransformer, nodesChain:ll.ILowLevelASTNode[]=[], occuredResourceTypes:{[key:string]:boolean}={}):ResourceGenericData[] { nodesChain = nodesChain.concat([obj]); var ownTraits = this.extractTraits(obj,transformer,nodesChain); var methodTraitsMap:{[key:string]:GenericData[]} = {}; for(var ch of obj.children()) { var mName = ch.key(); if(!isPossibleMethodName(mName)){ continue; } var methodTraits = this.extractTraits(ch, transformer, nodesChain); if (methodTraits && methodTraits.length > 0) { methodTraitsMap[mName] = methodTraits; } } var rtData:GenericData; var rtRef = _.find(obj.children(),x=>x.key()==def.universesInfo.Universe10.ResourceBase.properties.type.name); if(rtRef!=null) { var units = toUnits1(nodesChain); if(rtRef.valueKind() == yaml.Kind.SCALAR){ rtRef = jsyaml.createScalar(rtRef.value()); } rtData = this.readGenerictData(original, rtRef, obj, 'resource type', transformer, units); } var result = { resourceType:rtData, traits:ownTraits, methodTraits:methodTraitsMap }; arr.push(result); if(rtData) { var rt = rtData.node; var qName = rt.key() + "/" + rt.unit().absolutePath(); if(!occuredResourceTypes[qName]) { occuredResourceTypes[qName] = true; this.collectResourceData( original, rt, arr, rtData.transformer, nodesChain, occuredResourceTypes); } else{ result.resourceType = null; } } return arr; } private extractTraits(obj:ll.ILowLevelASTNode, _transformer:ValueTransformer, nodesChain:ll.ILowLevelASTNode[], occuredTraits:{[key:string]:boolean} = {}):GenericData[] { nodesChain = nodesChain.concat([obj]); var arr:GenericData[] = []; for (var i = -1; i < arr.length ; i++){ var gd:GenericData = i < 0 ? null : arr[i]; var _obj = gd ? gd.node : obj; var units = gd ? gd.unitsChain : toUnits1(nodesChain); var transformer:ValueTransformer = gd ? gd.transformer : _transformer; for(var x of _obj.children().filter(x=>x.key()==def.universesInfo.Universe10.MethodBase.properties.is.name)){ for(var y of x.children()){ var unitsChain = toUnits2(units, y); var traitData = this.readGenerictData(obj, y, _obj, 'trait', transformer, unitsChain); if (traitData) { var name = traitData.name; //if (!occuredTraits[name]) { occuredTraits[name] = true; arr.push(traitData); //} } } }; } return arr; } private readGenerictData(r:ll.ILowLevelASTNode,obj:ll.ILowLevelASTNode, context:ll.ILowLevelASTNode, template:string, transformer:ValueTransformer, unitsChain:ll.ICompilationUnit[]=[]):GenericData { let value = <any>obj.value(); if(!value){ return; } let name:string; let propName = pluralize.plural(changeCase.camelCase(template)); let hasParams = false; if (typeof(value) == 'string') { name = value; } else if(jsyaml.ASTNode.isInstance(value)||proxy.LowLevelProxyNode.isInstance(value)) { hasParams = true; name = (<ll.ILowLevelASTNode>value).key(); } else{ return null; } if(!name){ return null; } if (transformer) { name = transformer.transform(name).value; } let scalarParamValues:{[key:string]:string} = {}; let scalarParams:{[key:string]:ll.ILowLevelASTNode} = {}; let structuredParams:{[key:string]:ll.ILowLevelASTNode} = {}; let node = getDeclaration(name, propName, this.namespaceResolver, unitsChain); if (node) { let ds = new DefaultTransformer(<any>r, null, unitsChain); if (hasParams) { if (this.ramlVersion == 'RAML08') { (<ll.ILowLevelASTNode>value).children().forEach(x=>scalarParamValues[x.key()] = x.value()); } else { for(let x of (<ll.ILowLevelASTNode>value).children()){ let llNode = referencePatcher.toOriginal(x); let resolvedValueKind = x.resolvedValueKind(); if (resolvedValueKind == yaml.Kind.SCALAR||resolvedValueKind) { scalarParamValues[x.key()] = llNode.value(); scalarParams[x.key()] = llNode; } else { structuredParams[x.key()] = llNode; } }; } Object.keys(scalarParamValues).forEach(x=> { let q = ds.transform(scalarParamValues[x]); //if (q.value){ if (q) { if (typeof q !== "object") { scalarParamValues[x] = q; } } //} }); } let valTransformer = new ValueTransformer( template, name, unitsChain, scalarParamValues, scalarParams, structuredParams, transformer); let resourceTypeTransformer = new DefaultTransformer(null, valTransformer, unitsChain); return { name: name, transformer: resourceTypeTransformer, parentTransformer: transformer, node: node, ref: obj, unitsChain: unitsChain }; } return null; } // // private appendTraitReferences( // m:hl.IHighLevelNode, // traits:GenericData[]){ // // if(traits.length==0){ // return; // } // // var traitsData = traits.map(x=>{ // return { // node: x.ref.lowLevel(), // transformer: x.parentTransformer // }; // }); // referencePatcher.patchMethodIs(m,traitsData); // } } export class LibraryExpander{ expandLibraries(_api:hl.IHighLevelNode):hl.IHighLevelNode{ var api = _api; if(api==null){ return null; } if(!universeHelpers.isApiSibling(_api.definition())){ return null; } if(proxy.LowLevelCompositeNode.isInstance(api.lowLevel())){ api = api.lowLevel().unit().highLevel().asElement(); } var expander = new TraitsAndResourceTypesExpander(); var rp = new referencePatcher.ReferencePatcher(); var hlNode:hl.IHighLevelNode = expander.createHighLevelNode(api,true,rp,true); var result = expander.expandHighLevelNode(hlNode, rp, api,true); this.processNode(rp,result); return result; } expandLibrary(_lib:hl.IHighLevelNode):hl.IHighLevelNode{ let lib = _lib; if(lib==null){ return null; } // if(proxy.LowLevelCompositeNode.isInstance(lib.lowLevel())){ // lib = lib.lowLevel().unit().highLevel().asElement(); // } let expander = new TraitsAndResourceTypesExpander(); let rp = new referencePatcher.ReferencePatcher(); let hlNode:hl.IHighLevelNode = expander.createHighLevelNode(lib,true,rp,true); let llNode = <proxy.LowLevelCompositeNode>hlNode.lowLevel(); rp.process(llNode); rp.expandLibraries(llNode,true); return hlNode; } processNode(rp:referencePatcher.ReferencePatcher, hlNode:hl.IHighLevelNode){ if(hlNode==null){ return; } var master = <hl.IHighLevelNode>(<hlimpl.ASTNodeImpl>hlNode).getMaster(); this.processNode(rp,master); var llNode = hlNode.lowLevel(); var fLine = hlimpl.ramlFirstLine(llNode.unit().contents()); if(fLine.length==3&&fLine[2]=="Overlay"){ rp.process(llNode); } rp.expandLibraries(<proxy.LowLevelCompositeNode>llNode); } } function toUnits1(nodes:ll.ILowLevelASTNode[]):ll.ICompilationUnit[]{ var result:ll.ICompilationUnit[] = []; for(var n of nodes){ toUnits2(result,n,true); } return result; } function toUnits2(chainStart:ll.ICompilationUnit[], node:ll.ILowLevelASTNode, append:boolean=false):ll.ICompilationUnit[]{ var result = append ? chainStart : chainStart.concat([]); var unit = node.unit(); if(unit==null){ return result; } if(result.length==0){ result.push(unit); } else{ var prevPath = result[result.length-1].absolutePath(); if(unit.absolutePath()!=prevPath){ result.push(unit); } } return result; } export function toUnits(node:ll.ILowLevelASTNode):ll.ICompilationUnit[]{ var nodes:ll.ILowLevelASTNode[] = []; while(node){ nodes.push(node); node = node.parent(); } return toUnits1(nodes); } class TransformMatches { name: string; regexp: RegExp; static leftTransformRegexp: RegExp = /\s*!\s*/; static rightTransformRegexp: RegExp = /\s*$/; transformer: (arg: string) => string; constructor(name, transformer: (string) => string) { this.name = name; this.regexp = new RegExp(TransformMatches.leftTransformRegexp.source + name + TransformMatches.rightTransformRegexp.source); this.transformer = transformer; } } var transformers: TransformMatches[] = [ new TransformMatches("singularize", (arg: string) => pluralize.singular(arg)), new TransformMatches("pluralize", (arg: string) => pluralize.plural(arg)), new TransformMatches("uppercase", (arg: string) => arg ? arg.toUpperCase() : arg), new TransformMatches("lowercase", (arg: string) => arg ? arg.toLowerCase() : arg), new TransformMatches("lowercamelcase", (arg: string) => { if(!arg) { return arg; } return changeCase.camelCase(arg); }), new TransformMatches("uppercamelcase", (arg: string) => { if(!arg) { return arg; } var lowerCamelCase = changeCase.camelCase(arg); return lowerCamelCase[0].toUpperCase() + lowerCamelCase.substring(1, lowerCamelCase.length); }), new TransformMatches("lowerunderscorecase", (arg: string) => { if(!arg) { return arg; } var snakeCase = changeCase.snakeCase(arg); return snakeCase.toLowerCase(); }), new TransformMatches("upperunderscorecase", (arg: string) => { if(!arg) { return arg; } var snakeCase = changeCase.snakeCase(arg); return snakeCase.toUpperCase(); }), new TransformMatches("lowerhyphencase", (arg: string) => { if(!arg) { return arg; } var paramCase = changeCase.paramCase(arg); return paramCase.toLowerCase(); }), new TransformMatches("upperhyphencase", (arg: string) => { if(!arg) { return arg; } var paramCase = changeCase.paramCase(arg); return paramCase.toUpperCase(); }), new TransformMatches("sentencecase", (arg: string) => { if(!arg) { return arg; } var result = changeCase.sentenceCase(arg); return result[0].toUpperCase() + result.substring(1); }) ]; export function getTransformNames(): string[] { return transformers.map(transformer => transformer.name); } export function getTransformersForOccurence(occurence: string) { var result = []; var functions = occurence.split("|").slice(1); for(var f of functions) { for (var i = 0; i < transformers.length; i++) { if (f.match(transformers[i].regexp)) { result.push(transformers[i].transformer); break; } } } return result; } class TransformationBuffer{ buf:any = null; append(value:any){ if(value !== "") { if (this.buf != null) { if (value != null) { if (typeof(this.buf) != "string") { this.buf = "" + this.buf; } this.buf += value; } } else if (value !== "") { this.buf = value; } } } value():any{ return this.buf != null ? this.buf : ""; } } export class ValueTransformer implements proxy.ValueTransformer{ constructor( public templateKind:string, public templateName:string, public unitsChain: ll.ICompilationUnit[], public scalarParamValues?:{[key:string]:string}, public scalarParams?:{[key:string]:ll.ILowLevelASTNode}, public structuredParams?:{[key:string]:ll.ILowLevelASTNode}, public vDelegate?:ValueTransformer){ } transform( obj:any, toString?:boolean, doBreak?:()=>boolean, callback?:(obj:any,transformer:DefaultTransformer)=>any){ var undefParams:{[key:string]:boolean} = {}; var errors:hl.ValidationIssue[] = []; if(typeof(obj)==='string'){ if(this.structuredParams&&util.stringStartsWith(obj,"<<")&&util.stringEndsWith(obj,">>")){ let paramName = obj.substring(2,obj.length-2); var structuredValue = this.structuredParams[paramName]; if(structuredValue!=null){ return { value:structuredValue, errors: errors }; } } var str:string = <string>obj; var buf = new TransformationBuffer(); var prev = 0; for(var i = str.indexOf('<<'); i >=0 ; i = str.indexOf('<<',prev)){ buf.append(str.substring(prev,i)); var i0 = i; i += '<<'.length; prev = this.paramUpperBound(str, i); if (prev==-1){ break; } var paramOccurence = str.substring(i,prev); prev += '>>'.length; var originalString = str.substring(i0,prev); var val; let paramName:string; var transformers = getTransformersForOccurence(paramOccurence); if(transformers.length>0) { var ind = paramOccurence.indexOf('|'); paramName = paramOccurence.substring(0,ind).trim(); val = this.scalarParamValues[paramName]; if(val && typeof(val) == "string" && val.indexOf("<<")>=0&&this.vDelegate){ val = this.vDelegate.transform(val,toString,doBreak,callback).value; } if(val) { if(referencePatcherHL.PatchedReference.isInstance(val)){ val = (<referencePatcherHL.PatchedReference>val).value(); } for(var tr of transformers) { val = tr(val); } } } else { paramName = paramOccurence.trim(); val = this.scalarParamValues[paramName]; if(val && typeof(val) == "string" && val.indexOf("<<")>=0&&this.vDelegate){ val = this.vDelegate.transform(val,toString,doBreak,callback).value; } } if(val===null||val===undefined){ undefParams[paramName] = true; val = originalString; } buf.append(val); } // var upArr = Object.keys(undefParams); // if(upArr.length>0){ // var errStr = upArr.join(', ').trim(); // var message = `Undefined ${this.templateKind} parameter${upArr.length>1?'s':''}: ${errStr}`; // var error = { // code: hl.IssueCode.MISSING_REQUIRED_PROPERTY, // isWarning: false, // message: message, // node: null, // start: -1, // end: -1, // path: null // } // errors.push(error); // } buf.append(str.substring(prev,str.length)); return { value:buf.value(), errors: errors }; } else{ return { value:obj, errors: errors }; } } private paramUpperBound(str:string, pos:number) { var count = 0; for(var i = pos; i < str.length ;i ++){ if(util.stringStartsWith(str,"<<",i)){ count++; i++; } else if(util.stringStartsWith(str,">>",i)){ if(count==0){ return i; } count--; i++; } } return str.length; } children(node:ll.ILowLevelASTNode):ll.ILowLevelASTNode[]{ var substitution = this.substitutionNode(node); if(substitution){ return substitution.children(); } return null; } valueKind(node:ll.ILowLevelASTNode):yaml.Kind{ var substitution = this.substitutionNode(node); if(substitution){ return substitution.valueKind(); } return null; } anchorValueKind(node:ll.ILowLevelASTNode):yaml.Kind{ var substitution = this.substitutionNode(node); if(substitution && substitution.valueKind()==yaml.Kind.ANCHOR_REF){ return substitution.anchorValueKind(); } return null; } resolvedValueKind(node:ll.ILowLevelASTNode):yaml.Kind{ var substitution = this.substitutionNode(node); return substitution && substitution.resolvedValueKind(); } includePath(node:ll.ILowLevelASTNode):string{ var substitution = this.substitutionNode(node); if(substitution){ return substitution.includePath(); } return null; } substitutionNode(node:ll.ILowLevelASTNode,chain:ll.ILowLevelASTNode[]=[],inKey=false) { var paramName = this.paramName(node,inKey); let result = paramName && (this.scalarParams[paramName]||this.structuredParams[paramName]); if(!result){ return null; } chain.push(result); if(this.vDelegate){ return this.vDelegate.substitutionNode(result,chain) || result; } return result; } paramNodesChain(node:ll.ILowLevelASTNode,inKey:boolean):ll.ILowLevelASTNode[]{ let chain:ll.ILowLevelASTNode[]=[]; this.substitutionNode(referencePatcher.toOriginal(node),chain,inKey); return chain.length > 0 ? chain : null; } private paramName(node:ll.ILowLevelASTNode,inKey:boolean):string { let val:string; if(inKey){ if (node.kind() == yaml.Kind.MAPPING) { val = ("" + node.key()).trim(); } } else { if (node.valueKind() == yaml.Kind.SCALAR) { val = ("" + node.value()).trim(); } } let paramName:string; if (val) { if (util.stringStartsWith(val, "(") && util.stringEndsWith(val, ")")) { val = val.substring(1,val.length-1); } if (util.stringStartsWith(val, "<<") && util.stringEndsWith(val, ">>")) { paramName = val.substring(2, val.length - 2); } } return paramName; } definingUnitSequence(str:string){ if(str.length<2){ return null; } if(str.charAt(0)=="("&&str.charAt(str.length-1)==")"){ str = str.substring(1,str.length-1); } if(str.length<4){ return null; } if(str.substring(0,2)!="<<"){ return null; } if(str.substring(str.length-2,str.length)!=">>"){ return null; } let _str = str.substring(2,str.length-2); if(_str.indexOf("<<")>=0||_str.indexOf(">>")>=0){ return null; } return this._definingUnitSequence(_str); } _definingUnitSequence(str:string):ll.ICompilationUnit[]{ if(this.scalarParamValues && this.scalarParamValues[str]){ return this.unitsChain; } if(this.vDelegate){ return this.vDelegate._definingUnitSequence(str); } return null; } } export class DefaultTransformer extends ValueTransformer{ constructor( public owner:proxy.LowLevelCompositeNode, public delegate: ValueTransformer, unitsChain:ll.ICompilationUnit[] ){ super(delegate!=null?delegate.templateKind:"",delegate!=null?delegate.templateName:"",unitsChain); } transform( obj:any, toString?:boolean, doContinue?:()=>boolean, callback?:(obj:any,transformer:DefaultTransformer)=>any){ if(obj==null||(doContinue!=null&&!doContinue())){ return { value:obj, errors: [] } } var ownResult:{ value:any; errors:hl.ValidationIssue[] } = { value:obj, errors: [] }; var gotDefaultParam = false; defaultParameters.forEach(x=>gotDefaultParam = gotDefaultParam || obj.toString().indexOf('<<'+x)>=0); if(gotDefaultParam) { this.initParams(); ownResult = super.transform(obj,toString,doContinue,callback); } var result = this.delegate != null ? this.delegate.transform(ownResult.value,toString,doContinue,callback) : ownResult.value; if(doContinue!=null&&doContinue()&&callback!=null){ result.value = callback(result.value,this); } return result; } private initParams(){ var methodName:string; var resourcePath:string = ""; var resourcePathName:string; var ll=this.owner; var node = ll; var last=null; while(node){ var key = node.key(); if(key!=null) { if (util.stringStartsWith(key, '/')) { if (!resourcePathName) { var arr = key.split('/'); for (var i=arr.length-1;i>=0;i--){ var seg=arr[i]; if (seg.indexOf('{')==-1){ resourcePathName = arr[i]; break; } if (seg.length>0) { last = seg; } } } resourcePath = key + resourcePath; } else { methodName = key; } } node = node.parent(); } if (!resourcePathName){ if (last){ resourcePathName=""; } } this.scalarParamValues = { resourcePath: resourcePath, resourcePathName: resourcePathName }; if(methodName){ this.scalarParamValues['methodName'] = methodName; } } children(node:ll.ILowLevelASTNode):ll.ILowLevelASTNode[]{ return this.delegate != null ? this.delegate.children(node) : null; } valueKind(node:ll.ILowLevelASTNode):yaml.Kind{ return this.delegate != null ? this.delegate.valueKind(node) : null; } includePath(node:ll.ILowLevelASTNode):string{ return this.delegate != null ? this.delegate.includePath(node) : null; } anchorValueKind(node:ll.ILowLevelASTNode):yaml.Kind{ return this.delegate != null ? this.delegate.anchorValueKind(node) : null; } resolvedValueKind(node:ll.ILowLevelASTNode):yaml.Kind{ return this.delegate != null ? this.delegate.resolvedValueKind(node) : null; } substitutionNode(node:ll.ILowLevelASTNode,chain:ll.ILowLevelASTNode[]=[],inKey=false) { return this.delegate ? this.delegate.substitutionNode(node,chain,inKey) : null; } _definingUnitSequence(str:string):ll.ICompilationUnit[]{ if(this.scalarParamValues && this.scalarParamValues[str]){ return this.unitsChain; } if(this.delegate){ return this.delegate._definingUnitSequence(str); } return null; } } interface GenericData{ node:ll.ILowLevelASTNode; ref:ll.ILowLevelASTNode; name:string; transformer:DefaultTransformer; parentTransformer:ValueTransformer; unitsChain:ll.ICompilationUnit[]; } interface ResourceGenericData{ resourceType:GenericData traits:GenericData[] methodTraits:{[key:string]:GenericData[]} } var defaultParameters = [ 'resourcePath', 'resourcePathName', 'methodName' ]; var possibleMethodNames; export function isPossibleMethodName(n:string){ if(!possibleMethodNames){ possibleMethodNames = {}; var methodType = def.getUniverse("RAML10").type(def.universesInfo.Universe10.Method.name); for(var opt of methodType.property(def.universesInfo.Universe10.Method.properties.method.name).enumOptions()){ possibleMethodNames[opt] = true; } } return possibleMethodNames[n]; } function getDeclaration( elementName:string, propName:string, resolver:namespaceResolver.NamespaceResolver, _units:ll.ICompilationUnit[]):ll.ILowLevelASTNode{ if(!elementName){ return null; } var ns = ""; var name = elementName; var ind = elementName.lastIndexOf("."); if(ind>=0){ ns = elementName.substring(0,ind); name = elementName.substring(ind+1); } var result:ll.ILowLevelASTNode; var gotLibrary = false; var units:ll.ICompilationUnit[] = _units; for(var i = units.length ; i > 0 ; i--){ var u = units[i-1]; var fLine = hlimpl.ramlFirstLine(u.contents()); var className = fLine && fLine.length==3 && fLine[2]; if(className==def.universesInfo.Universe10.Library.name){ if (gotLibrary) { break; } gotLibrary = true; } var actualUnit = u; if(ns){ actualUnit = null; var map = resolver.nsMap(u); if(map) { var info = map[ns]; if (info) { actualUnit = info.unit; } } } if(!actualUnit){ continue; } var uModel = resolver.unitModel(actualUnit); var c = <namespaceResolver.ElementsCollection>uModel[propName]; if(!namespaceResolver.ElementsCollection.isInstance(c)){ continue; } result = c.getElement(name); if(result){ break; } if(i==1){ if(className==def.universesInfo.Universe10.Extension.name || className==def.universesInfo.Universe10.Overlay.name){ let extendedUnit = namespaceResolver.extendedUnit(u); if(extendedUnit){ i++; _units[0] = extendedUnit; } } } } return result; } function extractResources(llNode:proxy.LowLevelCompositeNode):proxy.LowLevelCompositeNode[] { var resources = llNode.children().filter(x=> { var key = x.key(); return key && (key.length > 0) && (key.charAt(0) == "/"); }); return resources; }; const sufficientTypeAttributes:any = {}; sufficientTypeAttributes[def.universesInfo.Universe10.TypeDeclaration.properties.type.name] = true; sufficientTypeAttributes[def.universesInfo.Universe10.TypeDeclaration.properties.example.name] = true; sufficientTypeAttributes[def.universesInfo.Universe08.BodyLike.properties.schema.name] = true; sufficientTypeAttributes[def.universesInfo.Universe10.ObjectTypeDeclaration.properties.properties.name] = true; export function parseMediaType(str:string){ if (!str){ return null; } if (str == "*/*") { return null; } if (str.indexOf("/*")==str.length-2){ str=str.substring(0,str.length-2)+"/xxx"; } return mediaTypeParser.parse(str); }
the_stack
import AceConfig from "@wowts/ace_config-3.0"; import AceConfigDialog from "@wowts/ace_config_dialog-3.0"; import { l } from "./Localization"; import AceDB, { AceDatabase } from "@wowts/ace_db-3.0"; import AceDBOptions from "@wowts/ace_db_options-3.0"; import aceConsole, { AceConsole } from "@wowts/ace_console-3.0"; import aceEvent, { AceEvent } from "@wowts/ace_event-3.0"; import { InterfaceOptionsFrame_OpenToCategory } from "@wowts/wow-mock"; import { ipairs, LuaObj, lualength, LuaArray } from "@wowts/lua"; import { huge } from "@wowts/math"; import { Color } from "./SpellFlash"; import { OvaleClass } from "../Ovale"; import { AceModule } from "@wowts/tsaddon"; import { printFormat } from "../tools/tools"; import { OptionUiGroup } from "./acegui-helpers"; interface OptionModule { upgradeSavedVariables(): void; } const optionModules: LuaObj<OptionModule> = {}; export interface SpellFlashOptions { enabled: boolean; colors: { colorMain: Color; colorCd: Color; colorShortCd: Color; colorInterrupt: Color; }; inCombat?: boolean; hideInVehicle?: boolean; hasTarget?: boolean; hasHostileTarget?: boolean; threshold: number; size: number; brightness: number; } export interface ApparenceOptions { avecCible: boolean; clickThru: boolean; enCombat: boolean; enableIcons: boolean; hideEmpty: boolean; hideVehicule: boolean; margin: number; offsetX: number; offsetY: number; targetHostileOnly: boolean; verrouille: boolean; vertical: boolean; alpha: number; flashIcon: boolean; remainsFontColor: { r: number; g: number; b: number; }; fontScale: number; highlightIcon: true; iconScale: number; numeric: false; raccourcis: true; smallIconScale: number; targetText: string; iconShiftX: number; iconShiftY: number; numberOfIcons: number; optionsAlpha: number; secondIconScale: number; taggedEnemies: boolean; minFrameRefresh: number; maxFrameRefresh: number; fullAuraScan: false; frequentHealthUpdates: true; auraLag: number; moving: boolean; spellFlash: SpellFlashOptions; minimap: { hide: boolean; }; } export interface OvaleDb { profile: { source: LuaObj<string>; code: string; check: LuaObj<boolean>; list: LuaObj<string>; standaloneOptions: boolean; showHiddenScripts: boolean; overrideCode?: string; apparence: ApparenceOptions; }; global: { debug: LuaObj<boolean>; profiler: LuaObj<boolean>; }; } export class OvaleOptionsClass { db!: AceDatabase & OvaleDb; defaultDB: OvaleDb = { profile: { source: {}, code: "", showHiddenScripts: false, overrideCode: undefined, check: {}, list: {}, standaloneOptions: false, apparence: { avecCible: false, clickThru: false, enCombat: false, enableIcons: true, hideEmpty: false, hideVehicule: false, margin: 4, offsetX: 0, offsetY: 0, targetHostileOnly: false, verrouille: false, vertical: false, alpha: 1, flashIcon: true, remainsFontColor: { r: 1, g: 1, b: 1, }, fontScale: 1, highlightIcon: true, iconScale: 1, numeric: false, raccourcis: true, smallIconScale: 0.8, targetText: "●", iconShiftX: 0, iconShiftY: 0, optionsAlpha: 1, secondIconScale: 1, taggedEnemies: false, minFrameRefresh: 50, maxFrameRefresh: 250, fullAuraScan: false, frequentHealthUpdates: true, auraLag: 400, moving: false, numberOfIcons: 1, spellFlash: { enabled: true, brightness: 1, hasHostileTarget: false, hasTarget: false, hideInVehicle: false, inCombat: false, size: 2.4, threshold: 500, colors: { colorMain: { r: 1, g: 1, b: 1, }, colorShortCd: { r: 1, g: 1, b: 0, }, colorCd: { r: 1, g: 1, b: 0, }, colorInterrupt: { r: 0, g: 1, b: 1, }, }, }, minimap: { hide: false, }, }, }, global: { debug: {}, profiler: {}, }, }; actions: OptionUiGroup = { name: "Actions", type: "group", args: { show: { type: "execute", name: l["show_frame"], guiHidden: true, func: () => { this.db.profile.apparence.enableIcons = true; this.module.SendMessage( "Ovale_OptionChanged", "visibility" ); }, }, hide: { type: "execute", name: l["hide_frame"], guiHidden: true, func: () => { this.db.profile.apparence.enableIcons = false; this.module.SendMessage( "Ovale_OptionChanged", "visibility" ); }, }, config: { name: "Configuration", type: "execute", func: () => { this.toggleConfig(); }, }, refresh: { name: l["display_refresh_statistics"], type: "execute", func: () => { let [avgRefresh, minRefresh, maxRefresh, count] = this.ovale.getRefreshIntervalStatistics(); if (minRefresh == huge) { [avgRefresh, minRefresh, maxRefresh, count] = [ 0, 0, 0, 0, ]; } printFormat( "Refresh intervals: count = %d, avg = %d, min = %d, max = %d (ms)", count, avgRefresh, minRefresh, maxRefresh ); }, }, }, }; apparence: OptionUiGroup = { name: "Ovale Spell Priority", type: "group", get: (info: LuaArray<keyof ApparenceOptions>) => { return this.db.profile.apparence[info[lualength(info)]]; }, set: <T extends keyof ApparenceOptions>( info: LuaArray<T>, value: ApparenceOptions[T] ) => { this.db.profile.apparence[info[lualength(info)]] = value; this.module.SendMessage( "Ovale_OptionChanged", info[lualength(info) - 1] ); }, args: { standaloneOptions: { order: 30, name: l["standalone_options"], desc: l["movable_configuration_pannel"], type: "toggle", get: () => { return this.db.profile.standaloneOptions; }, set: (info: LuaArray<string>, value: boolean) => { this.db.profile.standaloneOptions = value; }, }, iconGroupAppearance: { order: 40, type: "group", name: l["icon_group"], args: { enableIcons: { order: 10, type: "toggle", name: l["enabled"], width: "full", set: (info: LuaArray<string>, value: boolean) => { this.db.profile.apparence.enableIcons = value; this.module.SendMessage( "Ovale_OptionChanged", "visibility" ); }, }, verrouille: { order: 10, type: "toggle", name: l["lock_position"], disabled: () => { return !this.db.profile.apparence.enableIcons; }, }, clickThru: { order: 20, type: "toggle", name: l["ignore_mouse_clicks"], disabled: () => { return !this.db.profile.apparence.enableIcons; }, }, visibility: { order: 20, type: "group", name: l["visibility"], inline: true, disabled: () => { return !this.db.profile.apparence.enableIcons; }, args: { enCombat: { order: 10, type: "toggle", name: l["combat_only"], }, avecCible: { order: 20, type: "toggle", name: l["if_target"], }, targetHostileOnly: { order: 30, type: "toggle", name: l["hide_if_dead_or_friendly_target"], }, hideVehicule: { order: 40, type: "toggle", name: l["hide_in_vehicles"], }, hideEmpty: { order: 50, type: "toggle", name: l["hide_empty_buttons"], }, }, }, layout: { order: 30, type: "group", name: l["layout"], inline: true, disabled: () => { return !this.db.profile.apparence.enableIcons; }, args: { moving: { order: 10, type: "toggle", name: l["scrolling"], desc: l["scrolling_help"], }, vertical: { order: 20, type: "toggle", name: l["vertical"], }, offsetX: { order: 30, type: "range", name: l["horizontal_offset"], desc: l["horizontal_offset_help"], min: -1000, max: 1000, softMin: -500, softMax: 500, bigStep: 1, }, offsetY: { order: 40, type: "range", name: l["vertical_offset"], desc: l["vertical_offset_help"], min: -1000, max: 1000, softMin: -500, softMax: 500, bigStep: 1, }, margin: { order: 50, type: "range", name: l["margin_between_icons"], min: -16, max: 64, step: 1, }, }, }, }, }, iconAppearance: { order: 50, type: "group", name: l["icon"], args: { iconScale: { order: 10, type: "range", name: l["icon_scale"], desc: l["icon_scale"], min: 0.5, max: 3, bigStep: 0.01, isPercent: true, }, smallIconScale: { order: 20, type: "range", name: l["small_icon_scale"], desc: l["small_icon_scale_help"], min: 0.5, max: 3, bigStep: 0.01, isPercent: true, }, remainsFontColor: { type: "color", order: 25, name: l["remaining_time_font_color"], get: () => { const t = this.db.profile.apparence.remainsFontColor; return [t.r, t.g, t.b]; }, set: ( info: LuaArray<string>, r: number, g: number, b: number ) => { const t = this.db.profile.apparence.remainsFontColor; [t.r, t.g, t.b] = [r, g, b]; this.db.profile.apparence.remainsFontColor = t; }, }, fontScale: { order: 30, type: "range", name: l["font_scale"], desc: l["font_scale_help"], min: 0.2, max: 2, bigStep: 0.01, isPercent: true, }, alpha: { order: 40, type: "range", name: l["icon_opacity"], min: 0, max: 1, bigStep: 0.01, isPercent: true, }, raccourcis: { order: 50, type: "toggle", name: l["keyboard_shortcuts"], desc: l["show_keyboard_shortcuts"], }, numeric: { order: 60, type: "toggle", name: l["show_cooldown"], desc: l["show_cooldown_help"], }, highlightIcon: { order: 70, type: "toggle", name: l["highlight_icon"], desc: l["highlight_icon_help"], }, flashIcon: { order: 80, type: "toggle", name: l["highlight_icon_on_cd"], }, targetText: { order: 90, type: "input", name: l["range_indicator"], desc: l["range_indicator_help"], }, }, }, optionsAppearance: { order: 60, type: "group", name: l["options"], args: { iconShiftX: { order: 10, type: "range", name: l["options_horizontal_shift"], min: -256, max: 256, step: 1, }, iconShiftY: { order: 20, type: "range", name: l["options_vertical_shift"], min: -256, max: 256, step: 1, }, optionsAlpha: { order: 30, type: "range", name: l["option_opacity"], min: 0, max: 1, bigStep: 0.01, isPercent: true, }, }, }, predictiveIcon: { order: 70, type: "group", name: l["predictiveIcon"], args: { numberOfIcons: { order: 10, type: "range", min: 1, max: 5, step: 1, name: l["numberOfIcons"], desc: l["numberOfIconsDesc"], }, secondIconScale: { order: 20, type: "range", name: l["second_icon_scale"], min: 0.2, max: 1, bigStep: 0.01, isPercent: true, }, }, }, advanced: { order: 80, type: "group", name: "Advanced", args: { taggedEnemies: { order: 10, type: "toggle", name: l["only_tagged"], desc: l["only_tagged_help"], }, auraLag: { order: 20, type: "range", name: l["aura_lag"], desc: l["lag_threshold"], min: 100, max: 700, step: 10, }, minFrameRefresh: { order: 30, type: "range", name: l["min_refresh"], desc: l["min_refresh_help"], min: 50, max: 100, step: 5, }, maxFrameRefresh: { order: 40, type: "range", name: l["max_refresh"], desc: l["min_refresh_help"], min: 100, max: 400, step: 10, }, fullAuraScan: { order: 50, width: "full", type: "toggle", name: l["scan_all_auras"], desc: l.scan_all_auras_help, }, frequentHealthUpdates: { order: 60, width: "full", type: "toggle", name: l["frequent_health_updates"], desc: l["frequent_health_updates_help"], }, }, }, }, }; options: OptionUiGroup = { type: "group", args: { apparence: this.apparence, actions: this.actions, profile: {} as OptionUiGroup, }, }; module: AceModule & AceConsole & AceEvent; constructor(private ovale: OvaleClass) { this.module = ovale.createModule( "OvaleOptions", this.handleInitialize, this.handleDisable, aceConsole, aceEvent ); } private handleInitialize = () => { const ovale = this.ovale.GetName(); this.db = AceDB.New("OvaleDB", this.defaultDB); const db = this.db; this.options.args.profile = AceDBOptions.GetOptionsTable(db); // let LibDualSpec = LibStub("LibDualSpec-1.0", true); // if (LibDualSpec) { // LibDualSpec.EnhanceDatabase(db, "Ovale"); // LibDualSpec.EnhanceOptions(this.options.args.profile, db); // } db.RegisterCallback(this, "OnNewProfile", this.handleProfileChanges); db.RegisterCallback(this, "OnProfileReset", this.handleProfileChanges); db.RegisterCallback( this, "OnProfileChanged", this.handleProfileChanges ); db.RegisterCallback(this, "OnProfileCopied", this.handleProfileChanges); this.upgradeSavedVariables(); AceConfig.RegisterOptionsTable(ovale, this.options.args.apparence); AceConfig.RegisterOptionsTable( `${ovale} Profiles`, this.options.args.profile ); AceConfig.RegisterOptionsTable( `${ovale} Actions`, this.options.args.actions, "Ovale" ); AceConfigDialog.AddToBlizOptions(ovale); AceConfigDialog.AddToBlizOptions( `${ovale} Profiles`, "Profiles", ovale ); this.handleProfileChanges(); }; private handleDisable = () => {}; registerOptions() { // tinsert(self_register, addon); } upgradeSavedVariables() { // const profile = Ovale.db.profile; // if (profile.display != undefined && _type(profile.display) == "boolean") { // profile.apparence.enableIcons = profile.display; // profile.display = undefined; // } // if (profile.left || profile.top) { // profile.left = undefined; // profile.top = undefined; // Ovale.OneTimeMessage("The Ovale icon frames position has been reset."); // } for (const [, addon] of ipairs(optionModules)) { if (addon.upgradeSavedVariables) { addon.upgradeSavedVariables(); } } this.db.RegisterDefaults(this.defaultDB); } private handleProfileChanges = () => { this.module.SendMessage("Ovale_ProfileChanged"); this.module.SendMessage("Ovale_ScriptChanged"); this.module.SendMessage("Ovale_OptionChanged", "layout"); this.module.SendMessage("Ovale_OptionChanged", "visibility"); }; toggleConfig() { const appName = this.ovale.GetName(); if (this.db.profile.standaloneOptions) { if (AceConfigDialog.OpenFrames[appName]) { AceConfigDialog.Close(appName); } else { AceConfigDialog.Open(appName); } } else { InterfaceOptionsFrame_OpenToCategory(appName); InterfaceOptionsFrame_OpenToCategory(appName); } } }
the_stack
import * as Context from './context'; import { EnterException, ExitException, within } from './context'; describe('Context', () => { describe('still calls `exit` when operation throws exception', () => { test('with sync `enter` and `exit`', () => { const context = { [Context.enter]: jest.fn(), [Context.exit]: jest.fn(), }; expect(() => { within(context, () => { throw Error('expected error'); }); }).toThrowError('expected error'); expect(context[Context.enter]).toHaveBeenCalledTimes(1); expect(context[Context.exit]).toHaveBeenCalledTimes(1); }); test('with async `enter`', async () => { const context = { [Context.enter]: jest.fn(async () => {}), [Context.exit]: jest.fn(), }; const result = within(context, () => { throw Error('expected error'); }); expect(context[Context.enter]).toHaveBeenCalledTimes(1); await expect(result).rejects.toThrowError('expected error'); expect(context[Context.exit]).toHaveBeenCalledTimes(1); }); test('with async `exit`', async () => { const context = { [Context.enter]: jest.fn(), [Context.exit]: jest.fn(async () => {}), }; const promise = within(context, () => { throw Error('expected error'); }); expect(context[Context.enter]).toHaveBeenCalledTimes(1); await expect(promise).rejects.toThrowError('expected error'); expect(context[Context.exit]).toHaveBeenCalledTimes(1); }); test('with async operation', async () => { const context = { [Context.enter]: jest.fn(), [Context.exit]: jest.fn(), }; const promise = within(context, async () => { throw Error('expected error'); }); expect(context[Context.enter]).toHaveBeenCalledTimes(1); await expect(promise).rejects.toThrowError('expected error'); expect(context[Context.exit]).toHaveBeenCalledTimes(1); }); }); /* eslint-disable jest/no-try-expect */ describe('operation and `exit` not called if `enter` throws exception', () => { test('with sync `enter` and `exit`', () => { const context = { [Context.enter]: () => { throw Error('expected error'); }, [Context.exit]: jest.fn(), }; const operation = jest.fn(); let exception: unknown; try { within(context, operation); throw Error('unreachable'); } catch (error) { expect(error).toBeInstanceOf(EnterException); ({ exception } = error); } expect(exception).toEqual(Error('expected error')); expect(operation).not.toHaveBeenCalled(); expect(context[Context.exit]).not.toHaveBeenCalled(); }); test('with async `enter`', async () => { const context = { [Context.enter]: jest.fn(async () => { throw Error('expected error'); }), [Context.exit]: jest.fn(), }; const operation = jest.fn(); const promise = within(context, operation); expect(context[Context.enter]).toHaveBeenCalledTimes(1); let exception: unknown; try { await promise; throw Error('unreachable'); } catch (error) { expect(error).toBeInstanceOf(EnterException); ({ exception } = error); } expect(exception).toEqual(Error('expected error')); expect(operation).not.toHaveBeenCalled(); expect(context[Context.exit]).not.toHaveBeenCalled(); }); test('with async `exit`', () => { const context = { [Context.enter]: () => { throw Error('expected error'); }, [Context.exit]: jest.fn(async () => {}), }; const operation = jest.fn(); // It would be nice if we were able to return a rejected promise // instead of throwing, but we have no way of knowing whether we // should do so without being able to call `exit`. let exception: unknown; try { within(context, operation); throw Error('unreachable'); } catch (error) { expect(error).toBeInstanceOf(EnterException); ({ exception } = error); } expect(exception).toEqual(Error('expected error')); expect(operation).not.toHaveBeenCalled(); expect(context[Context.exit]).not.toHaveBeenCalled(); }); test('with async operation', async () => { const context = { [Context.enter]: () => { throw Error('expected error'); }, [Context.exit]: jest.fn(), }; const operation = jest.fn(async () => {}); // It would be nice if we were able to return a rejected promise // instead of throwing, but we have no way of knowing whether we // should do so without being able to call the operation. let exception: unknown; try { within(context, operation); throw Error('unreachable'); } catch (error) { expect(error).toBeInstanceOf(EnterException); ({ exception } = error); } expect(exception).toEqual(Error('expected error')); expect(operation).not.toHaveBeenCalled(); expect(context[Context.exit]).not.toHaveBeenCalled(); }); }); describe('when `exit` throws exception', () => { test('with sync `enter` and `exit`', () => { const context = { [Context.enter]: jest.fn(), [Context.exit]: () => { throw Error('expected error'); }, }; let exception: unknown; let result: ExitException<number>['result']; try { within(context, () => 1); throw Error('unreachable'); } catch (error) { expect(error).toBeInstanceOf(ExitException); ({ exception, result } = error); } expect(context[Context.enter]).toHaveBeenCalledTimes(1); expect(exception).toEqual(Error('expected error')); expect(result).toEqual({ value: 1 }); }); test('with async `enter`', async () => { const context = { [Context.enter]: jest.fn(async () => {}), [Context.exit]: () => { throw Error('expected error'); }, }; const promise = within(context, () => 1); expect(context[Context.enter]).toHaveBeenCalledTimes(1); let exception: unknown; let result: ExitException<number>['result']; try { await promise; throw Error('unreachable'); } catch (error) { expect(error).toBeInstanceOf(ExitException); ({ exception, result } = error); } expect(exception).toEqual(Error('expected error')); expect(result).toEqual({ value: 1 }); }); test('with async `exit`', async () => { const context = { [Context.enter]: jest.fn(), [Context.exit]: async () => { throw Error('expected error'); }, }; const promise = within(context, () => 1); expect(context[Context.enter]).toHaveBeenCalledTimes(1); let exception: unknown; let result: ExitException<number>['result']; try { await promise; throw Error('unreachable'); } catch (error) { expect(error).toBeInstanceOf(ExitException); ({ exception, result } = error); } expect(exception).toEqual(Error('expected error')); expect(result).toEqual({ value: 1 }); }); test('with async operation', async () => { const context = { [Context.enter]: jest.fn(), [Context.exit]: () => { throw Error('expected error'); }, }; const promise = within(context, async () => 1); expect(context[Context.enter]).toHaveBeenCalledTimes(1); let exception: unknown; let result: ExitException<number>['result']; try { await promise; throw Error('unreachable'); } catch (error) { expect(error).toBeInstanceOf(ExitException); ({ exception, result } = error); } expect(exception).toEqual(Error('expected error')); expect(result).toEqual({ value: 1 }); }); }); describe('when operation and `exit` throws exception', () => { test('with sync `enter` and `exit`', () => { const context = { [Context.enter]: jest.fn(), [Context.exit]: () => { throw Error('expected error'); }, }; let exception: unknown; let result: ExitException<number>['result']; try { within(context, () => { throw Error('operation error'); }); throw Error('unreachable'); } catch (error) { expect(error).toBeInstanceOf(ExitException); ({ exception, result } = error); } expect(context[Context.enter]).toHaveBeenCalledTimes(1); expect(exception).toEqual(Error('expected error')); expect(result).toEqual({ exception: Error('operation error') }); }); test('with async `enter`', async () => { const context = { [Context.enter]: jest.fn(async () => {}), [Context.exit]: () => { throw Error('expected error'); }, }; const promise = within(context, () => { throw Error('operation error'); }); expect(context[Context.enter]).toHaveBeenCalledTimes(1); let exception: unknown; let result: ExitException<number>['result']; try { await promise; throw Error('unreachable'); } catch (error) { expect(error).toBeInstanceOf(ExitException); ({ exception, result } = error); } expect(exception).toEqual(Error('expected error')); expect(result).toEqual({ exception: Error('operation error') }); }); test('with async `exit`', async () => { const context = { [Context.enter]: jest.fn(), [Context.exit]: async () => { throw Error('expected error'); }, }; const promise = within(context, () => { throw Error('operation error'); }); expect(context[Context.enter]).toHaveBeenCalledTimes(1); let exception: unknown; let result: ExitException<number>['result']; try { await promise; throw Error('unreachable'); } catch (error) { expect(error).toBeInstanceOf(ExitException); ({ exception, result } = error); } expect(exception).toEqual(Error('expected error')); expect(result).toEqual({ exception: Error('operation error') }); }); test('with async operation', async () => { const context = { [Context.enter]: jest.fn(), [Context.exit]: () => { throw Error('expected error'); }, }; const promise = within(context, async () => { throw Error('operation error'); }); expect(context[Context.enter]).toHaveBeenCalledTimes(1); let exception: unknown; let result: ExitException<number>['result']; try { await promise; throw Error('unreachable'); } catch (error) { expect(error).toBeInstanceOf(ExitException); ({ exception, result } = error); } expect(exception).toEqual(Error('expected error')); expect(result).toEqual({ exception: Error('operation error') }); }); }); /* eslint-enable jest/no-try-expect */ describe('types', () => { let isNumber: number; let isPromise: PromiseLike<number>; test('with sync `enter`', async () => { const context = { [Context.enter]: () => {}, }; isNumber = within(context, () => 1); expect(isNumber).toEqual(1); isPromise = within(context, async () => 1); await expect(isPromise).resolves.toEqual(1); }); test('with async `enter`', async () => { const context = { [Context.enter]: async () => {}, }; isPromise = within(context, () => 1); await expect(isPromise).resolves.toEqual(1); isPromise = within(context, async () => 1); await expect(isPromise).resolves.toEqual(1); }); test('with sync `exit`', async () => { const context = { [Context.enter]: () => {}, [Context.exit]: () => {}, }; isNumber = within(context, () => 1); expect(isNumber).toEqual(1); isPromise = within(context, async () => 1); await expect(isPromise).resolves.toEqual(1); }); test('with async `exit`', async () => { const context = { [Context.enter]: () => {}, [Context.exit]: async () => {}, }; isPromise = within(context, () => 1); await expect(isPromise).resolves.toEqual(1); isPromise = within(context, async () => 1); await expect(isPromise).resolves.toEqual(1); }); test('with sync `enter` and `exit`', async () => { const context = { [Context.enter]: () => {}, [Context.exit]: () => {}, }; isNumber = within(context, () => 1); expect(isNumber).toEqual(1); isPromise = within(context, async () => 1); await expect(isPromise).resolves.toEqual(1); }); test('with async `enter` and `exit`', async () => { const context = { [Context.enter]: async () => {}, [Context.exit]: async () => {}, }; isPromise = within(context, () => 1); await expect(isPromise).resolves.toEqual(1); isPromise = within(context, async () => 1); await expect(isPromise).resolves.toEqual(1); }); /* eslint-disable jest/expect-expect, jest/no-disabled-tests */ test.skip('Missing `enter`', () => { within( // @ts-expect-error {}, () => 1, ); within( // @ts-expect-error {}, async () => 1, ); within( // @ts-expect-error { [Context.exit]: () => {}, }, () => 1, ); within( // @ts-expect-error { [Context.exit]: () => {}, }, async () => 1, ); within( // @ts-expect-error { [Context.exit]: async () => {}, }, () => 1, ); within( // @ts-expect-error { [Context.exit]: async () => {}, }, async () => 1, ); }); describe.skip('Context handle types', () => { test('are consistent', () => { within( { [Context.enter]: () => 'hello', }, (handle: string) => handle, ); within( { [Context.enter]: async () => 'hello', }, (handle: string) => handle, ); within( { [Context.enter]: () => 'hello', // eslint-disable-next-line @typescript-eslint/no-unused-vars [Context.exit]: (handle: string) => {}, }, (handle: string) => handle, ); within( { [Context.enter]: () => 'hello', // eslint-disable-next-line @typescript-eslint/no-unused-vars [Context.exit]: async (handle: string) => {}, }, (handle: string) => handle, ); }); test('error when `enter` and `exit` disagree', () => { within( { [Context.enter]: () => true, // @ts-expect-error [Context.exit]: (handle: string) => handle, }, (handle: string) => handle, ); within( { [Context.enter]: () => true, // @ts-expect-error [Context.exit]: (handle: string) => handle, }, async (handle: string) => handle, ); within( { [Context.enter]: () => 'hello', // @ts-expect-error [Context.exit]: (handle: boolean) => handle, }, (handle: string) => handle, ); within( { [Context.enter]: () => 'hello', // @ts-expect-error [Context.exit]: (handle: boolean) => handle, }, async (handle: string) => handle, ); }); test('error when `enter` and provided function disagree', () => { within( { [Context.enter]: () => {}, }, // @ts-expect-error (handle: string) => handle, ); within( { [Context.enter]: async () => {}, }, // @ts-expect-error (handle: string) => handle, ); within( { [Context.enter]: () => true, }, // @ts-expect-error (handle: string) => handle, ); within( { [Context.enter]: () => 'hello', // eslint-disable-next-line @typescript-eslint/no-unused-vars [Context.exit]: (handle: string) => {}, }, // @ts-expect-error (handle: number) => handle, ); within( { [Context.enter]: () => 'hello', // eslint-disable-next-line @typescript-eslint/no-unused-vars [Context.exit]: (handle: string) => {}, }, // @ts-expect-error async (handle: number) => handle, ); }); }); /* eslint-enable jest/expect-expect, jest/no-disabled-tests */ }); });
the_stack
import DSLFilterTypes from "../../../js/constants/DSLFilterTypes"; import DSLFilter from "../../../js/structs/DSLFilter"; import DSLCombinerTypes from "../../../js/constants/DSLCombinerTypes"; import List from "../../../js/structs/List"; import SearchDSL from "../SearchDSL"; // Handles 'attrib:?' class AttribFilter extends DSLFilter { filterCanHandle(filterType, filterArguments) { return ( filterType === DSLFilterTypes.ATTRIB && filterArguments.label === "attrib" ); } filterApply(resultset, filterType, filterArguments) { return resultset.filterItems( (item) => item.attrib.indexOf(filterArguments.text) !== -1 ); } } // Handles 'text' class FuzzyTextFilter extends DSLFilter { filterCanHandle(filterType) { return filterType === DSLFilterTypes.FUZZY; } filterApply(resultset, filterType, filterArguments) { return resultset.filterItems( (item) => item.text.indexOf(filterArguments.text) !== -1 ); } } // Handles '"text"' class ExactTextFilter extends DSLFilter { filterCanHandle(filterType) { return filterType === DSLFilterTypes.EXACT; } filterApply(resultset, filterType, filterArguments) { return resultset.filterItems((item) => item.text === filterArguments.text); } } let thisFilters, thisMockResultset; describe("SearchDSL", () => { describe("Metadata", () => { describe("Filters (Operands)", () => { it("parses fuzzy text", () => { const expr = SearchDSL.parse("fuzzy"); expect(expr.ast.filterType).toEqual(DSLFilterTypes.FUZZY); expect(expr.ast.filterParams.text).toEqual("fuzzy"); }); it("parses exact text", () => { const expr = SearchDSL.parse('"exact string"'); expect(expr.ast.filterType).toEqual(DSLFilterTypes.EXACT); expect(expr.ast.filterParams.text).toEqual("exact string"); }); it("parses attributes", () => { const expr = SearchDSL.parse("attrib:value"); expect(expr.ast.filterType).toEqual(DSLFilterTypes.ATTRIB); expect(expr.ast.filterParams.text).toEqual("value"); expect(expr.ast.filterParams.label).toEqual("attrib"); }); }); describe("Combiners (Operators)", () => { it("uses AND operator by default", () => { const expr = SearchDSL.parse("text1 text2"); expect(expr.ast.combinerType).toEqual(DSLCombinerTypes.AND); }); it("uses OR operator", () => { const expr = SearchDSL.parse("text1, text2"); expect(expr.ast.combinerType).toEqual(DSLCombinerTypes.OR); }); it("uses OR shorthand operator on attrib", () => { // NOTE: attrib:value1,value2 becomes -> attrib:value1, attrib:value2 const expr = SearchDSL.parse("attrib:value1,value2"); expect(expr.ast.combinerType).toEqual(DSLCombinerTypes.OR); expect(expr.ast.children[0].filterType).toEqual(DSLFilterTypes.ATTRIB); expect(expr.ast.children[0].filterParams.text).toEqual("value1"); expect(expr.ast.children[0].filterParams.label).toEqual("attrib"); expect(expr.ast.children[1].filterType).toEqual(DSLFilterTypes.ATTRIB); expect(expr.ast.children[1].filterParams.text).toEqual("value2"); expect(expr.ast.children[1].filterParams.label).toEqual("attrib"); }); it("handles OR shorthand + OR with other operands", () => { // NOTE: attrib:value1,value2 becomes -> attrib:value1, attrib:value2 const expr = SearchDSL.parse("attrib:value1,value2, foo"); expect(expr.ast.combinerType).toEqual(DSLCombinerTypes.OR); expect(expr.ast.children[0].combinerType).toEqual(DSLCombinerTypes.OR); expect(expr.ast.children[0].children[0].filterType).toEqual( DSLFilterTypes.ATTRIB ); expect(expr.ast.children[0].children[0].filterParams.text).toEqual( "value1" ); expect(expr.ast.children[0].children[0].filterParams.label).toEqual( "attrib" ); expect(expr.ast.children[0].children[1].filterType).toEqual( DSLFilterTypes.ATTRIB ); expect(expr.ast.children[0].children[1].filterParams.text).toEqual( "value2" ); expect(expr.ast.children[0].children[1].filterParams.label).toEqual( "attrib" ); expect(expr.ast.children[1].filterType).toEqual(DSLFilterTypes.FUZZY); expect(expr.ast.children[1].filterParams.text).toEqual("foo"); }); it("populates children", () => { const expr = SearchDSL.parse("text1 text2"); expect(expr.ast.children[0].filterType).toEqual(DSLFilterTypes.FUZZY); expect(expr.ast.children[0].filterParams.text).toEqual("text1"); expect(expr.ast.children[1].filterType).toEqual(DSLFilterTypes.FUZZY); expect(expr.ast.children[1].filterParams.text).toEqual("text2"); }); }); describe("Complex expressions", () => { it("nests operations in correct order", () => { const expr = SearchDSL.parse( "text1 text2, (text3 (text4 text5), text6)" ); // . : [text1 text2] OR [(text3 (text4 text5), text6)] expect(expr.ast.combinerType).toEqual(DSLCombinerTypes.OR); // .0 : [text1] AND [text2] expect(expr.ast.children[0].combinerType).toEqual(DSLCombinerTypes.AND); // .0.0 : text1 expect(expr.ast.children[0].children[0].filterType).toEqual( DSLFilterTypes.FUZZY ); expect(expr.ast.children[0].children[0].filterParams.text).toEqual( "text1" ); // .0.1 : text2 expect(expr.ast.children[0].children[1].filterType).toEqual( DSLFilterTypes.FUZZY ); expect(expr.ast.children[0].children[1].filterParams.text).toEqual( "text2" ); // .1 : [text3 (text4 text5)] OR [text6] expect(expr.ast.children[1].combinerType).toEqual(DSLCombinerTypes.OR); // .1.0 : [text3] AND [text4 text5] expect(expr.ast.children[1].children[0].combinerType).toEqual( DSLCombinerTypes.AND ); // .1.0.0 : text3 expect(expr.ast.children[1].children[0].children[0].filterType).toEqual( DSLFilterTypes.FUZZY ); expect( expr.ast.children[1].children[0].children[0].filterParams.text ).toEqual("text3"); // .1.0.1 : [text4] AND [text5] expect( expr.ast.children[1].children[0].children[1].combinerType ).toEqual(DSLCombinerTypes.AND); // .1.0.1.0: text4 expect( expr.ast.children[1].children[0].children[1].children[0].filterType ).toEqual(DSLFilterTypes.FUZZY); expect( expr.ast.children[1].children[0].children[1].children[0].filterParams .text ).toEqual("text4"); // .1.0.1.1: text5 expect( expr.ast.children[1].children[0].children[1].children[1].filterType ).toEqual(DSLFilterTypes.FUZZY); expect( expr.ast.children[1].children[0].children[1].children[1].filterParams .text ).toEqual("text5"); // .1.1 : text6 expect(expr.ast.children[1].children[1].filterType).toEqual( DSLFilterTypes.FUZZY ); expect(expr.ast.children[1].children[1].filterParams.text).toEqual( "text6" ); }); }); describe("Token positions", () => { it("tracks location of fuzzy text", () => { const expr = SearchDSL.parse("fuzzy"); expect(expr.ast.position).toEqual([[0, 5]]); }); it("tracks location of exact text", () => { const expr = SearchDSL.parse('"exact string"'); expect(expr.ast.position).toEqual([[0, 14]]); }); it("tracks location of attrib", () => { const expr = SearchDSL.parse("attrib:value"); expect(expr.ast.position).toEqual([ [0, 7], [7, 12], ]); }); it("tracks location of attrib with multi values", () => { const expr = SearchDSL.parse("attrib:value1,value2"); expect(expr.ast.children[1].position).toEqual([ [0, 7], [14, 20], ]); }); }); describe("Filtering", () => { beforeEach(() => { thisFilters = [ new AttribFilter(), new FuzzyTextFilter(), new ExactTextFilter(), ]; thisMockResultset = new List({ items: [ { text: "some test string", attrib: ["a", "b"] }, { text: "repeating test string", attrib: ["b", "c"] }, { text: "some other string", attrib: ["c", "d"] }, ], }); }); it("filters by fuzzy match", () => { const expr = SearchDSL.parse("test"); expect(expr.filter(thisFilters, thisMockResultset).getItems()).toEqual([ { text: "some test string", attrib: ["a", "b"] }, { text: "repeating test string", attrib: ["b", "c"] }, ]); }); it("filters by exact match", () => { const expr = SearchDSL.parse('"some other string"'); expect(expr.filter(thisFilters, thisMockResultset).getItems()).toEqual([ { text: "some other string", attrib: ["c", "d"] }, ]); }); it("filters by attribute", () => { const expr = SearchDSL.parse("attrib:b"); expect(expr.filter(thisFilters, thisMockResultset).getItems()).toEqual([ { text: "some test string", attrib: ["a", "b"] }, { text: "repeating test string", attrib: ["b", "c"] }, ]); }); it("combines with OR operator with multi-value attr", () => { const expr = SearchDSL.parse("attrib:a,b"); expect(expr.filter(thisFilters, thisMockResultset).getItems()).toEqual([ { text: "some test string", attrib: ["a", "b"] }, { text: "repeating test string", attrib: ["b", "c"] }, ]); }); it("combines with OR operator multiple attr", () => { const expr = SearchDSL.parse("attrib:a, attrib:b"); expect(expr.filter(thisFilters, thisMockResultset).getItems()).toEqual([ { text: "some test string", attrib: ["a", "b"] }, { text: "repeating test string", attrib: ["b", "c"] }, ]); }); it("combines with AND operator multiple attr", () => { const expr = SearchDSL.parse("attrib:a attrib:b"); expect(expr.filter(thisFilters, thisMockResultset).getItems()).toEqual([ { text: "some test string", attrib: ["a", "b"] }, ]); }); it("combines with AND operator multiple attr", () => { const expr = SearchDSL.parse("attrib:a attrib:b"); expect(expr.filter(thisFilters, thisMockResultset).getItems()).toEqual([ { text: "some test string", attrib: ["a", "b"] }, ]); }); }); }); });
the_stack
import { createSelector, MemoizedSelector } from '@ngrx/store'; import { denormalize, schema } from 'normalizr'; import { NormalizeActionTypes } from '../actions/normalize'; import { NormalizeChildActionPayload, NormalizeRemoveChildActionPayload } from '../index'; /** * The state key under which the normalized state will be stored */ const STATE_KEY = 'normalized'; /** * Interface describing the entities propery of a normalized state. * A map of schema keys wich map to a map of entity id's to entity data. * This corresponds to the `entities` property of a `normalizr.normalize` result. */ export interface EntityMap { [key: string]: { [id: string]: any }; } /** * The state interface from which the app state should extend. * Holds an instance of `NormalizedEntityState` itself. */ export interface NormalizedState { /** The normalized state property */ normalized: NormalizedEntityState; } /** * The normalized state, representing a `normalizr.normalize` result. * Can be selected by the provided `getNormalizedEntities` and `getResult` * selectors. */ export interface NormalizedEntityState { /** * The original sorting of the unnormalized data. * Holds all id's of the last set operation in original order. * Can be used to restore the original sorting of entities */ result: string[]; /** * The normalized entities. Should be passed to all projector functions * to enable access to all entities needed. */ entities: EntityMap; } /** * The initial state for the normalized entity state. */ const initialState: NormalizedEntityState = { result: [], entities: {} }; /** * The normalizing reducer function which will handle actions with the types * `NormalizeActionTypes.SET_DATA`, `NormalizeActionTypes.ADD_DATA` and `NormalizeActionTypes.REMOVE_DATA`. * * On an `NormalizeActionTypes.SET_DATA` action: * * All entities and childs of the given schema will be replaced with the new entities. * * On an `NormalizeActionTypes.ADD_DATA` action: * * Entities are identified by their id attribute set in the schema passed by the payload. * Existing entities will be overwritten by updated data, new entities will be added to the store. * * On an `NormalizeActionTypes.REMOVE_DATA` action: * * Entities are identified by their id attribute set in the schema passed by the payload. * The entity with the passed id will be removed. If a `removeChildren` option is set in the action * payload, it is assumed as a map of schema keys to object property names. All referenced children * of the entity will be read by the object propety name and removed by the schema key. * * @param state The current state * @param action The dispatched action, one of `NormalizeActionTypes.ADD_DATA` or `NormalizeActionTypes.REMOVE_DATA`. */ export function normalized( state: NormalizedEntityState = initialState, action: any ) { switch (action.type) { case NormalizeActionTypes.SET_DATA: { const { result, entities } = action.payload; return { result, entities: { ...state.entities, ...entities } }; } case NormalizeActionTypes.ADD_DATA: { const { result, entities } = action.payload; return { result, entities: Object.keys(entities).reduce( (p: any, c: string) => { p[c] = { ...p[c], ...entities[c] }; return p; }, { ...state.entities } ) }; } case NormalizeActionTypes.ADD_CHILD_DATA: { const { result, entities, parentSchemaKey, parentProperty, parentId } = action.payload as NormalizeChildActionPayload; const newEntities = { ...state.entities }; /* istanbul ignore else */ if (getParentReferences(newEntities, action.payload)) { newEntities[parentSchemaKey][parentId][parentProperty].push(...result); } return { result, entities: Object.keys(entities).reduce((p: any, c: string) => { p[c] = { ...p[c], ...entities[c] }; return p; }, newEntities) }; } case NormalizeActionTypes.UPDATE_DATA: { const { id, key, changes, result } = action.payload; if (!state.entities[key] || !state.entities[key][id]) { return state; } const newEntities = { ...state.entities }; Object.entries(changes).forEach(([key, value]: [string, any]) => { Object.entries(changes[key]).forEach(([id, obj]: [string, any]) => { newEntities[key][id] = newEntities[key][id] || {}; Object.entries(changes[key][id]).forEach( ([property, value]: [string, any]) => { if (Array.isArray(value)) { newEntities[key][id][property].push(...value); } else { newEntities[key][id][property] = value; } } ); }); }); return { result, entities: newEntities }; } case NormalizeActionTypes.REMOVE_DATA: { const { id, key, removeChildren } = action.payload; const entities = { ...state.entities }; const entity = entities[key][id]; if (!entity) { return state; } if (removeChildren) { Object.entries(removeChildren).map( ([key, entityProperty]: [string, string]) => { const child = entity[entityProperty]; /* istanbul ignore else */ if (child && entities[key]) { const ids = Array.isArray(child) ? child : [child]; ids.forEach((oldId: string) => delete entities[key][oldId]); } } ); } delete entities[key][id]; return { result: state.result, entities }; } case NormalizeActionTypes.REMOVE_CHILD_DATA: { const { id, childSchemaKey, parentProperty, parentSchemaKey, parentId } = action.payload as NormalizeRemoveChildActionPayload; const newEntities = { ...state.entities }; const entity = newEntities[childSchemaKey][id]; /* istanbul ignore if */ if (!entity) { return state; } const parentRefs = getParentReferences(newEntities, action.payload); /* istanbul ignore else */ if (parentRefs && parentRefs.indexOf(id) > -1) { newEntities[parentSchemaKey][parentId][parentProperty].splice( parentRefs.indexOf(id), 1 ); } delete newEntities[childSchemaKey][id]; return { ...state, entities: newEntities }; } default: return state; } } /** * Default getter for the normalized state * @param state any state */ const getNormalizedState = (state: any): NormalizedEntityState => state[STATE_KEY]; /** * Selects all normalized entities of the state, regardless of their schema. * This selector should be used to enable denormalizing projector functions access * to all needed schema entities. */ export const getNormalizedEntities: MemoizedSelector< any, EntityMap > = createSelector( getNormalizedState, (state: NormalizedEntityState) => state.entities ); /** * Select the result order of the last set operation. */ export const getResult: MemoizedSelector<any, string[]> = createSelector( getNormalizedState, (state: NormalizedEntityState) => state.result ); /** * Generic interface for `createSchemaSelectors` return type. */ export interface SchemaSelectors<T> { getNormalizedEntities: MemoizedSelector<any, EntityMap>; getEntities: MemoizedSelector<{}, T[]>; entityProjector: (entities: {}, id: string) => T; entitiesProjector: (entities: {}) => T[]; } /** * Creates an object of selectors and projector functions bound to the given schema. * @param schema The schema to bind the selectors and projectors to */ export function createSchemaSelectors<T>( schema: schema.Entity ): SchemaSelectors<T> { return { /** * Select all entities, regardless of their schema, exported for convenience. */ getNormalizedEntities, /** * Select all entities and perform a denormalization based on the given schema. */ getEntities: createEntitiesSelector<T>(schema), /** * Uses the given schema to denormalize an entity by the given id */ entityProjector: createEntityProjector<T>(schema), /** * Uses the given schema to denormalize all given entities */ entitiesProjector: createEntitiesProjector<T>(schema) }; } /** * Create a schema bound selector which denormalizes all entities with the given schema. * @param schema The schema to bind this selector to */ function createEntitiesSelector<T>( schema: schema.Entity ): MemoizedSelector<{}, T[]> { return createSelector( getNormalizedEntities, createEntitiesProjector<T>(schema) ); } /** * Create a schema bound projector function to denormalize a single entity. * @param schema The schema to bind this selector to */ function createEntityProjector<T>(schema: schema.Entity) { return (entities: {}, id: string) => createSingleDenormalizer(schema)(entities, id) as T; } /** * Create a schema bound projector function to denormalize an object of normalized entities * @param schema The schema to bind this selector to */ function createEntitiesProjector<T>(schema: schema.Entity) { return (entities: {}, ids?: Array<string>) => createMultipleDenormalizer(schema)(entities, ids) as T[]; } /** * Create a schema bound denormalizer. * @param schema The schema to bind this selector to */ function createSingleDenormalizer(schema: schema.Entity) { const key = schema.key; return (entities: { [key: string]: {} }, id: string) => { /* istanbul ignore if */ if (!entities || !entities[key]) { return; } const denormalized = denormalize( { [key]: [id] }, { [key]: [schema] }, entities ); return denormalized[key][0]; }; } /** * Create a schema bound denormalizer. * @param schema The schema to bind this selector to */ function createMultipleDenormalizer(schema: schema.Entity) { const key = schema.key; return (entities: { [key: string]: {} }, ids?: Array<string>) => { /* istanbul ignore if */ if (!entities || !entities[key]) { return; } const data = ids ? { [key]: ids } : { [key]: Object.keys(entities[key]) }; const denormalized = denormalize(data, { [key]: [schema] }, entities); return denormalized[key]; }; } /** * @private * Get the reference array from the parent entity * @param entities normalized entity state object * @param payload NormalizeChildActionPayload */ function getParentReferences( entities: any, payload: NormalizeChildActionPayload ): string | undefined { const { parentSchemaKey, parentProperty, parentId } = payload; if ( entities[parentSchemaKey] && entities[parentSchemaKey][parentId] && entities[parentSchemaKey][parentId][parentProperty] && Array.isArray(entities[parentSchemaKey][parentId][parentProperty]) ) { return entities[parentSchemaKey][parentId][parentProperty]; } }
the_stack
export interface TestUtils { test: (name: string, fn: () => void) => void; assertEquals: (actual: any, expected: any, msg?: string) => void; } /** * Tests. * * @param {*} mod * @param {TestUtils} { test, assertEquals } */ export function beginTests(mod: any, { test, assertEquals }: TestUtils): void { test('KEY_CANCEL equals 3', () => { assertEquals(mod.KEY_CANCEL, 3); }); test('KEY_HELP equals 6', () => { assertEquals(mod.KEY_HELP, 6); }); test('KEY_BACK_SPACE equals 8', () => { assertEquals(mod.KEY_BACK_SPACE, 8); }); test('KEY_TAB equals 9', () => { assertEquals(mod.KEY_TAB, 9); }); test('KEY_CLEAR equals 12', () => { assertEquals(mod.KEY_CLEAR, 12); }); test('KEY_RETURN equals 13', () => { assertEquals(mod.KEY_RETURN, 13); }); test('KEY_SHIFT equals 16', () => { assertEquals(mod.KEY_SHIFT, 16); }); test('KEY_CONTROL equals 17', () => { assertEquals(mod.KEY_CONTROL, 17); }); test('KEY_ALT equals 18', () => { assertEquals(mod.KEY_ALT, 18); }); test('KEY_PAUSE equals 19', () => { assertEquals(mod.KEY_PAUSE, 19); }); test('KEY_CAPS_LOCK equals 20', () => { assertEquals(mod.KEY_CAPS_LOCK, 20); }); test('KEY_ESCAPE equals 27', () => { assertEquals(mod.KEY_ESCAPE, 27); }); test('KEY_SPACE equals 32', () => { assertEquals(mod.KEY_SPACE, 32); }); test('KEY_PAGE_UP equals 14', () => { assertEquals(mod.KEY_PAGE_UP, 33); }); test('KEY_PAGE_DOWN equals 34', () => { assertEquals(mod.KEY_PAGE_DOWN, 34); }); test('KEY_END equals 35', () => { assertEquals(mod.KEY_END, 35); }); test('KEY_HOME equals 36', () => { assertEquals(mod.KEY_HOME, 36); }); test('KEY_LEFT equals 37', () => { assertEquals(mod.KEY_LEFT, 37); }); test('KEY_UP equals 38', () => { assertEquals(mod.KEY_UP, 38); }); test('KEY_RIGHT equals 39', () => { assertEquals(mod.KEY_RIGHT, 39); }); test('KEY_DOWN equals 40', () => { assertEquals(mod.KEY_DOWN, 40); }); test('KEY_PRINTSCREEN equals 44', () => { assertEquals(mod.KEY_PRINTSCREEN, 44); }); test('KEY_INSERT equals 45', () => { assertEquals(mod.KEY_INSERT, 45); }); test('KEY_DELETE equals 46', () => { assertEquals(mod.KEY_DELETE, 46); }); test('KEY_0 equals 48', () => { assertEquals(mod.KEY_0, 48); }); test('KEY_1 equals 49', () => { assertEquals(mod.KEY_1, 49); }); test('KEY_2 equals 50', () => { assertEquals(mod.KEY_2, 50); }); test('KEY_3 equals 51', () => { assertEquals(mod.KEY_3, 51); }); test('KEY_4 equals 52', () => { assertEquals(mod.KEY_4, 52); }); test('KEY_5 equals 53', () => { assertEquals(mod.KEY_5, 53); }); test('KEY_6 equals 54', () => { assertEquals(mod.KEY_6, 54); }); test('KEY_7 equals 55', () => { assertEquals(mod.KEY_7, 55); }); test('KEY_8 equals 56', () => { assertEquals(mod.KEY_8, 56); }); test('KEY_9 equals 57', () => { assertEquals(mod.KEY_9, 57); }); test('KEY_A equals 65', () => { assertEquals(mod.KEY_A, 65); }); test('KEY_B equals 66', () => { assertEquals(mod.KEY_B, 66); }); test('KEY_C equals 67', () => { assertEquals(mod.KEY_C, 67); }); test('KEY_D equals 68', () => { assertEquals(mod.KEY_D, 68); }); test('KEY_E equals 69', () => { assertEquals(mod.KEY_E, 69); }); test('KEY_F equals 70', () => { assertEquals(mod.KEY_F, 70); }); test('KEY_G equals 71', () => { assertEquals(mod.KEY_G, 71); }); test('KEY_H equals 72', () => { assertEquals(mod.KEY_H, 72); }); test('KEY_I equals 73', () => { assertEquals(mod.KEY_I, 73); }); test('KEY_J equals 74', () => { assertEquals(mod.KEY_J, 74); }); test('KEY_K equals 75', () => { assertEquals(mod.KEY_K, 75); }); test('KEY_L equals 76', () => { assertEquals(mod.KEY_L, 76); }); test('KEY_M equals 77', () => { assertEquals(mod.KEY_M, 77); }); test('KEY_N equals 78', () => { assertEquals(mod.KEY_N, 78); }); test('KEY_O equals 79', () => { assertEquals(mod.KEY_O, 79); }); test('KEY_P equals 80', () => { assertEquals(mod.KEY_P, 80); }); test('KEY_Q equals 81', () => { assertEquals(mod.KEY_Q, 81); }); test('KEY_R equals 82', () => { assertEquals(mod.KEY_R, 82); }); test('KEY_S equals 83', () => { assertEquals(mod.KEY_S, 83); }); test('KEY_T equals 84', () => { assertEquals(mod.KEY_T, 84); }); test('KEY_U equals 85', () => { assertEquals(mod.KEY_U, 85); }); test('KEY_V equals 86', () => { assertEquals(mod.KEY_V, 86); }); test('KEY_W equals 87', () => { assertEquals(mod.KEY_W, 87); }); test('KEY_X equals 88', () => { assertEquals(mod.KEY_X, 88); }); test('KEY_Y equals 89', () => { assertEquals(mod.KEY_Y, 89); }); test('KEY_Z equals 90', () => { assertEquals(mod.KEY_Z, 90); }); test('KEY_LEFT_CMD equals 91', () => { assertEquals(mod.KEY_LEFT_CMD, 91); }); test('KEY_RIGHT_CMD equals 92', () => { assertEquals(mod.KEY_RIGHT_CMD, 92); }); test('KEY_CONTEXT_MENU equals 93', () => { assertEquals(mod.KEY_CONTEXT_MENU, 93); }); test('KEY_NUMPAD0 equals 96', () => { assertEquals(mod.KEY_NUMPAD0, 96); }); test('KEY_NUMPAD1 equals 97', () => { assertEquals(mod.KEY_NUMPAD1, 97); }); test('KEY_NUMPAD2 equals 98', () => { assertEquals(mod.KEY_NUMPAD2, 98); }); test('KEY_NUMPAD3 equals 99', () => { assertEquals(mod.KEY_NUMPAD3, 99); }); test('KEY_NUMPAD4 equals 100', () => { assertEquals(mod.KEY_NUMPAD4, 100); }); test('KEY_NUMPAD5 equals 101', () => { assertEquals(mod.KEY_NUMPAD5, 101); }); test('KEY_NUMPAD6 equals 102', () => { assertEquals(mod.KEY_NUMPAD6, 102); }); test('KEY_NUMPAD7 equals 103', () => { assertEquals(mod.KEY_NUMPAD7, 103); }); test('KEY_NUMPAD8 equals 104', () => { assertEquals(mod.KEY_NUMPAD8, 104); }); test('KEY_NUMPAD9 equals 105', () => { assertEquals(mod.KEY_NUMPAD9, 105); }); test('KEY_MULTIPLY equals 106', () => { assertEquals(mod.KEY_MULTIPLY, 106); }); test('KEY_ADD equals 107', () => { assertEquals(mod.KEY_ADD, 107); }); test('KEY_SUBTRACT equals 109', () => { assertEquals(mod.KEY_SUBTRACT, 109); }); test('KEY_DECIMAL equals 110', () => { assertEquals(mod.KEY_DECIMAL, 110); }); test('KEY_DIVIDE equals 111', () => { assertEquals(mod.KEY_DIVIDE, 111); }); test('KEY_F1 equals 112', () => { assertEquals(mod.KEY_F1, 112); }); test('KEY_F2 equals 113', () => { assertEquals(mod.KEY_F2, 113); }); test('KEY_F3 equals 114', () => { assertEquals(mod.KEY_F3, 114); }); test('KEY_F4 equals 115', () => { assertEquals(mod.KEY_F4, 115); }); test('KEY_F5 equals 116', () => { assertEquals(mod.KEY_F5, 116); }); test('KEY_F6 equals 117', () => { assertEquals(mod.KEY_F6, 117); }); test('KEY_F7 equals 118', () => { assertEquals(mod.KEY_F7, 118); }); test('KEY_F8 equals 119', () => { assertEquals(mod.KEY_F8, 119); }); test('KEY_F9 equals 120', () => { assertEquals(mod.KEY_F9, 120); }); test('KEY_F10 equals 121', () => { assertEquals(mod.KEY_F10, 121); }); test('KEY_F11 equals 122', () => { assertEquals(mod.KEY_F11, 122); }); test('KEY_F12 equals 123', () => { assertEquals(mod.KEY_F12, 123); }); test('KEY_F13 equals 124', () => { assertEquals(mod.KEY_F13, 124); }); test('KEY_F14 equals 125', () => { assertEquals(mod.KEY_F14, 125); }); test('KEY_F15 equals 126', () => { assertEquals(mod.KEY_F15, 126); }); test('KEY_F16 equals 127', () => { assertEquals(mod.KEY_F16, 127); }); test('KEY_F17 equals 128', () => { assertEquals(mod.KEY_F17, 128); }); test('KEY_F18 equals 129', () => { assertEquals(mod.KEY_F18, 129); }); test('KEY_F19 equals 130', () => { assertEquals(mod.KEY_F19, 130); }); test('KEY_F20 equals 131', () => { assertEquals(mod.KEY_F20, 131); }); test('KEY_F21 equals 132', () => { assertEquals(mod.KEY_F21, 132); }); test('KEY_F22 equals 133', () => { assertEquals(mod.KEY_F22, 133); }); test('KEY_F23 equals 134', () => { assertEquals(mod.KEY_F23, 134); }); test('KEY_F24 equals 135', () => { assertEquals(mod.KEY_F24, 135); }); test('KEY_NUM_LOCK equals 144', () => { assertEquals(mod.KEY_NUM_LOCK, 144); }); test('KEY_SCROLL_LOCK equals 145', () => { assertEquals(mod.KEY_SCROLL_LOCK, 145); }); test('KEY_SEMICOLON equals 186', () => { assertEquals(mod.KEY_SEMICOLON, 186); }); test('KEY_EQUALS equals 187', () => { assertEquals(mod.KEY_EQUALS, 187); }); test('KEY_COMMA equals 188', () => { assertEquals(mod.KEY_COMMA, 188); }); test('KEY_DASH equals 189', () => { assertEquals(mod.KEY_DASH, 189); }); test('KEY_PERIOD equals 190', () => { assertEquals(mod.KEY_PERIOD, 190); }); test('KEY_SLASH equals 191', () => { assertEquals(mod.KEY_SLASH, 191); }); test('KEY_BACK_QUOTE equals 192', () => { assertEquals(mod.KEY_BACK_QUOTE, 192); }); test('KEY_OPEN_BRACKET equals 219', () => { assertEquals(mod.KEY_OPEN_BRACKET, 219); }); test('KEY_BACK_SLASH equals 220', () => { assertEquals(mod.KEY_BACK_SLASH, 220); }); test('KEY_CLOSE_BRACKET equals 221', () => { assertEquals(mod.KEY_CLOSE_BRACKET, 221); }); test('KEY_QUOTE equals 222', () => { assertEquals(mod.KEY_QUOTE, 222); }); test('KEY_FIREFOX_ENTER equals 14', () => { assertEquals(mod.KEY_FIREFOX_ENTER, 14); }); test('KEY_FIREFOX_SEMICOLON equals 59', () => { assertEquals(mod.KEY_FIREFOX_SEMICOLON, 59); }); test('KEY_FIREFOX_EQUALS equals 61', () => { assertEquals(mod.KEY_FIREFOX_EQUALS, 61); }); test('KEY_FIREFOX_SEPARATOR equals 108', () => { assertEquals(mod.KEY_FIREFOX_SEPARATOR, 108); }); test('KEY_FIREFOX_META equals 224', () => { assertEquals(mod.KEY_FIREFOX_META, 224); }); }
the_stack
import { closestFacility } from "../src/closestFacility"; import * as fetchMock from "fetch-mock"; import { barriers, barriersFeatureSet, polylineBarriers, polygonBarriers, } from "./mocks/inputs"; import { ClosestFacility, ClosestFacilityWebMercator } from "./mocks/responses"; import { IPoint, ILocation, IFeatureSet, IPolyline, IPolygon, } from "@esri/arcgis-rest-types"; const incidents: Array<[number, number]> = [[-118.257363, 34.076763]]; const facilities: Array<[number, number]> = [ [-118.3417932, 34.00451385], [-118.08788, 34.01752], [-118.20327, 34.19382], ]; const incidentsLatLong: ILocation[] = [ { lat: 34.076763, long: -118.257363, }, ]; const facilitiesLatLong: ILocation[] = [ { lat: 34.00451385, long: -118.3417932, }, { lat: 34.01752, long: -118.08788, }, { lat: 34.19382, long: -118.20327, }, ]; const incidentsLatitudeLongitude: ILocation[] = [ { latitude: 34.076763, longitude: -118.257363, }, ]; const facilitiesLatitudeLongitude: ILocation[] = [ { latitude: 34.00451385, longitude: -118.3417932, }, { latitude: 34.01752, longitude: -118.08788, }, { latitude: 34.19382, longitude: -118.20327, }, ]; const incidentsPoint: IPoint[] = [ { x: -118.257363, y: 34.076763, }, ]; const facilitiesPoint: IPoint[] = [ { x: -118.3417932, y: 34.00451385, }, { x: -118.08788, y: 34.01752, }, { x: -118.20327, y: 34.19382, }, ]; const incidentsFeatureSet: IFeatureSet = { spatialReference: { wkid: 4326, }, features: [ { geometry: { x: -122.4079, y: 37.78356, } as IPoint, attributes: { Name: "Fire Incident 1", Attr_TravelTime: 4, }, }, { geometry: { x: -122.404, y: 37.782, } as IPoint, attributes: { Name: "Crime Incident 45", Attr_TravelTime: 5, }, }, ], }; const facilitiesFeatureSet: IFeatureSet = { spatialReference: { wkid: 4326, }, features: [ { geometry: { x: -122.4079, y: 37.78356, } as IPoint, attributes: { Name: "Fire Station 34", Attr_TravelTime: 4, }, }, { geometry: { x: -122.404, y: 37.782, } as IPoint, attributes: { Name: "Fire Station 29", Attr_TravelTime: 5, }, }, ], }; // const customRoutingUrl = // "https://foo.com/ArcGIS/rest/services/Network/USA/NAServer/"; describe("closestFacility", () => { afterEach(fetchMock.restore); it("should throw an error when a closestFacility request is made without a token", (done) => { fetchMock.once("*", ClosestFacility); closestFacility({ incidents, facilities, returnCFRoutes: true, }) // tslint:disable-next-line .catch((e) => { expect(e).toEqual( "Finding the closest facility using the ArcGIS service requires authentication" ); done(); }); }); it("should make a simple closestFacility request (Point Arrays)", (done) => { fetchMock.once("*", ClosestFacility); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; closestFacility({ incidents, facilities, returnCFRoutes: true, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(url).toEqual( "https://route.arcgis.com/arcgis/rest/services/World/ClosestFacility/NAServer/ClosestFacility_World/solveClosestFacility" ); expect(options.method).toBe("POST"); expect(options.body).toContain("f=json"); expect(options.body).toContain( `incidents=${encodeURIComponent("-118.257363,34.076763")}` ); expect(options.body).toContain( `facilities=${encodeURIComponent( "-118.3417932,34.00451385;-118.08788,34.01752;-118.20327,34.19382" )}` ); expect(options.body).toContain("token=token"); expect(response.routes.spatialReference.latestWkid).toEqual(4326); expect(response.routes.features[0].attributes.Name).toEqual( "Echo Park Ave & W Sunset Blvd, Los Angeles, California, 90026 - Flint Wash Trail" ); done(); }) .catch((e) => { fail(e); }); }); it("should pass default values", (done) => { fetchMock.once("*", ClosestFacility); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; closestFacility({ incidents, facilities, params: { outSR: 102100, }, returnCFRoutes: true, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain("returnDirections=true"); expect(options.body).toContain("returnFacilities=true"); expect(options.body).toContain("returnIncidents=true"); expect(options.body).toContain("returnBarriers=true"); expect(options.body).toContain("returnPolylineBarriers=true"); expect(options.body).toContain("returnPolygonBarriers=true"); expect(options.body).toContain("preserveObjectID=true"); expect(options.body).toContain("outSR=102100"); done(); }) .catch((e) => { fail(e); }); }); it("should allow default values to be overridden", (done) => { fetchMock.once("*", ClosestFacility); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; closestFacility({ incidents, facilities, returnCFRoutes: true, returnDirections: false, returnFacilities: false, returnIncidents: false, returnBarriers: false, returnPolylineBarriers: false, returnPolygonBarriers: false, preserveObjectID: false, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain("returnDirections=false"); expect(options.body).toContain("returnFacilities=false"); expect(options.body).toContain("returnIncidents=false"); expect(options.body).toContain("returnBarriers=false"); expect(options.body).toContain("returnPolylineBarriers=false"); expect(options.body).toContain("returnPolygonBarriers=false"); expect(options.body).toContain("preserveObjectID=false"); done(); }) .catch((e) => { fail(e); }); }); it("should make a simple closestFacility request (array of objects - lat/lon)", (done) => { fetchMock.once("*", ClosestFacility); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; closestFacility({ incidents: incidentsLatLong, facilities: facilitiesLatLong, returnCFRoutes: true, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( `incidents=${encodeURIComponent("-118.257363,34.076763")}` ); expect(options.body).toContain( `facilities=${encodeURIComponent( "-118.3417932,34.00451385;-118.08788,34.01752;-118.20327,34.19382" )}` ); done(); }) .catch((e) => { fail(e); }); }); it("should make a simple closestFacility request (array of objects - latitude/longitude)", (done) => { fetchMock.once("*", ClosestFacility); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; closestFacility({ incidents: incidentsLatitudeLongitude, facilities: facilitiesLatitudeLongitude, returnCFRoutes: true, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( `incidents=${encodeURIComponent("-118.257363,34.076763")}` ); expect(options.body).toContain( `facilities=${encodeURIComponent( "-118.3417932,34.00451385;-118.08788,34.01752;-118.20327,34.19382" )}` ); done(); }) .catch((e) => { fail(e); }); }); it("should make a simple closestFacility request (array of IPoint)", (done) => { fetchMock.once("*", ClosestFacility); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; closestFacility({ incidents: incidentsPoint, facilities: facilitiesPoint, returnCFRoutes: true, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( `incidents=${encodeURIComponent("-118.257363,34.076763")}` ); expect(options.body).toContain( `facilities=${encodeURIComponent( "-118.3417932,34.00451385;-118.08788,34.01752;-118.20327,34.19382" )}` ); done(); }) .catch((e) => { fail(e); }); }); it("should make a simple closestFacility request (FeatureSet)", (done) => { fetchMock.once("*", ClosestFacility); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; closestFacility({ incidents: incidentsFeatureSet, facilities: facilitiesFeatureSet, returnCFRoutes: true, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( `incidents=${encodeURIComponent(JSON.stringify(incidentsFeatureSet))}` ); expect(options.body).toContain( `facilities=${encodeURIComponent( JSON.stringify(facilitiesFeatureSet) )}` ); done(); }) .catch((e) => { fail(e); }); }); it("should include proper travelDirection", (done) => { fetchMock.once("*", ClosestFacility); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; closestFacility({ incidents: incidentsPoint, facilities: facilitiesPoint, returnCFRoutes: true, travelDirection: "facilitiesToIncidents", authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( `travelDirection=esriNATravelDirectionToFacility` ); done(); }) .catch((e) => { fail(e); }); }); it("should include proper travelDirection", (done) => { fetchMock.once("*", ClosestFacility); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; closestFacility({ incidents: incidentsPoint, facilities: facilitiesPoint, returnCFRoutes: true, travelDirection: "incidentsToFacilities", authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( `travelDirection=esriNATravelDirectionFromFacility` ); done(); }) .catch((e) => { fail(e); }); }); it("should pass point barriers (array of IPoint)", (done) => { fetchMock.once("*", ClosestFacility); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; closestFacility({ incidents: incidentsPoint, facilities: facilitiesPoint, returnCFRoutes: true, barriers, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( `barriers=${encodeURIComponent("-117.1957,34.0564;-117.184,34.0546")}` ); done(); }) .catch((e) => { fail(e); }); }); it("should pass point barriers (FeatureSet)", (done) => { fetchMock.once("*", ClosestFacility); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; closestFacility({ incidents: incidentsPoint, facilities: facilitiesPoint, returnCFRoutes: true, barriers: barriersFeatureSet, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( `barriers=${encodeURIComponent(JSON.stringify(barriersFeatureSet))}` ); done(); }) .catch((e) => { fail(e); }); }); it("should pass polyline barriers", (done) => { fetchMock.once("*", ClosestFacility); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; closestFacility({ incidents: incidentsPoint, facilities: facilitiesPoint, returnCFRoutes: true, polylineBarriers, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( `polylineBarriers=${encodeURIComponent( JSON.stringify(polylineBarriers) )}` ); done(); }) .catch((e) => { fail(e); }); }); it("should pass polygon barriers", (done) => { fetchMock.once("*", ClosestFacility); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; closestFacility({ incidents: incidentsPoint, facilities: facilitiesPoint, returnCFRoutes: true, polygonBarriers, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( `polygonBarriers=${encodeURIComponent( JSON.stringify(polygonBarriers) )}` ); done(); }) .catch((e) => { fail(e); }); }); it("should include routes.geoJson in the return", (done) => { fetchMock.once("*", ClosestFacility); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; closestFacility({ incidents: incidentsPoint, facilities: facilitiesPoint, returnCFRoutes: true, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(Object.keys(response.routes)).toContain("geoJson"); expect(Object.keys(response.routes.geoJson)).toContain("type"); expect(response.routes.geoJson.type).toEqual("FeatureCollection"); expect(Object.keys(response.routes.geoJson)).toContain("features"); expect(response.routes.geoJson.features.length).toBeGreaterThan(0); done(); }) .catch((e) => { fail(e); }); }); it("should not include routes.geoJson in the return for non-4326", (done) => { fetchMock.once("*", ClosestFacilityWebMercator); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; closestFacility({ incidents: incidentsPoint, facilities: facilitiesPoint, returnCFRoutes: true, authentication: MOCK_AUTH, params: { outSR: 102100, }, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(Object.keys(response.routes)).not.toContain("geoJson"); done(); }) .catch((e) => { fail(e); }); }); });
the_stack
import React from 'react'; import { useDebouncedCallback } from 'use-debounce/lib'; import { Autocomplete, Typography } from '@mui/material'; import { Controller, ControllerRenderProps, useForm, } from 'react-hook-form'; import { DataEntityApiCreateOwnershipRequest, DataEntityApiUpdateOwnershipRequest, Owner, OwnerApiGetOwnerListRequest, OwnerList, Ownership, OwnershipFormData, Role, RoleApiGetRoleListRequest, RoleList, } from 'generated-sources'; import DialogWrapper from 'components/shared/DialogWrapper/DialogWrapper'; import { AutocompleteInputChangeReason, createFilterOptions, FilterOptionsState, } from '@mui/material/useAutocomplete'; import LabeledInfoItem from 'components/shared/LabeledInfoItem/LabeledInfoItem'; import AutocompleteSuggestion from 'components/shared/AutocompleteSuggestion/AutocompleteSuggestion'; import AppButton from 'components/shared/AppButton/AppButton'; import AppTextField from 'components/shared/AppTextField/AppTextField'; import ClearIcon from 'components/shared/Icons/ClearIcon'; interface OwnershipFormProps { dataEntityId: number; dataEntityOwnership?: Ownership; ownerEditBtn: JSX.Element; isUpdating: boolean; createDataEntityOwnership: ( params: DataEntityApiCreateOwnershipRequest ) => Promise<Ownership>; updateDataEntityOwnership: ( params: DataEntityApiUpdateOwnershipRequest ) => Promise<Ownership>; searchOwners: ( params: OwnerApiGetOwnerListRequest ) => Promise<OwnerList>; searchRoles: (params: RoleApiGetRoleListRequest) => Promise<RoleList>; } const OwnershipForm: React.FC<OwnershipFormProps> = ({ dataEntityId, dataEntityOwnership, ownerEditBtn, isUpdating, createDataEntityOwnership, updateDataEntityOwnership, searchOwners, searchRoles, }) => { // Owner Autocomplete type OwnerFilterOption = Omit<Owner, 'id' | 'name'> & Partial<Owner>; const [ownerOptions, setOwnerOptions] = React.useState< OwnerFilterOption[] >([]); const [ ownersAutocompleteOpen, setOwnersAutocompleteOpen, ] = React.useState(false); const [ownersLoading, setOwnersLoading] = React.useState<boolean>(false); const [ownersSearchText, setOwnersSearchText] = React.useState<string>( '' ); const ownersFilter = createFilterOptions<OwnerFilterOption>(); const handleOwnersSearch = React.useCallback( useDebouncedCallback(() => { setOwnersLoading(true); searchOwners({ page: 1, size: 30, query: ownersSearchText }).then( response => { setOwnersLoading(false); setOwnerOptions(response.items); } ); }, 500), [searchOwners, setOwnersLoading, setOwnerOptions, ownersSearchText] ); const onOwnersSearchInputChange = React.useCallback( ( _: React.ChangeEvent<unknown>, query: string, reason: AutocompleteInputChangeReason ) => { if (reason === 'input') { setOwnersSearchText(query); } else { setOwnersSearchText(''); // Clear input on select } }, [setOwnersSearchText] ); const getOwnerFilterOptions = ( filterOptions: OwnerFilterOption[], params: FilterOptionsState<OwnerFilterOption> ) => { const filtered = ownersFilter(filterOptions, params); if ( ownersSearchText !== '' && !ownersLoading && !filterOptions.some(option => option.name === ownersSearchText) ) { return [...filtered, { name: ownersSearchText }]; } return filtered; }; React.useEffect(() => { setOwnersLoading(ownersAutocompleteOpen); if (ownersAutocompleteOpen) { handleOwnersSearch(); } }, [ownersAutocompleteOpen, ownersSearchText]); // Role Autocomplete type RoleFilterOption = Omit<Role, 'id' | 'name'> & Partial<Role>; const [rolesOptions, setRoleOptions] = React.useState< RoleFilterOption[] >([]); const [rolesAutocompleteOpen, setRolesAutocompleteOpen] = React.useState( false ); const [rolesLoading, setRolesLoading] = React.useState<boolean>(false); const [rolesSearchText, setRolesSearchText] = React.useState<string>(''); const rolesFilter = createFilterOptions<RoleFilterOption>(); const handleRolesSearch = React.useCallback( useDebouncedCallback(() => { setRolesLoading(true); searchRoles({ page: 1, size: 30, query: rolesSearchText }).then( response => { setRolesLoading(false); setRoleOptions(response.items); } ); }, 500), [searchRoles, setRolesLoading, setRoleOptions, ownersSearchText] ); const onRolesSearchInputChange = React.useCallback( ( _: React.ChangeEvent<unknown>, query: string, reason: AutocompleteInputChangeReason ) => { if (reason === 'input') { setRolesSearchText(query); } else { setRolesSearchText(''); // Clear input on select } }, [setRolesSearchText] ); React.useEffect(() => { setRolesLoading(rolesAutocompleteOpen); if (rolesAutocompleteOpen) { handleRolesSearch(); } }, [rolesAutocompleteOpen, rolesSearchText]); const getOptionLabel = React.useCallback( (option: RoleFilterOption | OwnerFilterOption) => { if (typeof option === 'string') { return option; } if ('name' in option && option.name) { return option.name; } return ''; }, [] ); const getRoleFilterOptions = ( filterOptions: RoleFilterOption[], params: FilterOptionsState<RoleFilterOption> ) => { const filtered = rolesFilter(filterOptions, params); if ( rolesSearchText !== '' && !rolesLoading && !filterOptions.some(option => option.name === rolesSearchText) ) { return [...filtered, { name: rolesSearchText }]; } return filtered; }; const onAutocompleteChange = ( field: ControllerRenderProps, data: string | null | OwnerFilterOption | RoleFilterOption ) => { if (!data || typeof data === 'string') { field.onChange(data); } else { field.onChange(data.name); } }; // Form const methods = useForm<OwnershipFormData>({ mode: 'onChange', defaultValues: { ownerName: '', roleName: dataEntityOwnership?.role?.name || '', }, }); const initialFormState = { error: '', isSuccessfulSubmit: false }; const [{ error, isSuccessfulSubmit }, setFormState] = React.useState<{ error: string; isSuccessfulSubmit: boolean; }>(initialFormState); const resetState = React.useCallback(() => { setFormState(initialFormState); }, [setFormState]); const ownershipUpdate = (data: OwnershipFormData) => { (dataEntityOwnership ? updateDataEntityOwnership({ dataEntityId, ownershipId: dataEntityOwnership.id, ownershipUpdateFormData: { roleName: data.roleName }, }) : createDataEntityOwnership({ dataEntityId, ownershipFormData: data, }) ).then( () => { setFormState({ ...initialFormState, isSuccessfulSubmit: true }); resetState(); }, (response: Response) => { setFormState({ ...initialFormState, error: response.statusText || 'Unable to update owner', }); } ); }; const formTitle = ( <Typography variant="h4"> {dataEntityOwnership ? 'Edit' : 'Add'} owner </Typography> ); const formContent = () => ( <form id="owner-add-form" onSubmit={methods.handleSubmit(ownershipUpdate)} > {dataEntityOwnership ? ( <LabeledInfoItem inline label="Owner:" labelWidth="auto"> {dataEntityOwnership.owner.name} </LabeledInfoItem> ) : ( <Controller name="ownerName" control={methods.control} defaultValue="" rules={{ required: true }} render={({ field }) => ( <Autocomplete // eslint-disable-next-line react/jsx-props-no-spreading {...field} fullWidth id="owners-name-search" open={ownersAutocompleteOpen} onOpen={() => setOwnersAutocompleteOpen(true)} onClose={() => setOwnersAutocompleteOpen(false)} onChange={(_, data) => onAutocompleteChange(field, data)} onInputChange={onOwnersSearchInputChange} getOptionLabel={getOptionLabel} options={ownerOptions} filterOptions={getOwnerFilterOptions} loading={ownersLoading} isOptionEqualToValue={(option, value) => option.name === value.name } handleHomeEndKeys selectOnFocus blurOnSelect freeSolo clearIcon={<ClearIcon />} renderInput={params => ( <AppTextField {...params} ref={params.InputProps.ref} label="Owner name" placeholder="Search name" customEndAdornment={{ variant: 'loader', showAdornment: ownersLoading, position: { mr: 4 }, }} /> )} renderOption={(props, option) => ( <li {...props}> <Typography variant="body2"> {option.id ? ( option.name ) : ( <AutocompleteSuggestion optionLabel="owner" optionName={option.name} /> )} </Typography> </li> )} /> )} /> )} <Controller name="roleName" control={methods.control} defaultValue={dataEntityOwnership?.role?.name || ''} rules={{ required: true, validate: value => !!value?.trim() }} render={({ field }) => ( <Autocomplete // eslint-disable-next-line react/jsx-props-no-spreading {...field} fullWidth id="roles-name-search" open={rolesAutocompleteOpen} onOpen={() => setRolesAutocompleteOpen(true)} onClose={() => setRolesAutocompleteOpen(false)} onChange={(_, data) => onAutocompleteChange(field, data)} onInputChange={onRolesSearchInputChange} getOptionLabel={getOptionLabel} options={rolesOptions} filterOptions={getRoleFilterOptions} loading={rolesLoading} isOptionEqualToValue={(option, value) => option.name === value.name } handleHomeEndKeys selectOnFocus blurOnSelect freeSolo clearIcon={<ClearIcon />} renderInput={params => ( <AppTextField {...params} sx={{ mt: 1.5 }} ref={params.InputProps.ref} label="Role" placeholder="Search role" customEndAdornment={{ variant: 'loader', showAdornment: rolesLoading, position: { mr: 4 }, }} /> )} renderOption={(props, option) => ( <li {...props}> <Typography variant="body2"> {option.id ? ( option.name ) : ( <AutocompleteSuggestion optionLabel="role" optionName={option.name} /> )} </Typography> </li> )} /> )} /> </form> ); const ownerEditDialogActions = () => ( <AppButton size="large" color="primary" type="submit" form="owner-add-form" fullWidth disabled={!methods.formState.isValid || !methods.formState.isDirty} > {dataEntityOwnership ? 'Edit' : 'Add'} owner </AppButton> ); return ( <DialogWrapper maxWidth="xs" renderOpenBtn={({ handleOpen }) => React.cloneElement(ownerEditBtn, { onClick: handleOpen }) } title={formTitle} renderContent={formContent} renderActions={ownerEditDialogActions} handleCloseSubmittedForm={isSuccessfulSubmit} isLoading={isUpdating} errorText={error} /> ); }; export default OwnershipForm;
the_stack
import * as validateConfig from './common'; import { Diff } from 'deep-diff'; import { LHS, RHS } from './config-diff'; import { StackOutput } from '@aws-accelerator/common-outputs/src/stack-output'; import { VpcOutputFinder } from '@aws-accelerator/common-outputs/src/vpc'; import { loadAssignedVpcCidrPool, loadAssignedSubnetCidrPool } from '@aws-accelerator/common/src/util/common'; import { AcceleratorConfig } from '..'; /** * config path(s) for global options */ const GLOBAL_OPTIONS_AOM_ACCOUNT = ['global-options', 'aws-org-management', 'account']; const GLOBAL_OPTIONS_AOM_REGION = ['global-options', 'aws-org-management', 'region']; const GLOBAL_OPTIONS_CLS_ACCOUNT = ['global-options', 'central-log-services', 'account']; const GLOBAL_OPTIONS_CLS_REGION = ['global-options', 'central-log-services', 'region']; /** * config path(s) for mandatory accounts vpc(s) */ const ACCOUNT_VPC = ['mandatory-account-configs', 'vpc']; const ACCOUNT_VPC_NAME = ['mandatory-account-configs', 'vpc', 'name']; const ACCOUNT_VPC_REGION = ['mandatory-account-configs', 'vpc', 'region']; const ACCOUNT_VPC_DEPLOY = ['mandatory-account-configs', 'vpc', 'deploy']; const ACCOUNT_VPC_CIDR = ['mandatory-account-configs', 'vpc', 'cidr', 'value']; const ACCOUNT_VPC_TENANCY = ['mandatory-account-configs', 'vpc', 'dedicated-tenancy']; /** * config path(s) for mandatory accounts vpc subnets */ const ACCOUNT_SUBNETS = ['mandatory-account-configs', 'vpc', 'subnets']; const ACCOUNT_SUBNET_NAME = ['mandatory-account-configs', 'vpc', 'subnets', 'name']; const ACCOUNT_SUBNET_AZ = ['mandatory-account-configs', 'vpc', 'subnets', 'definitions', 'az']; const ACCOUNT_SUBNET_CIDR = ['mandatory-account-configs', 'vpc', 'subnets', 'definitions', 'cidr', 'value']; const ACCOUNT_SUBNET_DISABLED = ['mandatory-account-configs', 'vpc', 'subnets', 'definitions', 'disabled']; /** * config path(s) for mandatory accounts vpc - TGW */ const TGW_NAME = ['mandatory-account-configs', 'deployments', 'tgw', 'name']; const TGW_ASN = ['mandatory-account-configs', 'deployments', 'tgw', 'asn']; const TGW_REGION = ['mandatory-account-configs', 'deployments', 'tgw', 'region']; const TGW_FEATURES = ['mandatory-account-configs', 'deployments', 'tgw', 'features']; /** * config path(s) for mandatory accounts - MAD */ const MAD_DIR_ID = ['mandatory-account-configs', 'deployments', 'mad', 'dir-id']; const MAD_DEPLOY = ['mandatory-account-configs', 'deployments', 'mad', 'deploy']; const MAD_VPC_NAME = ['mandatory-account-configs', 'deployments', 'mad', 'vpc-name']; const MAD_REGION = ['mandatory-account-configs', 'deployments', 'mad', 'region']; const MAD_SUBNET = ['mandatory-account-configs', 'deployments', 'mad', 'subnet']; const MAD_SIZE = ['mandatory-account-configs', 'deployments', 'mad', 'size']; const MAD_DNS = ['mandatory-account-configs', 'deployments', 'mad', 'dns-domain']; const MAD_NETBIOS = ['mandatory-account-configs', 'deployments', 'mad', 'netbios-domain']; /** * config path for mandatory accounts - VGW */ const VGW_ASN = ['mandatory-account-configs', 'vpc', 'vgw', 'asn']; /** * config path(s) for organizational units - vpc */ const OU_VPC = ['organizational-units', 'vpc']; const OU_VPC_NAME = ['organizational-units', 'vpc', 'name']; const OU_VPC_REGION = ['organizational-units', 'vpc', 'region']; const OU_VPC_DEPLOY = ['organizational-units', 'vpc', 'deploy']; const OU_VPC_CIDR = ['organizational-units', 'vpc', 'cidr', 'value']; const OU_VPC_TENANCY = ['organizational-units', 'vpc', 'dedicated-tenancy']; const OU_VPC_OPT_IN = ['organizational-units', 'vpc', 'opt-in']; /** * config path(s) for organizational units vpc subnets */ const OU_SUBNETS = ['organizational-units', 'vpc', 'subnets']; const OU_SUBNET_NAME = ['organizational-units', 'vpc', 'subnets', 'name']; const OU_SUBNET_AZ = ['organizational-units', 'vpc', 'subnets', 'definitions', 'az']; const OU_SUBNET_CIDR = ['organizational-units', 'vpc', 'subnets', 'definitions', 'cidr', 'value']; const OU_SUBNET_DISABLED = ['organizational-units', 'vpc', 'subnets', 'definitions', 'disabled']; /** * config path(s) for organizational units vpc - NACLS */ const OU_NACLS = ['organizational-units', 'vpc', 'subnets', 'nacls']; const OU_NACLS_SUBNET = ['organizational-units', 'vpc', 'subnets', 'nacls', 'cidr-blocks', 'subnet']; const WORKLOAD_ACCOUNT_OPT_IN_VPC = ['workload-account-configs', 'MyProdAccount', 'opt-in-vpcs']; const ACCOUNT_OPT_IN_VPC = ['mandatory-account-configs', 'MyProdAccount', 'opt-in-vpcs']; /** * * function to validate Global Options changes * * @param differences * @param errors */ export async function validateGlobalOptions( differences: Diff<LHS, RHS>[], errors: string[], ): Promise<void | undefined> { // below function to check alz-baseline change const alzBaseline = validateConfig.matchEditedConfigPath(differences, 'alz-baseline', false); if (alzBaseline) { errors.push(...alzBaseline); } // below function to check ct-baseline change const ctBaseline = validateConfig.matchEditedConfigPath(differences, 'ct-baseline', false); if (ctBaseline) { errors.push(...ctBaseline); } // below function to check master account name change const account = validateConfig.matchConfigPath(differences, GLOBAL_OPTIONS_AOM_ACCOUNT); if (account) { errors.push(...account); } // below function to check master region name change // TODO validate the SM executed in the same region const masterRegion = validateConfig.matchConfigPath(differences, GLOBAL_OPTIONS_AOM_REGION); if (masterRegion) { errors.push(...masterRegion); } // below function to check master account name change const logAccount = validateConfig.matchConfigPath(differences, GLOBAL_OPTIONS_CLS_ACCOUNT); if (logAccount) { errors.push(...logAccount); } // below function to check master region name change // TODO validate the SM executed in the same region const logRegion = validateConfig.matchConfigPath(differences, GLOBAL_OPTIONS_CLS_REGION); if (logRegion) { errors.push(...logRegion); } } /** * * function to validate change/delete of account * * @param accountNames * @param differences * @param errors */ export async function validateDeleteAccountConfig( accountNames: string[], differences: Diff<LHS, RHS>[], errors: string[], ): Promise<void | undefined> { // below functions check whether sub accounts removed from config file const deletedAccount = validateConfig.deletedSubAccount(accountNames, differences); if (deletedAccount) { errors.push(...deletedAccount); } } /** * * function to validate rename of account name * * @param differences * @param errors */ export async function validateRenameAccountConfig( differences: Diff<LHS, RHS>[], errors: string[], ): Promise<void | undefined> { // the below function checks renaming of the sub accounts const renameAccount = validateConfig.matchEditedConfigPath(differences, 'account-name', true); if (renameAccount) { errors.push(...renameAccount); } } /** * * function to validate account email * * @param differences * @param errors */ export async function validateAccountEmail(differences: Diff<LHS, RHS>[], errors: string[]): Promise<void | undefined> { // the below function checks sub account email const accountEmail = validateConfig.matchEditedConfigPath(differences, 'email', true, 3); if (accountEmail) { errors.push(...accountEmail); } } /** * * function to validate mandatory accounts OU * * @param differences * @param errors */ export async function validateAccountOu(differences: Diff<LHS, RHS>[], errors: string[]): Promise<void> { // the below function checks sub account ou const accountOu = validateConfig.matchEditedConfigPath(differences, 'ou', true, 3); if (accountOu) { errors.push(...accountOu); } } /** * * function to validate mandatory account VPC configuration * * @param differences * @param errors */ export async function validateAccountVpc(differences: Diff<LHS, RHS>[], errors: string[]): Promise<void> { // the below function checks vpc deletion from Account Config errors.push(...validateConfig.deletedConfigEntry(differences, ACCOUNT_VPC, 'vpc')); // the below function checks vpc deploy of the account const accountVpcDeploy = validateConfig.matchEditedConfigDependency(differences, ACCOUNT_VPC_DEPLOY, 5); if (accountVpcDeploy) { errors.push(...accountVpcDeploy); } // the below function checks vpc name of the account const accountVpcName = validateConfig.matchEditedConfigDependency(differences, ACCOUNT_VPC_NAME, 5); if (accountVpcName) { errors.push(...accountVpcName); } // the below function checks vpc cidr of the account const accountVpcCidr = validateConfig.matchEditedConfigDependency(differences, ACCOUNT_VPC_CIDR, 7); if (accountVpcCidr) { errors.push(...accountVpcCidr); } // the below function checks vpc region of the account const accountVpcRegion = validateConfig.matchEditedConfigDependency(differences, ACCOUNT_VPC_REGION, 5); if (accountVpcRegion) { errors.push(...accountVpcRegion); } // the below function checks vpc tenancy of the account const vpcTenancy = validateConfig.matchBooleanConfigDependency(differences, ACCOUNT_VPC_TENANCY, 5); if (vpcTenancy) { errors.push(...vpcTenancy); } } /** * * function to validate mandatory accounts subnet configuration * * @param differences * @param errors */ export async function validateAccountSubnets(differences: Diff<LHS, RHS>[], errors: string[]): Promise<void> { const removeAccountSubnets = validateConfig.matchConfigDependencyArray(differences, ACCOUNT_SUBNETS, 5); if (removeAccountSubnets) { errors.push(...removeAccountSubnets); } const updatedAccountSubnetName = validateConfig.matchEditedConfigDependency(differences, ACCOUNT_SUBNET_NAME, 7); if (updatedAccountSubnetName) { errors.push(...updatedAccountSubnetName); } const updatedAccountSubnetAz = validateConfig.matchEditedConfigDependency(differences, ACCOUNT_SUBNET_AZ, 9); if (updatedAccountSubnetAz) { errors.push(...updatedAccountSubnetAz); } // the below function checks subnet cidr of the account const accountSubnetCidr = validateConfig.matchEditedConfigDependency(differences, ACCOUNT_SUBNET_CIDR, 10); if (accountSubnetCidr) { errors.push(...accountSubnetCidr); } const accountSubnetDisabled = validateConfig.matchEditedConfigPathDisabled(differences, ACCOUNT_SUBNET_DISABLED, 9); if (accountSubnetDisabled) { errors.push(...accountSubnetDisabled); } } /** * * function to validate mandatory accounts TGW * @param differences * @param errors */ export async function validateTgw(differences: Diff<LHS, RHS>[], errors: string[]): Promise<void> { // the below function checks vpc name of the account const tgwName = validateConfig.matchEditedConfigDependency(differences, TGW_NAME, 6); if (tgwName) { errors.push(...tgwName); } const tgwAsn = validateConfig.matchEditedConfigDependency(differences, TGW_ASN, 6); if (tgwAsn) { errors.push(...tgwAsn); } const tgwRegion = validateConfig.matchEditedConfigDependency(differences, TGW_REGION, 6); if (tgwRegion) { errors.push(...tgwRegion); } const tgwFeatures = validateConfig.matchEditedConfigPathValues(differences, TGW_FEATURES, false, 7); if (tgwFeatures) { errors.push(...tgwFeatures); } } /** * * function to validate mandatory accounts MAD configuration * * @param differences * @param errors */ export async function validateMad(differences: Diff<LHS, RHS>[], errors: string[]): Promise<void> { const madDirId = validateConfig.matchEditedConfigPathValues(differences, MAD_DIR_ID, false, 5); if (madDirId) { errors.push(...madDirId); } const madDeploy = validateConfig.matchEditedConfigPathValues(differences, MAD_DEPLOY, false, 5); if (madDeploy) { errors.push(...madDeploy); } const madVpcName = validateConfig.matchEditedConfigPathValues(differences, MAD_VPC_NAME, false, 5); if (madVpcName) { errors.push(...madVpcName); } const madRegion = validateConfig.matchEditedConfigPathValues(differences, MAD_REGION, false, 5); if (madRegion) { errors.push(...madRegion); } const madSubnet = validateConfig.matchEditedConfigPathValues(differences, MAD_SUBNET, false, 5); if (madSubnet) { errors.push(...madSubnet); } const madSize = validateConfig.matchEditedConfigPathValues(differences, MAD_SIZE, false, 5); if (madSize) { errors.push(...madSize); } const madDns = validateConfig.matchEditedConfigPathValues(differences, MAD_DNS, false, 5); if (madDns) { errors.push(...madDns); } const madNetBios = validateConfig.matchEditedConfigPathValues(differences, MAD_NETBIOS, false, 5); if (madNetBios) { errors.push(...madNetBios); } } /** * * function to validate mandatory accounts VGW configuration * * @param differences * @param errors */ export async function validateVgw(differences: Diff<LHS, RHS>[], errors: string[]): Promise<void> { const vgwAsn = validateConfig.matchEditedConfigDependency(differences, VGW_ASN, 6); if (vgwAsn) { errors.push(...vgwAsn); } } /** * * function to validate organizational units VPC configuration * * @param differences * @param errors */ export async function validateOuVpc(differences: Diff<LHS, RHS>[], errors: string[]): Promise<void> { // the below function checks vpc deletion from Organizational Unit errors.push(...validateConfig.deletedConfigEntry(differences, OU_VPC, 'vpc')); // the below function checks vpc deploy of the account const ouVpcDeploy = validateConfig.matchEditedConfigDependency(differences, OU_VPC_DEPLOY, 5); if (ouVpcDeploy) { errors.push(...ouVpcDeploy); } // the below function checks vpc name of the account const ouVpcName = validateConfig.matchEditedConfigDependency(differences, OU_VPC_NAME, 5); if (ouVpcName) { errors.push(...ouVpcName); } // the below function checks vpc cidr of the account const ouVpcCidr = validateConfig.matchEditedConfigDependency(differences, OU_VPC_CIDR, 7); if (ouVpcCidr) { errors.push(...ouVpcCidr); } // the below function checks vpc region of the account const ouVpcRegion = validateConfig.matchEditedConfigDependency(differences, OU_VPC_REGION, 5); if (ouVpcRegion) { errors.push(...ouVpcRegion); } // the below function checks vpc tenancy of the OU const vpcTenancy = validateConfig.matchBooleanConfigDependency(differences, OU_VPC_TENANCY, 5); if (vpcTenancy) { errors.push(...vpcTenancy); } // the below function checks vpc tenancy of the OU const vpcOptIn = validateConfig.matchBooleanConfigDependency(differences, OU_VPC_OPT_IN, 5); if (vpcOptIn) { errors.push(...vpcOptIn); } } /** * * function to validate organizational units subnet configuration * * @param differences * @param errors */ export async function validateOuSubnets(differences: Diff<LHS, RHS>[], errors: string[]): Promise<void> { const removeOuSubnets = validateConfig.matchConfigDependencyArray(differences, OU_SUBNETS, 5); if (removeOuSubnets) { errors.push(...removeOuSubnets); } const ouSubnetName = validateConfig.matchEditedConfigDependency(differences, OU_SUBNET_NAME, 7); if (ouSubnetName) { errors.push(...ouSubnetName); } const ouSubnetAz = validateConfig.matchEditedConfigDependency(differences, OU_SUBNET_AZ, 9); if (ouSubnetAz) { errors.push(...ouSubnetAz); } // the below function checks subnet cidr of the account const ouSubnetCidr = validateConfig.matchEditedConfigDependency(differences, OU_SUBNET_CIDR, 10); if (ouSubnetCidr) { errors.push(...ouSubnetCidr); } const ouSubnetDisabled = validateConfig.matchEditedConfigPathDisabled(differences, OU_SUBNET_DISABLED, 9); if (ouSubnetDisabled) { errors.push(...ouSubnetDisabled); } } /** * * function to validate organizational units share-to-ou-accounts configuration * * @param differences * @param errors */ export async function validateShareToOu(differences: Diff<LHS, RHS>[], errors: string[]): Promise<void> { const shareToOu = validateConfig.matchEditedConfigPath(differences, 'share-to-ou-accounts', true); if (shareToOu) { errors.push(...shareToOu); } } /** * * function to validate organizational units share-to-specific-accounts configuration * * @param differences * @param errors */ export async function validateShareToAccounts(differences: Diff<LHS, RHS>[], errors: string[]): Promise<void> { const shareToAccounts = validateConfig.editedConfigDependency(differences, ['share-to-specific-accounts']); if (shareToAccounts) { errors.push(...shareToAccounts); } const shareToAccountsArray = validateConfig.deletedConfigDependencyArray(differences, 'share-to-specific-accounts'); if (shareToAccountsArray) { errors.push(...shareToAccountsArray); } } /** * * function to validate organizational units NACLS configuration * * @param differences * @param errors */ export async function validateNacls(differences: Diff<LHS, RHS>[], errors: string[]): Promise<void> { const naclRules = validateConfig.editedConfigDependency(differences, OU_NACLS); if (naclRules) { errors.push(...naclRules); } const naclsSubnet = validateConfig.editedConfigArray(differences, OU_NACLS_SUBNET); if (naclsSubnet) { errors.push(...naclsSubnet); } } /** * * function to validate account opt-in-vpcs configuration * * @param differences * @param errors */ export async function validateAccountOptInVpc(differences: Diff<LHS, RHS>[], errors: string[]): Promise<void> { errors.push(...validateConfig.editedConfigDependency(differences, WORKLOAD_ACCOUNT_OPT_IN_VPC)); errors.push(...validateConfig.deletedConfigEntry(differences, WORKLOAD_ACCOUNT_OPT_IN_VPC, 'opt-in-vpcs')); errors.push(...validateConfig.editedConfigDependency(differences, ACCOUNT_OPT_IN_VPC)); errors.push(...validateConfig.deletedConfigEntry(differences, ACCOUNT_OPT_IN_VPC, 'opt-in-vpcs')); } /** * * function to validate account warming change * * @param differences * @param errors */ export async function validateAccountWarming( differences: Diff<LHS, RHS>[], errors: string[], ): Promise<void | undefined> { // the below function checks renaming of the sub accounts const accountWarming = validateConfig.matchEditedConfigPath(differences, 'account-warming-required', true); if (accountWarming) { errors.push(...accountWarming); } } /** * * function to validate VPC Outputs of previous executions with DDB Cidr values * * @param differences * @param errors */ export async function validateDDBChanges( acceleratorConfig: AcceleratorConfig, vpcCidrPoolAssignedTable: string, subnetCidrPoolAssignedTable: string, outputs: StackOutput[], errors: string[], ): Promise<void> { const assignedVpcCidrPools = await loadAssignedVpcCidrPool(vpcCidrPoolAssignedTable); const assignedSubnetCidrPools = await loadAssignedSubnetCidrPool(subnetCidrPoolAssignedTable); for (const { accountKey, vpcConfig, ouKey } of acceleratorConfig.getVpcConfigs()) { if (vpcConfig['cidr-src'] === 'provided') { continue; // Validations is already performed as part of compare configurations } const vpcOutput = VpcOutputFinder.tryFindOneByAccountAndRegionAndName({ outputs, accountKey, vpcName: vpcConfig.name, region: vpcConfig.region, }); if (!vpcOutput) { console.log(`VPC: ${accountKey}/${vpcConfig.region}/${vpcConfig.name} is not yet created`); continue; } const vpcAssignedCidrs = validateConfig.getAssigndVpcCidrs( assignedVpcCidrPools, accountKey, vpcConfig.name, vpcConfig.region, ouKey, ); // Validate VPC Cidrs let primaryCidr: string = ''; let additionalCidr: string[] = []; if (vpcConfig['cidr-src'] === 'lookup') { vpcAssignedCidrs.sort((a, b) => (a['vpc-assigned-id']! > b['vpc-assigned-id']! ? 1 : -1)); primaryCidr = vpcAssignedCidrs[0].cidr; if (vpcAssignedCidrs.length > 1) { additionalCidr = vpcAssignedCidrs.slice(1, vpcAssignedCidrs.length).map(c => c.cidr); } } else { primaryCidr = vpcAssignedCidrs.find(vpcPool => vpcPool.pool === vpcConfig.cidr[0].pool)?.cidr!; additionalCidr = vpcAssignedCidrs.filter(vpcPool => vpcPool.pool !== vpcConfig.cidr[0].pool).map(c => c.cidr); } if (primaryCidr !== vpcOutput.cidrBlock) { errors.push(`CIDR for VPC: ${accountKey}/${vpcConfig.region}/${vpcConfig.name} has been changed`); } if ( vpcOutput.additionalCidrBlocks.length > 0 && vpcOutput.additionalCidrBlocks.filter(v => additionalCidr.indexOf(v) < 0).length > 0 ) { errors.push(`CIDR2 for VPC: ${accountKey}/${vpcConfig.region}/${vpcConfig.name} has been changed`); } const subnetAssignedCidrs = validateConfig.getAssigndVpcSubnetCidrs( assignedSubnetCidrPools, accountKey, vpcConfig.name, vpcConfig.region, ouKey, ); for (const subnetDefinition of vpcOutput.subnets) { const subnetCidr = subnetAssignedCidrs.find( s => s['subnet-name'] === subnetDefinition.subnetName && s.az === subnetDefinition.az, )?.cidr; if (subnetDefinition.cidrBlock !== subnetCidr) { errors.push( `CIDR for Subnet: ${accountKey}/${vpcConfig.region}/${vpcConfig.name}/${subnetDefinition.subnetName}/${subnetDefinition.az} has been changed`, ); } } } } export async function validateNfw(differences: Diff<LHS, RHS>[], errors: string[]) { const nfwDiffs = differences.filter(diff => { return ( diff.path?.includes('mandatory-account-configs') && diff.path.includes('vpc') && diff.path.includes('nfw') && diff.path.length === 5 ); }); for (const diff of nfwDiffs) { if (diff.kind === 'D') { errors.push(`Firewall has been deleted from path ${diff.path?.join('/')}. This is not allowed.`); console.log(JSON.stringify(diff, null, 4)); } } const nfwNameDiffs = differences.filter(diff => { return ( diff.path?.includes('mandatory-account-configs') && diff.path.includes('vpc') && diff.path.includes('nfw') && diff.path.includes('firewall-name') ); }); for (const diff of nfwNameDiffs) { if (diff.kind === 'E') { errors.push( `Firewall name has changed from ${diff.lhs} to ${diff.rhs} in ${diff.path?.join( '/', )}. Changing the firewall name will cause the replacement of the firewall.`, ); } if (diff.kind === 'D') { errors.push( `Firewall name has been deleted. Previous value was ${diff.lhs} in ${diff.path?.join( '/', )}. Changing the firewall name or deleting the firewall is not allowed.`, ); } } }
the_stack
import {extend, warnOnce, isWorker} from './util'; import config from './config'; import assert from 'assert'; import {cacheGet, cachePut} from './tile_request_cache'; import webpSupported from './webp_supported'; import type {Callback} from '../types/callback'; import type {Cancelable} from '../types/cancelable'; export interface IResourceType { Unknown: keyof this; Style: keyof this; Source: keyof this; Tile: keyof this; Glyphs: keyof this; SpriteImage: keyof this; SpriteJSON: keyof this; Image: keyof this; } /** * The type of a resource. * @private * @readonly * @enum {string} */ const ResourceType = { Unknown: 'Unknown', Style: 'Style', Source: 'Source', Tile: 'Tile', Glyphs: 'Glyphs', SpriteImage: 'SpriteImage', SpriteJSON: 'SpriteJSON', Image: 'Image' } as IResourceType; export {ResourceType}; if (typeof Object.freeze == 'function') { Object.freeze(ResourceType); } /** * A `RequestParameters` object to be returned from Map.options.transformRequest callbacks. * @typedef {Object} RequestParameters * @property {string} url The URL to be requested. * @property {Object} headers The headers to be sent with the request. * @property {string} method Request method `'GET' | 'POST' | 'PUT'`. * @property {string} body Request body. * @property {string} type Response body type to be returned `'string' | 'json' | 'arrayBuffer'`. * @property {string} credentials `'same-origin'|'include'` Use 'include' to send cookies with cross-origin requests. * @property {boolean} collectResourceTiming If true, Resource Timing API information will be collected for these transformed requests and returned in a resourceTiming property of relevant data events. * @example * // use transformRequest to modify requests that begin with `http://myHost` * transformRequest: function(url, resourceType) { * if (resourceType === 'Source' && url.indexOf('http://myHost') > -1) { * return { * url: url.replace('http', 'https'), * headers: { 'my-custom-header': true }, * credentials: 'include' // Include cookies for cross-origin requests * } * } * } * */ export type RequestParameters = { url: string; headers?: any; method?: 'GET' | 'POST' | 'PUT'; body?: string; type?: 'string' | 'json' | 'arrayBuffer'; credentials?: 'same-origin' | 'include'; collectResourceTiming?: boolean; }; export type ResponseCallback<T> = ( error?: Error | null, data?: T | null, cacheControl?: string | null, expires?: string | null ) => void; /** * An error thrown when a HTTP request results in an error response. * @extends Error * @param {number} status The response's HTTP status code. * @param {string} statusText The response's HTTP status text. * @param {string} url The request's URL. * @param {Blob} body The response's body. */ export class AJAXError extends Error { /** * The response's HTTP status code. */ status: number; /** * The response's HTTP status text. */ statusText: string; /** * The request's URL. */ url: string; /** * The response's body. */ body: Blob; constructor(status: number, statusText: string, url: string, body: Blob) { super(`AJAXError: ${statusText} (${status}): ${url}`); this.status = status; this.statusText = statusText; this.url = url; this.body = body; } } // Ensure that we're sending the correct referrer from blob URL worker bundles. // For files loaded from the local file system, `location.origin` will be set // to the string(!) "null" (Firefox), or "file://" (Chrome, Safari, Edge, IE), // and we will set an empty referrer. Otherwise, we're using the document's URL. /* global self */ export const getReferrer = isWorker() ? () => (self as any).worker && (self as any).worker.referrer : () => (window.location.protocol === 'blob:' ? window.parent : window).location.href; // Determines whether a URL is a file:// URL. This is obviously the case if it begins // with file://. Relative URLs are also file:// URLs iff the original document was loaded // via a file:// URL. const isFileURL = url => /^file:/.test(url) || (/^file:/.test(getReferrer()) && !/^\w+:/.test(url)); function makeFetchRequest(requestParameters: RequestParameters, callback: ResponseCallback<any>): Cancelable { const controller = new AbortController(); const request = new Request(requestParameters.url, { method: requestParameters.method || 'GET', body: requestParameters.body, credentials: requestParameters.credentials, headers: requestParameters.headers, referrer: getReferrer(), signal: controller.signal }); let complete = false; let aborted = false; const cacheIgnoringSearch = false; if (requestParameters.type === 'json') { request.headers.set('Accept', 'application/json'); } const validateOrFetch = (err, cachedResponse?, responseIsFresh?) => { if (aborted) return; if (err) { // Do fetch in case of cache error. // HTTP pages in Edge trigger a security error that can be ignored. if (err.message !== 'SecurityError') { warnOnce(err); } } if (cachedResponse && responseIsFresh) { return finishRequest(cachedResponse); } if (cachedResponse) { // We can't do revalidation with 'If-None-Match' because then the // request doesn't have simple cors headers. } const requestTime = Date.now(); fetch(request).then(response => { if (response.ok) { const cacheableResponse = cacheIgnoringSearch ? response.clone() : null; return finishRequest(response, cacheableResponse, requestTime); } else { return response.blob().then(body => callback(new AJAXError(response.status, response.statusText, requestParameters.url, body))); } }).catch(error => { if (error.code === 20) { // silence expected AbortError return; } callback(new Error(error.message)); }); }; const finishRequest = (response, cacheableResponse?, requestTime?) => { ( requestParameters.type === 'arrayBuffer' ? response.arrayBuffer() : requestParameters.type === 'json' ? response.json() : response.text() ).then(result => { if (aborted) return; if (cacheableResponse && requestTime) { // The response needs to be inserted into the cache after it has completely loaded. // Until it is fully loaded there is a chance it will be aborted. Aborting while // reading the body can cause the cache insertion to error. We could catch this error // in most browsers but in Firefox it seems to sometimes crash the tab. Adding // it to the cache here avoids that error. cachePut(request, cacheableResponse, requestTime); } complete = true; callback(null, result, response.headers.get('Cache-Control'), response.headers.get('Expires')); }).catch(err => { if (!aborted) callback(new Error(err.message)); }); }; if (cacheIgnoringSearch) { cacheGet(request, validateOrFetch); } else { validateOrFetch(null, null); } return {cancel: () => { aborted = true; if (!complete) controller.abort(); }}; } function makeXMLHttpRequest(requestParameters: RequestParameters, callback: ResponseCallback<any>): Cancelable { const xhr: XMLHttpRequest = new XMLHttpRequest(); xhr.open(requestParameters.method || 'GET', requestParameters.url, true); if (requestParameters.type === 'arrayBuffer') { xhr.responseType = 'arraybuffer'; } for (const k in requestParameters.headers) { xhr.setRequestHeader(k, requestParameters.headers[k]); } if (requestParameters.type === 'json') { xhr.responseType = 'text'; xhr.setRequestHeader('Accept', 'application/json'); } xhr.withCredentials = requestParameters.credentials === 'include'; xhr.onerror = () => { callback(new Error(xhr.statusText)); }; xhr.onload = () => { if (((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) && xhr.response !== null) { let data: unknown = xhr.response; if (requestParameters.type === 'json') { // We're manually parsing JSON here to get better error messages. try { data = JSON.parse(xhr.response); } catch (err) { return callback(err); } } callback(null, data, xhr.getResponseHeader('Cache-Control'), xhr.getResponseHeader('Expires')); } else { const body = new Blob([xhr.response], {type: xhr.getResponseHeader('Content-Type')}); callback(new AJAXError(xhr.status, xhr.statusText, requestParameters.url, body)); } }; xhr.send(requestParameters.body); return {cancel: () => xhr.abort()}; } export const makeRequest = function(requestParameters: RequestParameters, callback: ResponseCallback<any>): Cancelable { // We're trying to use the Fetch API if possible. However, in some situations we can't use it: // - IE11 doesn't support it at all. In this case, we dispatch the request to the main thread so // that we can get an accruate referrer header. // - Safari exposes window.AbortController, but it doesn't work actually abort any requests in // some versions (see https://bugs.webkit.org/show_bug.cgi?id=174980#c2) // - Requests for resources with the file:// URI scheme don't work with the Fetch API either. In // this case we unconditionally use XHR on the current thread since referrers don't matter. if (/:\/\//.test(requestParameters.url) && !(/^https?:|^file:/.test(requestParameters.url))) { if (isWorker() && (self as any).worker && (self as any).worker.actor) { return (self as any).worker.actor.send('getResource', requestParameters, callback); } if (!isWorker()) { const protocol = requestParameters.url.substring(0, requestParameters.url.indexOf('://')); const action = config.REGISTERED_PROTOCOLS[protocol] || makeFetchRequest; return action(requestParameters, callback); } } if (!isFileURL(requestParameters.url)) { if (fetch && Request && AbortController && Object.prototype.hasOwnProperty.call(Request.prototype, 'signal')) { return makeFetchRequest(requestParameters, callback); } if (isWorker() && (self as any).worker && (self as any).worker.actor) { const queueOnMainThread = true; return (self as any).worker.actor.send('getResource', requestParameters, callback, undefined, queueOnMainThread); } } return makeXMLHttpRequest(requestParameters, callback); }; export const getJSON = function(requestParameters: RequestParameters, callback: ResponseCallback<any>): Cancelable { return makeRequest(extend(requestParameters, {type: 'json'}), callback); }; export const getArrayBuffer = function( requestParameters: RequestParameters, callback: ResponseCallback<ArrayBuffer> ): Cancelable { return makeRequest(extend(requestParameters, {type: 'arrayBuffer'}), callback); }; export const postData = function(requestParameters: RequestParameters, callback: ResponseCallback<string>): Cancelable { return makeRequest(extend(requestParameters, {method: 'POST'}), callback); }; function sameOrigin(url) { const a: HTMLAnchorElement = window.document.createElement('a'); a.href = url; return a.protocol === window.document.location.protocol && a.host === window.document.location.host; } const transparentPngUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII='; function arrayBufferToImage(data: ArrayBuffer, callback: (err?: Error | null, image?: HTMLImageElement | null) => void) { const img: HTMLImageElement = new Image(); img.onload = () => { callback(null, img); URL.revokeObjectURL(img.src); // prevent image dataURI memory leak in Safari; // but don't free the image immediately because it might be uploaded in the next frame // https://github.com/mapbox/mapbox-gl-js/issues/10226 img.onload = null; window.requestAnimationFrame(() => { img.src = transparentPngUrl; }); }; img.onerror = () => callback(new Error('Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.')); const blob: Blob = new Blob([new Uint8Array(data)], {type: 'image/png'}); img.src = data.byteLength ? URL.createObjectURL(blob) : transparentPngUrl; } function arrayBufferToImageBitmap(data: ArrayBuffer, callback: (err?: Error | null, image?: ImageBitmap | null) => void) { const blob: Blob = new Blob([new Uint8Array(data)], {type: 'image/png'}); createImageBitmap(blob).then((imgBitmap) => { callback(null, imgBitmap); }).catch((e) => { callback(new Error(`Could not load image because of ${e.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)); }); } export type ExpiryData = {cacheControl?: string | null; expires?: string | null}; function arrayBufferToCanvasImageSource(data: ArrayBuffer, callback: Callback<CanvasImageSource>) { const imageBitmapSupported = typeof createImageBitmap === 'function'; if (imageBitmapSupported) { arrayBufferToImageBitmap(data, callback); } else { arrayBufferToImage(data, callback); } } let imageQueue, numImageRequests; export const resetImageRequestQueue = () => { imageQueue = []; numImageRequests = 0; }; resetImageRequestQueue(); export type GetImageCallback = (error?: Error | null, image?: HTMLImageElement | ImageBitmap | null, expiry?: ExpiryData | null) => void; export const getImage = function( requestParameters: RequestParameters, callback: GetImageCallback ): Cancelable { if (webpSupported.supported) { if (!requestParameters.headers) { requestParameters.headers = {}; } requestParameters.headers.accept = 'image/webp,*/*'; } // limit concurrent image loads to help with raster sources performance on big screens if (numImageRequests >= config.MAX_PARALLEL_IMAGE_REQUESTS) { const queued = { requestParameters, callback, cancelled: false, cancel() { this.cancelled = true; } }; imageQueue.push(queued); return queued; } numImageRequests++; let advanced = false; const advanceImageRequestQueue = () => { if (advanced) return; advanced = true; numImageRequests--; assert(numImageRequests >= 0); while (imageQueue.length && numImageRequests < config.MAX_PARALLEL_IMAGE_REQUESTS) { // eslint-disable-line const request = imageQueue.shift(); const {requestParameters, callback, cancelled} = request; if (!cancelled) { request.cancel = getImage(requestParameters, callback).cancel; } } }; // request the image with XHR to work around caching issues // see https://github.com/mapbox/mapbox-gl-js/issues/1470 const request = getArrayBuffer(requestParameters, (err?: Error | null, data?: ArrayBuffer | null, cacheControl?: string | null, expires?: string | null) => { advanceImageRequestQueue(); if (err) { callback(err); } else if (data) { const decoratedCallback = (imgErr?: Error | null, imgResult?: CanvasImageSource | null) => { if (imgErr != null) { callback(imgErr); } else if (imgResult != null) { callback(null, imgResult as (HTMLImageElement | ImageBitmap), {cacheControl, expires}); } }; arrayBufferToCanvasImageSource(data, decoratedCallback); } }); return { cancel: () => { request.cancel(); advanceImageRequestQueue(); } }; }; export const getVideo = function(urls: Array<string>, callback: Callback<HTMLVideoElement>): Cancelable { const video: HTMLVideoElement = window.document.createElement('video'); video.muted = true; video.onloadstart = function() { callback(null, video); }; for (let i = 0; i < urls.length; i++) { const s: HTMLSourceElement = window.document.createElement('source'); if (!sameOrigin(urls[i])) { video.crossOrigin = 'Anonymous'; } s.src = urls[i]; video.appendChild(s); } return {cancel: () => {}}; };
the_stack
declare var BIP38Util: ReturnType<typeof INIT_BIP38>; interface BIP38EncryptionData { addressType: AddressType; keypair: EcKeypairString; passpoint: number[]; ownersalt: number[]; } function INIT_BIP38() { function GenerateRandomBIP38EncryptionData(password: string, addressType: AddressType): Result<BIP38EncryptionData, string> { if (password === "") { return { type: "err", error: "Password must not be empty" }; } const ownersalt = WorkerUtils.Get32SecureRandomBytes().slice(0, 8); const passfactor = <Uint8Array>CryptoHelper.scrypt(password, ownersalt, 14, 8, 8, 32); const bigint = WorkerUtils.ByteArrayToBigint(passfactor); const keypair = EllipticCurve.EccMultiply(EllipticCurve.ecc_Gx, EllipticCurve.ecc_Gy, bigint); const publicKeyBytesX = WorkerUtils.BigintToByteArray(keypair.x); while (publicKeyBytesX.length < 32) { publicKeyBytesX.push(0); } const passpoint = publicKeyBytesX.slice(); // copy passpoint.push(keypair.y.isOdd() ? 0x03 : 0x02); passpoint.reverse(); return { type: "ok", result: { addressType, keypair: { x: keypair.x.toString(), y: keypair.y.toString() }, passpoint, ownersalt } }; } function GenerateRandomBIP38EncryptedAddress(encryptionData: BIP38EncryptionData): AddressWithPrivateKey { const seedb = WorkerUtils.Get32SecureRandomBytes().slice(0, 24); const factorb = CryptoHelper.SHA256(CryptoHelper.SHA256(seedb)); const keypairX = new BN(encryptionData.keypair.x); const keypairY = new BN(encryptionData.keypair.y); const ecPoint = EllipticCurve.EccMultiply(keypairX, keypairY, WorkerUtils.ByteArrayToBigint(factorb)); const generatedAddress = AddressUtil.MakeLegacyAddress(ecPoint); const addressWithType = (() => { switch (encryptionData.addressType) { case "legacy": return generatedAddress; case "segwit": return AddressUtil.MakeSegwitAddress(ecPoint); case "bech32": return AddressUtil.MakeBech32Address(ecPoint); } })(); const addressHash = CryptoHelper.SHA256(CryptoHelper.SHA256(generatedAddress)).slice(0, 4); const salt = [...addressHash, ...encryptionData.ownersalt]; const encrypted = <Uint8Array>CryptoHelper.scrypt(encryptionData.passpoint, salt, 10, 1, 1, 64); const derivedHalf1 = encrypted.slice(0, 32); const derivedHalf2 = encrypted.slice(32, 64); const encryptedpart1 = CryptoHelper.AES_Encrypt_ECB_NoPadding(WorkerUtils.ByteArrayXOR(seedb.slice(0, 16), derivedHalf1.slice(0, 16)), derivedHalf2); const block2 = [...encryptedpart1.slice(8, 16), ...seedb.slice(16, 24)]; const encryptedpart2 = CryptoHelper.AES_Encrypt_ECB_NoPadding(WorkerUtils.ByteArrayXOR(block2, derivedHalf1.slice(16, 32)), derivedHalf2); const finalPrivateKeyWithoutChecksum = [ 0x01, 0x43, 0x20, ...addressHash, ...encryptionData.ownersalt, ...encryptedpart1.slice(0, 8), ...encryptedpart2 ]; return { addressType: encryptionData.addressType, address: addressWithType, privateKey: WorkerUtils.Base58CheckEncode(finalPrivateKeyWithoutChecksum) }; } function DecryptPrivateKey(privateKey: string, password: string): Result<string, string> { if (password === "") { return { type: "err", error: "password must not be empty" }; } const decoded = WorkerUtils.Base58CheckDecode(privateKey); if (decoded.type === "err") { return decoded; } const bytes = decoded.result; if (bytes[0] !== 0x01) { return { type: "err", error: "invalid byte at position 0" }; } bytes.shift(); // typescript will show an error if I have (bytes[0] === 0x43) here, because it doesn't know that bytes.shift() changes the array // see https://github.com/microsoft/TypeScript/issues/35795 // putting any here so it works if (<any>bytes[0] === 0x43) { if ((bytes[1] & 0x20) === 0) { return { type: "err", error: "only compressed private keys are supported" }; } const ownerSalt = bytes.slice(6, 14); const scryptResult = <Uint8Array>CryptoHelper.scrypt(password, ownerSalt, 14, 8, 8, 32); const bigint = WorkerUtils.ByteArrayToBigint(scryptResult); const keypair = EllipticCurve.GetECCKeypair(bigint); const publicKeyBytesX = WorkerUtils.BigintToByteArray(keypair.x); while (publicKeyBytesX.length < 32) { publicKeyBytesX.push(0); } const passpoint = publicKeyBytesX.slice(); passpoint.push(keypair.y.isOdd() ? 0x03 : 0x02); passpoint.reverse(); const encryptedPart2 = bytes.slice(22, 38); const addressHash = bytes.slice(2, 14); const scryptResult2 = <Uint8Array>CryptoHelper.scrypt(passpoint, addressHash, 10, 1, 1, 64); const derivedHalf1 = scryptResult2.slice(0, 32); const derivedHalf2 = scryptResult2.slice(32, 64); const decrypted2 = CryptoHelper.AES_Decrypt_ECB_NoPadding(encryptedPart2, derivedHalf2); const encryptedpart1 = [ ...bytes.slice(14, 22), ...WorkerUtils.ByteArrayXOR(decrypted2.slice(0, 8), scryptResult2.slice(16, 24)) ]; const decrypted1 = CryptoHelper.AES_Decrypt_ECB_NoPadding(encryptedpart1, derivedHalf2); const seedb = [ ...WorkerUtils.ByteArrayXOR(decrypted1.slice(0, 16), derivedHalf1.slice(0, 16)), ...WorkerUtils.ByteArrayXOR(decrypted2.slice(8, 16), derivedHalf1.slice(24, 32)) ]; const factorb = CryptoHelper.SHA256(CryptoHelper.SHA256(seedb)); const finalPrivateKeyValue = WorkerUtils.ByteArrayToBigint(scryptResult) .mul(WorkerUtils.ByteArrayToBigint(factorb)) .mod(EllipticCurve.ecc_n); const finalKeypair = EllipticCurve.GetECCKeypair(finalPrivateKeyValue); const finalAddress = AddressUtil.MakeLegacyAddress(finalKeypair); const finalAddressHash = CryptoHelper.SHA256(CryptoHelper.SHA256(finalAddress)); for (let i = 0; i < 4; ++i) { if (addressHash[i] !== finalAddressHash[i]) { return { type: "err", error: "invalid password" }; } } const finalPrivateKey = AddressUtil.MakePrivateKey(finalPrivateKeyValue); return { type: "ok", result: finalPrivateKey }; } else if (<any>bytes[0] === 0x42) { if (bytes[1] !== 0xe0) { return { type: "err", error: "only compressed private keys are supported" }; } const addressHash = bytes.slice(2, 6); const derivedBytes = <Uint8Array>CryptoHelper.scrypt(password, addressHash, 14, 8, 8, 64); const decrypted = CryptoHelper.AES_Decrypt_ECB_NoPadding(bytes.slice(6, 38), derivedBytes.slice(32)); const privateKeyBytes = WorkerUtils.ByteArrayXOR(decrypted, derivedBytes); const finalPrivateKeyValue = WorkerUtils.ByteArrayToBigint(privateKeyBytes); const finalKeypair = EllipticCurve.GetECCKeypair(finalPrivateKeyValue); const finalAddress = AddressUtil.MakeLegacyAddress(finalKeypair); const finalAddressHash = CryptoHelper.SHA256(CryptoHelper.SHA256(finalAddress)); for (let i = 0; i < 4; ++i) { if (addressHash[i] !== finalAddressHash[i]) { return { type: "err", error: "invalid password" }; } } const finalPrivateKey = AddressUtil.MakePrivateKey(finalPrivateKeyValue); return { type: "ok", result: finalPrivateKey }; } return { type: "err", error: "invalid byte at EC multiply flag" }; } function EncryptPrivateKey(privateKey: string, password: string): Result<string, string> { if (password === "") { return { type: "err", error: "password must not be empty" }; } const privateKeyDecoded = AddressUtil.PrivateKeyStringToKeyPair(privateKey); if (privateKeyDecoded.type === "err") { return privateKeyDecoded; } const privateKeyBytes = WorkerUtils.BigintToByteArray(privateKeyDecoded.result.privateKeyValue); while (privateKeyBytes.length < 32) { privateKeyBytes.push(0); } privateKeyBytes.reverse(); const address = AddressUtil.MakeLegacyAddress(privateKeyDecoded.result.keypair); const salt = CryptoHelper.SHA256(CryptoHelper.SHA256(address)).slice(0, 4); const derivedBytes = <Uint8Array>CryptoHelper.scrypt(password, salt, 14, 8, 8, 64); const firstHalf = WorkerUtils.ByteArrayXOR(privateKeyBytes, derivedBytes.slice(0, 32)); const secondHalf = derivedBytes.slice(32); const finalPrivateKeyWithoutChecksum = [ 0x01, 0x42, 0xe0, ...salt, ...CryptoHelper.AES_Encrypt_ECB_NoPadding(firstHalf, secondHalf) ]; return { type: "ok", result: WorkerUtils.Base58CheckEncode(finalPrivateKeyWithoutChecksum) } } return { GenerateRandomBIP38EncryptionData, GenerateRandomBIP38EncryptedAddress, DecryptPrivateKey, EncryptPrivateKey }; }
the_stack
import {Component, OnInit} from '@angular/core'; import * as utpl from 'uri-templates'; import {URITemplate} from 'uri-templates'; import {AppService, RequestHeader} from '../app.service'; import {Command, EventType, HttpRequestEvent, RequestService, UriTemplateParameter} from './request.service'; export class DictionaryObject { constructor(public prompt, public value) { } } @Component({ selector: 'app-uri-input', templateUrl: './request.component.html', styleUrls: ['./request.component.css'] }) export class RequestComponent implements OnInit { uri: string; isUriTemplate: boolean; templatedUri: string; uriTemplateParameters: UriTemplateParameter[]; httpRequestEvent: HttpRequestEvent = new HttpRequestEvent(EventType.FillHttpRequest, Command.Post, ''); originalRequestUri: string; newRequestUri: string; requestBody: string; selectedHttpMethod: Command; commandPlaceholder = Command; requestHeaders: RequestHeader[]; tempRequestHeaders: RequestHeader[]; hasCustomRequestHeaders: boolean; jsonSchema: any; halFormsProperties: any; halFormsTemplate: any; halFormsPropertyKey: string; halFormsContentType: string; noValueSelected = '<No Value Selected>'; constructor(private appService: AppService, private requestService: RequestService) { } ngOnInit() { this.jsonSchema = undefined; this.halFormsProperties = undefined; this.halFormsContentType = undefined; this.uri = this.appService.getUri(); this.tempRequestHeaders = this.appService.getCustomRequestHeaders(); this.requestService.getNeedInfoObservable().subscribe(async (value: any) => { if (value.type === EventType.FillHttpRequest) { this.jsonSchema = undefined; this.halFormsProperties = undefined; this.halFormsPropertyKey = undefined; this.halFormsTemplate = undefined; const event: HttpRequestEvent = value as HttpRequestEvent; this.httpRequestEvent = event; if (event.jsonSchema) { this.jsonSchema = event.jsonSchema.properties; } if (event.halFormsTemplate) { this.halFormsTemplate = event.halFormsTemplate; this.halFormsProperties = this.halFormsTemplate.value.properties; if(this.halFormsTemplate.value.contentType) { this.halFormsContentType = this.halFormsTemplate.value.contentType; } if (Array.isArray(this.halFormsProperties)) { for (const property of this.halFormsProperties) { if (property.options) { const options = property.options; if (!options.inline && options.link) { this.requestService.computeHalFormsOptionsFromLink(property); // Hack to poll and wait for the asynchronous HTTP call // that fills property.options.inline for (let i = 0; i < 10; i++) { if (!options.inline) { try { await new Promise((resolve) => setTimeout(resolve, 50)); } catch (e) { // ignore } } else { break; } } } if (!options.inline) { console.warn('Cannot compute HAL-FORMS options for property "' + property.name + '".'); console.warn('Will ignore HAL-FORMS options for property "' + property.name + '".'); property.options = undefined; } else { property.options.computedOptions = this.getHalFormsOptions(property); if (options.selectedValues) { if (options?.maxItems === 1) { property.value = options.selectedValues[0]; } else { property.value = options.selectedValues; } } else if (!property.required && !options.selectedValues && !(options?.minItems >= 1)) { property.value = this.noValueSelected; } else if (property.required && !options.selectedValues && options.computedOptions) { if (options?.maxItems === 1) { property.value = property.options.computedOptions[0].value; } else { property.value = [property.options.computedOptions[0].value]; } } } } } } this.halFormsPropertyKey = this.halFormsTemplate.value.title; } this.requestBody = ''; this.selectedHttpMethod = event.command; this.templatedUri = undefined; this.isUriTemplate = RequestComponent.isUriTemplated(event.uri); this.originalRequestUri = event.uri; if (this.isUriTemplate) { const uriTemplate: URITemplate = utpl(event.uri); this.uriTemplateParameters = []; for (const param of uriTemplate.varNames) { this.uriTemplateParameters.push(new UriTemplateParameter(param, '')); } this.templatedUri = event.uri; this.computeUriFromTemplate(); } else { this.newRequestUri = event.uri; } document.getElementById('HttpRequestTrigger').click(); this.propertyChanged(); } }); this.appService.uriObservable.subscribe(url => this.goFromHashChange(url)); this.appService.requestHeadersObservable.subscribe(requestHeaders => { this.tempRequestHeaders = requestHeaders; this.updateRequestHeaders(); }); this.updateRequestHeaders(); this.getUri(); } getUri() { this.requestService.getUri(this.uri); } getExpandedUri() { this.requestService.getUri(this.newRequestUri); } makeHttpRequest() { this.requestService.requestUri(this.newRequestUri, Command[this.selectedHttpMethod], this.requestBody, this.halFormsContentType); } goFromHashChange(uri: string) { this.uri = uri; this.requestService.getUri(this.uri); } computeUriFromTemplate(checkHalFormsProperties = true) { const uriTemplate = utpl(this.templatedUri); const templateParams = {}; for (const parameter of this.uriTemplateParameters) { if (parameter.value.length > 0) { templateParams[parameter.key] = parameter.value; } } this.newRequestUri = uriTemplate.fill(templateParams); if (this.halFormsProperties && checkHalFormsProperties) { this.propertyChanged(); } } private static isUriTemplated(uri: string) { const uriTemplate = utpl(uri); return uriTemplate.varNames.length > 0; } propertyChanged() { this.requestBody = '{\n'; if (this.templatedUri) { this.computeUriFromTemplate(false); } else if (this.originalRequestUri) { this.newRequestUri = this.originalRequestUri; } let hasQueryParams = false; if (this.jsonSchema) { for (const key of Object.keys(this.jsonSchema)) { if (this.jsonSchema[key].value && this.jsonSchema[key].value.length > 0) { if (hasQueryParams) { this.requestBody += ',\n'; } this.requestBody += ' "' + key + '": ' + (this.jsonSchema[key].type !== 'integer' ? '"' : '') + this.jsonSchema[key].value + (this.jsonSchema[key].type !== 'integer' ? '"' : ''); hasQueryParams = true; } } } else if (this.halFormsProperties) { if (this.templatedUri) { hasQueryParams = this.newRequestUri.includes('?'); } for (const item of this.halFormsProperties) { let httpMethod = 'get'; if (this.halFormsTemplate.value.method) { httpMethod = this.halFormsTemplate.value.method.toLowerCase(); } if (httpMethod !== 'get' && httpMethod !== 'post' && httpMethod !== 'put' && httpMethod !== 'patch' && httpMethod !== 'delete') { httpMethod = 'get'; } const hasBody = (httpMethod === 'post' || httpMethod === 'put' || httpMethod === 'patch'); const optionsAsArray = item?.options?.maxItems !== 1; if (item.name && item.value && item.value !== '<No Value Selected>') { if (hasQueryParams) { if (hasBody) { this.requestBody += ',\n'; } else { this.newRequestUri += '&'; } } else { if (!hasBody) { this.newRequestUri += '?'; } } if (hasBody) { if (optionsAsArray) { this.requestBody += ' "' + item.name + '": ' + JSON.stringify(item.value); } else { this.requestBody += ' "' + item.name + '": ' + '"' + item.value + '"'; } } else { this.newRequestUri += item.name + '=' + item.value; } hasQueryParams = true; } } } this.requestBody += '\n}'; } showEditHeadersDialog() { this.tempRequestHeaders = []; for (let i = 0; i < 5; i++) { if (this.requestHeaders.length > i) { this.tempRequestHeaders.push(new RequestHeader(this.requestHeaders[i].key, this.requestHeaders[i].value)); } else { this.tempRequestHeaders.push(new RequestHeader('', '')); } } document.getElementById('requestHeadersModalTrigger').click(); } updateRequestHeaders() { this.requestHeaders = []; for (const requestHeader of this.tempRequestHeaders) { const key: string = requestHeader.key.trim(); const value: string = requestHeader.value.trim(); if (key.length > 0 && value.length > 0) { this.requestHeaders.push(new RequestHeader(key, value)); } } this.processRequestHeaders(); } clearRequestHeaders() { this.tempRequestHeaders = []; for (let i = 0; i < 5; i++) { this.tempRequestHeaders.push(new RequestHeader('', '')); } this.processRequestHeaders(); } private processRequestHeaders() { this.requestService.setCustomHeaders(this.requestHeaders); this.hasCustomRequestHeaders = this.requestHeaders.length > 0; this.appService.setCustomRequestHeaders(this.requestHeaders); } setAcceptRequestHeader(value: string) { let acceptHeaderSet = false; for (let i = 0; i < 5; i++) { if (this.tempRequestHeaders[i].key.toLowerCase() === 'accept') { this.tempRequestHeaders[i].value = value; acceptHeaderSet = true; break; } } if (!acceptHeaderSet) { for (let i = 0; i < 5; i++) { if (this.tempRequestHeaders[i].key === '') { this.tempRequestHeaders[i].key = 'Accept'; this.tempRequestHeaders[i].value = value; break; } } } } getTooltip(key: string): string { if (!this.jsonSchema) { return ''; } let tooltip = this.jsonSchema[key].type; if (this.jsonSchema[key].format) { tooltip += ' in ' + this.jsonSchema[key].format + ' format'; } return tooltip; } getInputType(key: string): string { return this.requestService.getInputType(this.jsonSchema[key].type, this.jsonSchema[key].format); } getValidationErrors(ngModel: any): string { if (!ngModel.errors) { return ''; } let errorMessage = ''; if (ngModel.errors.required) { errorMessage = 'Value is required\n'; } if (ngModel.errors.pattern) { errorMessage += 'Value does not match pattern: ' + ngModel.errors.pattern.requiredPattern + '\n'; } if (ngModel.errors.maxlength) { errorMessage += 'Value does not have required max length: ' + ngModel.errors.maxlength.requiredLength + '\n'; } if (ngModel.errors.minlength) { errorMessage += 'Value does not have required min length: ' + ngModel.errors.minlength.requiredLength + '\n'; } if (ngModel.errors.max) { errorMessage += 'Value is bigger than max: ' + ngModel.errors.max.max + '\n'; } if (ngModel.errors.min) { errorMessage += 'Value is smaller than min: ' + ngModel.errors.min.min + '\n'; } if (ngModel.errors.email) { errorMessage += 'Value is not a valid email\n'; } if (ngModel.errors.maxItems) { errorMessage += 'Selection exceeds the maximum number of items: ' + ngModel.errors.maxItems.maxItems + '\n'; } if (ngModel.errors.minItems) { errorMessage += 'Selection falls below the minimum number of items: ' + ngModel.errors.minItems.minItems + '\n'; } return errorMessage; } getUiElementForHalFormsTemplateProperty(property: any): string { if (property.options) { return 'select'; } return 'input'; } getHalFormsOptions(property: any): Array<DictionaryObject> { if (!property.options) { return []; } const options = property.options; const dictionaryObjects: Array<DictionaryObject> = []; if (!property.required && options.maxItems === 1 && !(options.minItems >= 1)) { dictionaryObjects.push(new DictionaryObject(this.noValueSelected, this.noValueSelected)); } const promptField = options?.promptField || 'prompt'; const valueField = options?.valueField || 'value'; if (options.inline) { if (!(options.inline instanceof Array)) { console.warn('HAL-FORMS: Selectable options for property "' + property.name + '" must be an array'); console.warn('=> Property "' + property.name + '" input will be rendered as HTML "input"'); property.options = undefined; // this leads to updating the HTML to 'input' instead of 'select' return dictionaryObjects; } for (const entry of options.inline) { if (typeof entry === 'string' || entry instanceof String) { dictionaryObjects.push(new DictionaryObject(entry, entry)); } else { if (entry[promptField] && entry[valueField]) { dictionaryObjects.push(new DictionaryObject(entry[promptField], entry[valueField])); } else { console.warn('HAL-FORMS: Selectable options for property "' + property.name + '" are not parsable'); console.warn('=> Property "' + property.name + '" input will be rendered as HTML "input"'); property.options = undefined; // this leads to updating the HTML to 'input' instead of 'select' return dictionaryObjects; } } } } return dictionaryObjects; } isHalFormsOptionSelected(property: any, value: string): boolean { if (!property.value) { return false; } return property.value.includes(value); } }
the_stack
import { Module } from "vuex" import { AppSession, CanvasEdge, CanvasNode, EdgeSchema, ModuleStore, NodeSchema, SessionStore } from "../StoreTypes"; import { toIsoString } from "@/assets/Math" import { titleCase } from "@/assets/String"; export default { state: { session: { namespace: "", canvas: { cameraX : 0, cameraY : 0, padding : 0, pageSizeX : 0, pageSizeY : 0 }, nodes: new Map() as Map<string, CanvasNode>, edges: new Map() as Map<string, CanvasEdge>, schema: null }, nodeIdCounter: 0, layoutTrigger: 0, }, actions: { /////////////////////////////////////////////////////////////////////// // 1. Session Import & Export /////////////////////////////////////// /////////////////////////////////////////////////////////////////////// /** * Opens and imports an Attack Flow save file into the store. * @param ctx * The Vuex context. * @param text * The save file's raw text. */ openAttackFlowSaveFile({ dispatch }, text: string) { let file = JSON.parse(text) as AppSession; dispatch("importSession", { session: file, schema: file.schema }); }, /** * Saves and downloads the current attack flow session. * @param ctx * The Vuex context. * @param name * The save file's name */ saveAttackFlow({ state, dispatch, rootState }, name: string) { if(state.session.nodes.size !== 0) { let session = { namespace: state.session.namespace, canvas: state.session.canvas, nodes: [...state.session.nodes.values()], edges: [...state.session.edges.values()], schema: state.session.schema } let file = JSON.stringify(session); dispatch("_downloadFile", { filename: name, text: file }) } else { dispatch("pushNotification", { type: "info", title: "NOTICE", description: "You can't save an empty session.", time: 2000 }) } }, /** * Compiles and downloads the current attack flow session. * @param ctx * The Vuex context. * @param saveParams * [name] * The save file's name. * [date] * The save date. */ async publishAttackFlow({ state, dispatch, rootState }, { name, date }: { name: string, date: Date}) { let namespace = state.session.namespace; // Export let $schema = `./${ name }` let flow = { type: "attack-flow", id: `http://${ namespace }`, name: "Attack Flow Export", author: "Unspecified", created: toIsoString(date) } try { // Validate schema let { nodeSchemas } = rootState.SchemaStore; let n = [...state.session.nodes.values()]; for(let [type, schema] of nodeSchemas) { let nodes = n.filter(o => o.type === type); for(let node of nodes) { if(!await dispatch("_validateObj", { obj: node, schema })) { throw `Required '${ titleCase(type) }' node fields are missing.` } } } let { edgeSchemas } = rootState.SchemaStore; let e = [...state.session.edges.values()]; for(let [type, schema] of edgeSchemas) { let edges = e.filter(o => o.type === type); for(let edge of edges) { if(!await dispatch("_validateObj", { obj: edge, schema })) { throw `Required '${ titleCase(type) }' edge fields are missing.` } } } /////////////////////////////////////////////////////////////// // The following code is designed specifically for the current // schema, changing the schema may break publish functionality. /////////////////////////////////////////////////////////////// // Uri Formatter let format = (str?: string | null) => str?.replace(/\s+|_/g, "-") ?? null; let getUri = (node?: CanvasNode | CanvasEdge) => { let n = `http://${ namespace }`; switch (node?.type) { case "action": case "asset": return `${ n }/${ format(node.type) }-${ node.id }` case "data_property": case "object_property_target": return `${ n }#${ format(node.payload.target) ?? null }` case "relationship": case "data_property_type": case "object_property_type": return `${ n }#${ format(node.payload.type) ?? null }` default: return n; } } // Actions let _actions = n.filter(o => o.type === "action"); let actions = []; for(let action of _actions) { actions.push({ id: getUri(action), type: action.type, name: action.payload.name ?? null, description: action.payload.description ?? null, timestamp: action.payload.timestamp ?? null, reference: action.payload.reference ?? null, succeeded: action.payload.succeeded ?? null, confidence: action.payload.confidence ?? null, logic_operator_language: action.payload.logic_operator_language ?? null, logic_operator: action.payload.logic_operator ?? null }) } // Assets let _assets = n.filter(o => o.type === "asset"); let assets = []; for(let asset of _assets) { assets.push({ id: getUri(asset), type: asset.type, state: asset.payload.state ?? null }) } // Edges let generateEdges = (type: string, targetIsUri: boolean) => { let _edges = e.filter(o => o.type === type); let edges = []; for(let e of _edges) { // Get source and target let src = state.session.nodes.get(e.sourceId); let trg = state.session.nodes.get(e.targetId); if(src === undefined || trg === undefined) throw `Broken ${ e.type } edge '${ src?.id ?? '?' } -> ${ trg?.id ?? '?' }'`; // Generate props edges.push({ source: getUri(src), type: getUri(e), target: targetIsUri ? getUri(trg) : trg.payload.target }) } return edges; } let relationships = generateEdges("relationship", true); let object_properties = generateEdges("object_property_type", true); let data_properties = generateEdges("data_property_type", false); // Links to flow let nodes = _actions.concat(_assets); for(let node of nodes) { relationships.push({ source: getUri(), type: `${ getUri() }#flow-edge`, target: getUri(node) }) } // Download let file = JSON.stringify({ $schema, flow, actions, assets, relationships, object_properties, data_properties }); dispatch("_downloadFile", { filename: name, text: file }) } catch(ex) { dispatch("pushNotification", { type: "error", title: "Export Failed", description: ex }) } }, /** * Imports a designer session and schema into the store. * @param ctx * The Vuex context. * @param * [session] * The designer session to import. * [schema] * The attack flow schema to use. */ async importSession({ commit, dispatch, state }, { session, schema }) { commit("clearSession"); // Load Schema await dispatch("loadSchema", schema); // Load Session commit("setSessionNamespace", session.namespace); commit("setCanvasState", session.canvas); commit("setSessionSchema", schema); for(let node of session.nodes) { // Add Node commit("addNode", node); } for(let edge of session.edges) { let source = state.session.nodes.get(edge.sourceId); let target = state.session.nodes.get(edge.targetId); if(source === undefined || target === undefined) continue; let edgeObj: CanvasEdge = { id: edge.id, sourceId: edge.sourceId, targetId: edge.targetId, source, target, type: edge.type, payload: edge.payload } // Add Edge commit("addEdge", edgeObj); } commit("recalculatePages"); commit("incrementLayoutTrigger"); }, /** * [INTERNAL USE ONLY] * Validates an object against its schema. * @param ctx * The Vuex context. * @param nodeParams * [node] * The object to validate. * [schema] * The schema to validate against. * @returns * True if the object matches the schema, false otherwise. */ _validateObj(ctx, { obj, schema }: SchemaValidationParams) { for(let [name, field] of schema.fields) { switch(field.type) { case "string": case "datetime": if(field.required && !obj.payload[name]) { return false; } } } return true; }, /** * [INTERNAL USE ONLY] * Downloads a text file to the local machine. * @param ctx * The Vuex context. * @param saveParams * [filename] * The save file's name. * [text] * The text contents of the file. */ _downloadFile(ctx, { filename, text }: { filename: string, text: string }) { // Create Blob let blob = new Blob([text], {type: "octet/stream"}); let url = window.URL.createObjectURL(blob); // Generate Link let a = document.createElement("a"); a.href = url; a.download = filename; // Download a.click(); window.URL.revokeObjectURL(url); }, /////////////////////////////////////////////////////////////////////// // 2. Graph Editing ///////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// /** * Creates a new graph node. * @param ctx * The Vuex context. * @param nodeParams * [type] * The node type. * [location] * Where the node should be placed on the canvas. */ createNode({ commit, rootState }, { type, location }: NodeParams) { let schema = rootState.SchemaStore?.nodeSchemas.get(type); if(schema !== undefined){ // Create default payload let payload: any = {} for(let [name, field] of schema.fields) payload[name] = field?.default // Create node let node: CanvasNode = { id: "-1", type: type, subtype: schema.subtype?.default, x0: location[0], y0: location[1], x1: location[0], y1: location[1], payload }; // Add node commit("addNode", node); } commit("recalculatePages"); commit("incrementLayoutTrigger"); }, /** * Sets a node's subtype field. * @param ctx * The Vuex context. * @param nodeParams * [id] * The id of the node to edit. * [value] * The new subtype value. */ setNodeSubtype({ commit }, nodeParams: SubTypeUpdate) { commit("setNodeSubtype", nodeParams); }, /** * Sets a node's field. * @param ctx * The Vuex context. * @param nodeParams * [id] * The id of the node to edit. * [field] * The name of the field. * [value] * The field's new value. */ setNodeField({ commit }, nodeParams: FieldUpdate) { commit("setNodeField", nodeParams); }, /** * Sets a node's lower right boundary. * @param ctx * The Vuex context. * @param positionParams * [id] * The id of the node to edit. * [x1] * The lower boundary's x coordinate. * [y1] * The lower boundary's y coordinate. */ setNodeLowerBound({ commit }, positionParams: { id: string, x1: number, y1: number }) { commit("setNodeLowerBound", positionParams) }, /** * Offsets a node's position by the given amount. * @param ctx * The Vuex context. * @param offsetParams * [id] * The id of the node to offset. * [x] * The amount to offset by on the x axis. * [y] * The amount to offset by on the y axis. */ offsetNode({ state, commit }, {id, x, y}: { id: string, x: number, y: number }) { let node = state.session.nodes.get(id); if(node !== undefined) { commit("setNodePosition", { id, x0: node.x0 + x, y0: node.y0 + y, x1: node.x1 + x, y1: node.y1 + y, }); }; }, /** * Creates a new graph edge. * @param ctx * The Vuex Context. * @param edgeParams * [type] * The edge type. * [source] * The edge's source node (specified by id). * [target] * The edge's target node (specified by id). */ async createEdge({ commit, rootState, dispatch, state }, { type, source, target }: EdgeParams) { // Get Nodes let srcNode = state.session.nodes.get(source); if(srcNode != undefined) { let trgNode = state.session.nodes.get(target); if(trgNode === undefined) return; // Resolve Type let type = await dispatch("getEdgeType", { source: srcNode.type, target: trgNode.type }) let schema = rootState.SchemaStore?.edgeSchemas.get(type); if(schema !== undefined) { // Create default payload let payload: any = {} for(let [name, field] of schema.fields) payload[name] = field?.default // Create Link let link: CanvasEdge = { id: `${ srcNode.id }.${ trgNode.id }`, sourceId: srcNode.id, targetId: trgNode.id, source: srcNode, target: trgNode, type: type, payload } commit("addEdge", link); } } }, /** * Sets an edge's field. * @param ctx * The Vuex context. * @param edgeParams * [id] * The id of the edge to edit. * [field] * The name of the field. * [value] * The field's new value. */ setEdgeField({ commit }, edgeParams: FieldUpdate) { commit("setEdgeField", edgeParams); }, /** * Duplicates a sequence of interconnected nodes. * @param ctx * The Vuex context. * @param ids * The set of nodes (specified by id) to duplicate. */ async duplicateSequence({ commit, dispatch, state }, ids) { // Duplicate nodes let newNodeMap = new Map<string, CanvasNode>() for(let id of ids) { let base = state.session.nodes.get(id); if(base !== undefined) { let node: CanvasNode = { id: "-1", type: base.type, subtype: base.subtype, x0: base.x0 + 100, y0: base.y0 + 100, x1: base.x1 + 100, y1: base.y1 + 100, payload: { ...base.payload } } newNodeMap.set(id, node); commit("addNode", node); } } // Duplicate dependent edges let edges = await dispatch("_getConnectedEdges", { ids, includeWeakLinks: false }); for(let id of edges) { let base = state.session.edges.get(id); if(base === undefined) continue; let source = newNodeMap.get(base!.sourceId); let target = newNodeMap.get(base!.targetId); if(source === undefined || target === undefined) continue; let edge: CanvasEdge = { id: `${ source.id }.${ target.id }`, sourceId: source.id, targetId: target.id, source, target, type: base.type, payload: { ...base.payload } } commit("addEdge", edge); } }, /** * Deletes a set of items from the graph. * @param ctx * The Vuex context. * @param ids * The items (specified by id) to delete. */ async deleteItems({ commit, dispatch }, ids) { // Partition ids let nodeIds: Array<string> = []; let edgeIds: Array<string> = []; for(let id of ids) (/^[0-9]+$/.test(id) ? nodeIds : edgeIds).push(id); // Delete edges commit("deleteEdges", edgeIds); // Delete nodes commit("deleteNodes", nodeIds); // Delete dependent edges let edges = await dispatch("_getConnectedEdges", { ids: nodeIds, includeWeakLinks: true }); commit("deleteEdges", edges); // Recalculate pages commit("recalculatePages"); }, /** * Recalculates the number of pages that make up the canvas. * * @param param0 */ recalculatePages({commit}) { commit("recalculatePages"); }, // Canvas Operations setCameraPosition({ commit }, args) { commit("setCameraPosition", args); }, /** * [INTERNAL USE ONLY] * Returns the set of edge's that connect to the given nodes. * @param ctx * The Vuex context. * @param queryParams * [ids] * The node's (specified by id) to evaluate. * [includeWeakLinks] * If true, a link only needs to have a source or a target in the set * to be included. If false, a link's source and target *must* be in * the set to be included. * @returns * The set of connected edges. */ _getConnectedEdges({ state }, { ids, includeWeakLinks }: { ids: Array<string>, includeWeakLinks: boolean }) { // Not ideal, graph traversal would be better, but this will work for now. let idsSet = new Set(ids); let edges: Array<string> = []; for(let [_, edge] of state.session.edges) { let isFullLink = idsSet.has(edge.sourceId) && idsSet.has(edge.targetId); let isWeakLink = idsSet.has(edge.sourceId) || idsSet.has(edge.targetId); if(isFullLink || (includeWeakLinks && isWeakLink)) { edges.push(edge.id); } } return edges; }, }, mutations: { /** * Clears the current session and configures the canvas state. * @param state * The Vuex state. * @param session * The session that's being imported. */ clearSession(state) { state.session.nodes.clear(); state.session.edges.clear(); }, /** * Sets the session's namespace. * @param state * The Vuex state. * @param namespace * The session's namespace. */ setSessionNamespace(state, namespace: string) { state.session.namespace = namespace; }, /** * Sets the canvas state. * @param state * The Vuex state. * @param session * The new canvas state. */ setCanvasState(state, canvas) { state.session.canvas = canvas; }, /** * Sets the session's (unparsed) schema. * @param state * The Vuex state. * @param schema * The session's (unparsed) schema. */ setSessionSchema(state, schema: any) { state.session.schema = schema; }, /** * Adds a node to the session store. * @param state * The Vuex state. * @param node * The node to add. */ addNode(state, node: CanvasNode) { // Assign ID if none set if(node.id === "-1") { node.id = `${ ++state.nodeIdCounter }`; } else { state.nodeIdCounter = Math.max(state.nodeIdCounter, parseInt(node.id)); } if(!state.session.nodes.has(node.id)) { state.session.nodes.set(node.id, node); } }, /** * Sets a node's subtype field. * @param state * The Vuex state. * @param nodeParams * [id] * The id of the node to edit. * [value] * The new subtype value. */ setNodeSubtype(state, { id, value }: SubTypeUpdate) { let node = state.session.nodes.get(id); if(node !== undefined) { node.subtype = value; } }, /** * Sets a nodes's field. * @param state * The Vuex state. * @param edgeParams * [id] * The id of the node to edit. * [field] * The name of the field. * [value] * The field's new value. */ setNodeField(state, { id, field, value }: FieldUpdate) { let node = state.session.nodes.get(id); if(node !== undefined) { node.payload[field] = value } }, /** * Deletes a set of nodes from the session store. * @param state * The Vuex state. * @param ids * The set of nodes (specified by id) to delete. */ deleteNodes(state, ids: Array<string>) { for(let id of ids) { state.session.nodes.delete(id); } }, /** * Sets a node's lower right boundary. * @param state * The Vuex state. * @param positionParams * [id] * The id of the node to edit. * [x1] * The lower boundary's x coordinate. * [y1] * The lower boundary's y coordinate. */ setNodeLowerBound(state, { id, x1, y1 }: { id: string, x1: number, y1: number }){ let node = state.session.nodes.get(id); if(node !== undefined) { node.x1 = x1; node.y1 = y1; } }, /** * Sets a nodes position on the canvas. * @param state * The Vuex state. * @param positionParams */ setNodePosition(state, { id, x0, y0, x1, y1 }: NodePosition) { let node = state.session.nodes.get(id); if(node !== undefined) { node.x0 = x0; node.y0 = y0; node.x1 = x1; node.y1 = y1; } }, /** * Adds an edge to the session store. * @param state * The Vuex state. * @param edge * The edge to add. */ addEdge(state, edge: CanvasEdge) { if(!state.session.edges.has(edge.id)) { state.session.edges.set(edge.id, edge); } }, /** * Sets an edge's field. * @param state * The Vuex state. * @param edgeParams * [id] * The id of the edge to edit. * [field] * The name of the field. * [value] * The field's new value. */ setEdgeField(state, { id, field, value }: FieldUpdate) { let edge = state.session.edges.get(id); if(edge !== undefined) { edge.payload[field] = value } }, /** * Deletes a set of edges from the session store. * @param state * The Vuex state. * @param ids * The set of edges (specified by id) to delete. */ deleteEdges(state, ids: Array<string>) { for(let id of ids) { state.session.edges.delete(id); } }, /** * Stores the current camera position. * @param state * The Vuex state. * @param positionParams * [x] * The x coordinate of the camera. * [y] * The y coordinate of the camera. */ setCameraPosition(state, {x, y}: { x: number, y: number }) { state.session.canvas.cameraX = x; state.session.canvas.cameraY = y; }, recalculatePages(state) { // Skip if no nodes if(state.session.nodes.size === 0) return; // Compute upper-left bound let [x, y] = [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY]; for(let [_, node] of state.session.nodes) { x = Math.min(node.x0, x); y = Math.min(node.y0, y); } // Compute xOffset and yOffset correction let { pageSizeX, pageSizeY, padding } = state.session.canvas; // xRemaining = (x-padding) % pageSizeX (below "fixes" negative mod in JS) let xRemaining = (((x-padding) % pageSizeX) + pageSizeX) % pageSizeX; let xOffset = x - (xRemaining + padding) // yRemaining = (x-padding) % pageSizeY (below "fixes" negative mod in JS) let yRemaining = (((y-padding) % pageSizeY) + pageSizeY) % pageSizeY; let yOffset = y - (yRemaining + padding); // If offset correction required: if(xOffset !== 0 || yOffset !== 0) { for(let [_, node] of state.session.nodes) { node.x0 -= xOffset; node.y0 -= yOffset; node.x1 -= xOffset; node.y1 -= yOffset; } // Correct Camera state.session.canvas.cameraX -= xOffset; state.session.canvas.cameraY -= yOffset; } }, /** * Increments the layout trigger. * @param state * The Vuex state. */ incrementLayoutTrigger(state){ state.layoutTrigger++; } } } as Module<SessionStore, ModuleStore> /////////////////////////////////////////////////////////////////////////////// // Internal Types /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// type EdgeParams = { type: string, source: string, target: string }; type NodeParams = { type: string, location: Array<number> } type SubTypeUpdate = { id: string, value: any }; type FieldUpdate = { id: string, field: string, value: any }; type NodePosition = { id: string, x0: number, y0: number, x1: number, y1: number }; type SchemaValidationParams = { obj: CanvasNode | CanvasEdge, schema: NodeSchema | EdgeSchema }
the_stack
import React from "react"; import { Carousel, Content } from "../src/components/Carousel"; import styled from "styled-components"; import Icon from "./Icon"; import { useRect } from "../utilities/hooks"; import { Tab, Tabs } from "../src/components/Tabs"; import { HostApi } from "../webview-api"; import { PanelHeader } from "../src/components/PanelHeader"; import ScrollBox from "./ScrollBox"; import CancelButton from "./CancelButton"; import { closePanel } from "./actions"; import { useDispatch, useSelector } from "react-redux"; import { Dialog } from "../src/components/Dialog"; const Root = styled.div` color: var(--text-color); position: relative; h2, h3 { color: var(--text-color-highlight); } h3 { margin: 30px 0 5px 0; .icon { margin-right: 5px; vertical-align: -2px; } } ${Carousel} { max-width: 600px; } `; const Diagram = styled.div` position: relative; display: inline-block; width: 600px; height: 175px; transform-origin: top left; // background: rgba(127, 127, 127, 0.05); `; const Contents = styled.div` position: absolute; top: 0; bottom: 0; left: 0; right: 0; `; export const GitTimeline = styled.div` position: absolute; top: 30px; width: 100%; height: 3px; background: #999; margin-top: -1px; &:after { content: ""; position: absolute; right: -6px; top: -5px; width: 0; height: 0; border-top: 7px solid transparent; border-left: 15px solid #999; border-bottom: 7px solid transparent; transition: transform ease-out 0.2s; } .simplified & { top: 123px; width: 200px; right: 0; &:before { content: ""; position: absolute; left: -400px; width: 280px; height: 3px; background: #999; } } .adhoc & { top: 123px; top: 25px; } `; export const BranchLineDown = styled.div` position: absolute; width: 3px; background: #999; height: 50px; top: 50px; left: 70px; `; export const BranchCurve = styled.div` position: absolute; top: 75px; left: 70px; width: 3px; width: 50px; height: 50px; border: 3px solid #999; border-color: #999 transparent transparent transparent; border-radius: 50%; transform: rotate(225deg); `; export const BranchLineAcross = styled.div` position: absolute; height: 3px; width: 186px; background: #999; top: 122px; left: 95px; `; const MergeLineDown = styled.div` position: absolute; width: 3px; background: #999; height: 50px; top: 50px; right: 70px; `; const MergeLineAcross = styled.div` position: absolute; height: 3px; width: 106px; background: #999; top: 122px; left: 399px; z-index: 0; `; const MergeCurve = styled.div` position: absolute; top: 75px; right: 70px; width: 3px; width: 50px; height: 50px; border: 3px solid #999; border-color: #999 transparent transparent transparent; border-radius: 50%; transform: rotate(135deg); `; const Action = styled.div` position: absolute; display: flex; justify-content: center; align-items: center; cursor: pointer; width: 40px; height: 40px; border-radius: 50%; background: #999; top: 103px; .adhoc & { top: 25px; } z-index: 2; &:before { content: ""; position: absolute; top: 3px; left: 3px; width: 34px; height: 34px; border-radius: 50%; background: var(--base-border-color); } .icon { display: inline-block; transform: scale(1.5); color: #999; } transition: transform ease-out 0.2s; &.active, &:hover:not(.no-hover) { z-index: 3; background: var(--button-background-color); color: var(--button-foreground-color); background: #999; color: var(--base-border-color); .icon { color: var(--button-foreground-color); color: var(--base-border-color); } &:before { background: #999; // background: var(--button-background-color); } box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2); .vscode-dark & { box-shadow: 0 3px 10px rgba(0, 0, 0, 0.4); } transform: scale(1.5); } `; export const GitBranch = styled(Action)` top: 10px; left: 52px; .icon { margin-left: 1px; } `; const GrabTicket = styled(Action)` left: 40px; svg { padding: 1px 0 0 0; } `; const GitMerge = styled(Action)` top: 10px; right: 52px; .icon { margin-left: 1px; } `; const Upload = styled(Action)` left: 520px; `; const CreatePR = styled(Action)` top: 10px; right: 52px; .icon { margin-left: 1px; } `; const Edit = styled(Action)` left: 120px; `; const Review = styled(Action)` left: 200px; .adhoc & { left: 360px; } `; const Team = styled(Action)` .adhoc & { left: 440px; } `; const Comment = styled(Action)` top: -6px; left: -6px; .adhoc & { // top: 102px; top: 25px; left: 120px; } `; const Issue = styled(Action)` top: auto; bottom: 0; left: -6px; .adhoc & { // top: 102px; top: 25px; bottom: auto; left: 200px; } `; const Amend = styled(Action)` top: -6px; right: 0; left: auto; svg { padding: 1px 0 0 1px; } `; const Permalink = styled(Action)` left: 280px; `; const Fix = styled(Action)` top: auto; bottom: 0; left: auto; right: 0; `; const Approve = styled(Action)` left: 440px; `; const DiscussionCircle = styled.div` position: absolute; top: 60px; left: 280px; width: 120px; height: 120px; border: 3px solid #999; border-radius: 50%; z-index: 2; `; const DiscussionAnimate = styled.div` position: relative; width: 120px; height: 120px; transition: transform 1s ease-out; &.rotate { transform: rotate(360deg); } &.rotate .icon { transform: scale(1.5) rotate(-360deg); } z-index: 2; ${Comment}, ${Issue}, ${Fix}, ${Amend} { z-index: 2; .icon { display: inline-block; transition: transform 1s ease-out; } } `; const Commit = styled.div` top: 116px; left: 173px; position: absolute; display: flex; height: 15px; width: 15px; z-index: 4; cursor: pointer; &:before { content: ""; position: absolute; top: 0px; left: 0px; width: 15px; height: 15px; border-radius: 50%; background: #999; } &:after { content: ""; position: absolute; top: 3px; left: 3px; width: 9px; height: 9px; border-radius: 50%; background: var(--base-border-color); } &.second { left: 273px; } &.third { top: 54px; left: 333px; } &.fourth { top: 172px; left: 333px; } &.fifth { left: 392px; } transition: transform ease-out 0.2s; // transform-origin: 21px 0; .active &, :hover { box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2); .vscode-dark& { box-shadow: 0 3px 10px rgba(0, 0, 0, 0.4); } transform: scale(1.5); &:after { background: #999; } } `; const Key = styled.span` font-size: 13px; vertical-align: 3px; padding-left: 5px; white-space: nowrap; `; export const VideoLink = styled.a` margin-top: 30px; display: flex; align-items: center; > img { height: 22px; cursor: pointer; opacity: 0.8; margin-right: 5px; } > span { text-decoration: none !important; } &:hover > img { opacity: 1; text-shadow: 0 5px 10px rgba(0, 0, 0, 0.8); } `; const Desc = styled.div` margin: 0 0 20px 0; `; const CreateBranch = ( <Content> <h2>Start Work: Grab a Ticket &amp; Create a Branch</h2> When you're working on a team, you're going to have a bunch of different features or ideas in progress at any given time – some of which are ready to go, and others which are not. Branching exists to help you manage this workflow. <br /> <br /> When you create a branch in your project, you're creating an environment where you can try out new ideas. Changes you make on a branch don't affect the main branch, so you're free to experiment and commit changes, safe in the knowledge that your branch won't be merged until it's been reviewed by someone you're collaborating with. <br /> <br /> CodeStream makes it easy to get started by integrating with your issue provider, so you can grab a ticket without leaving your IDE, and your status is shared automatically with your team. <VideoLink href={"https://youtu.be/4MHv8hta02s"}> <img src="https://i.imgur.com/9IKqpzf.png" /> <span>Grab a Ticket &amp; Create a Branch</span> </VideoLink> </Content> ); const StartWritingCode = ( <Content> <h2>Begin Writing Code</h2> Once you've grabbed a ticket, it's time to start making changes. Whenever you add, edit, or delete a file, you can share those changes with your teammates to get feedback. <br /> <br /> When you have questions about existing code, asking is as easy as selecting the code and typing your question. CodeStream automatically captures the context of your editor when sharing your question with the team, so no context switch is required for you or your teammates. Your teammates can participate in this discussion directly in their IDE, or via integrations with Slack, MS Teams, or email. <VideoLink href={"https://www.youtube.com/watch?v=RPaIIZgaFK8"}> <img src="https://i.imgur.com/9IKqpzf.png" /> <span>If I ask comments on my local branch, how do my teammates see them?</span> </VideoLink> </Content> ); const RequestFeedback = ( <Content> <h2>Request Feedback from Your Team</h2> With one command, request feedback on a snapshot of your repo, including uncommitted &amp; unpushed code, allowing you to verify that your work-in-progress is on the right track. (You can also do it the old-fashioned way by committing &amp; pushing at the end of your dev sprint, of course.) <br /> <br /> Review teammates’ code in your IDE, with full source tree context, your favorite keybindings, jump-to-definition, and the environment you're used to. <br /> <br /> Comments on reviews are visible in your IDE as source code annotations after merging, creating a historical record of discussions and decisions. <h3>Exclusive</h3> CodeStream makes it easier to get feedback earlier in your dev cycle by disconnecting discussion about code with commit flow. This means you can request a review on code you haven't committed &amp; pushed yet, and CodeStream will take care of the mechanics of making sure your teammate can see your changes by packaging up a diffset along with the review object. <VideoLink href={"https://youtu.be/2AyqT4z5Omc"}> <img src="https://i.imgur.com/9IKqpzf.png" /> <span>Feedback Request Walkthrough</span> </VideoLink> </Content> ); const DiscussAndRefine = ( <Content> <h2>Discuss and Refine Your Changes</h2> Whether your code was a work-in-progress or was ready for final review, chances are pretty good your teammates might have some suggestions to make it even better. Whether it's a simple thumbs-up, or a tear-it-to-the-ground set of suggestions for a rewrite (hope not!), CodeStream makes it easy to both give and receive feedback in real-time, using modern messaging semantics. <br /> <br /> Unlike other systems, your discussion and commit cadance can be disconnected. This means you can share, review, and discuss code without worrying about committing it first. <VideoLink href={"FIXME"} style={{ display: "none" }}> <img src="https://i.imgur.com/9IKqpzf.png" /> <span>Updating a Feedback Request to Address Changes</span> </VideoLink> </Content> ); const GetFinalApproval = ( <Content> <h2>Get Final Approval</h2> CodeStream's feedback requests can be reviewed by multiple people, with assignment based on changed code, round-robin, or random chance. You can set things up where everyone on the team has to give the thumbs-up, or the first person who approves the review wins. <br /> <br /> However your team works, CodeStream provides the tools to make it easy and transparent, sharing every status change with the team through the Acitivty feed, at-mentions, and configurable notifications. <VideoLink href={"FIXME"} style={{ display: "none" }}> <img src="https://i.imgur.com/9IKqpzf.png" /> <span>How are reviewers assigned?</span> </VideoLink> </Content> ); // const GetPreliminaryApproval = ( // <Content> // <h2>Get Preliminary Approval</h2> // Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut // labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco // laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in // voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat // non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. // <h3>Exclusive</h3> // <Icon name="checked-checkbox" /> Reviewers are based on a variety of ... // <VideoLink href={"FIXME"}> // <img src="https://i.imgur.com/9IKqpzf.png" /> // <span>How are reviewers assigned?</span> // </VideoLink> // </Content> // ); const CreatePRAndMerge = ( <Content> <h2>Create a PR and Merge</h2> Once you get final approval, it's time to publish your changes. CodeStream integrates with your PR provider, whether it's GitHub, BitBucket or GitLab, cloud-based or on-prem. Creating a PR is a simple two-click process, capturing the context and history of your development workflow, from grabbing a ticket, through discussion and review, until final approval. <br /> <br /> Once the PR is created, final signoff should be a breeze, so code can be merged in on-time and stress-free. <VideoLink href={"FIXME"} style={{ display: "none" }}> <img src="https://i.imgur.com/9IKqpzf.png" /> <span>How do I connect to my code host provider?</span> </VideoLink> </Content> ); // const CreatePRAndRequestApproval = ( // <Content> // <h2>Create a PR and Request Final Approval</h2>A PR will be created which references the // changes, discussion, and approvals on CodeStream, making the final PR approval a walk in the // park. // <h3>Exclusive</h3> // <Icon name="mark-github" /> CodeStream works with the on-prem and cloud-based versions of // GitHub, GitLab, and BitBucket. // <VideoLink href={"FIXME"}> // <img src="https://i.imgur.com/9IKqpzf.png" /> // <span>How do I connect to my source host provider?</span> // </VideoLink> // </Content> // ); const twitterUrl = "https://twitter.com/intent/tweet?ref_src=twsrc%5Etfw&related=twitterapi%2Ctwitter&tw_p=tweetbutton&via=teamcodestream"; const FinalThought = ( <Content> <h2>Final Thought</h2> There are many different ways that CodeStream can be used, and it's worth noting that you can mix-and-match different strategies if that suits your team. For larger features, go ahead and create a branch to contain your changes, but even for one-line fixes, CodeStream makes it easy to get a quick second set of eyes on it before you merge directly to master and push. <br /> <br /> If you've read this far, we'd love to hear your feedback and how CodeStream can help your team succeed. <br /> <br /> <a href="mailto:pez@codestream.com?Subject=CodeStream+Feedback">Email the CEO</a> or{" "} <a href={twitterUrl}>Let us know on Twitter</a> </Content> ); const CommitAndPush = ( <Content> <h2>Commit &amp; Push</h2> Trunk-based development means there isn't a lot of ceremony between review approval and getting code merged in. Once your teammates give you the thumbs-up, you can do any final commits, push your code, and move on to the next project. CodeStream updates your status automatically to let you know you've finished. Congrats! </Content> ); const GrabATicket = ( <Content> <h2>Start Work: Grab a Ticket</h2> If your team uses Jira, Trello, GitHub or a similar service, CodeStream makes it easy to get to work by grabbing a ticket that's assigned to you, and sharing your status with the team. When you request a code review, it is automatically joined to the ticket so your teammates understand the context of your changes. Down the road, you can connect the dots in reverse, going from code to commit to review to ticket, to get a better understanding not only of what changed, but also why. <VideoLink href={"FIXME"} style={{ display: "none" }}> <img src="https://i.imgur.com/9IKqpzf.png" /> <span>How do I grab a ticket?</span> </VideoLink> </Content> ); const CommentOnCode = ( <Content> <h2>Discuss Any Code, Anytime</h2> Discussing code is as simple as "select the code, type your comment", whether it's old code you're trying to figure out, new code you've just written, or code that one of your teammates just changed. <br /> <br /> A simple use-cases is when you see code for the first time and don't quite grok it, just select it and ask your teammates "how does this work?" CodeStream will at-mention the code authors and share your comment on Slack, MS Teams, or via email, to make it easier to get an answer from the right person. <br /> <br /> Your code discussions remain connected to the lines of code being discussed via in-IDE annotations, even as you merge in new code or refactor. <VideoLink href={"https://youtu.be/RPaIIZgaFK8"}> <img src="https://i.imgur.com/9IKqpzf.png" /> <span>Discussing Code with CodeStream</span> </VideoLink> </Content> ); const FileAnIssue = ( <Content> <h2>Perform Ad-hoc Code Review</h2> Pre-merge code review is a great way to maintain code quality and share information on your team. CodeStream also allows you to do a code review post-merge, as you come across code smell that you want to ensure gets fixed. <br /> <br /> CodeStream integrates with nine popular issue tracking services such as Jira and Trello, allowing you to create tickets as you come across code that needs to be fixed. It's as simple as selecting the code and clicking an icon, and CodeStream takes care of creating the ticket for you, and capturing all the context for the assignee. <VideoLink href={"https://youtu.be/lUI110T_SHY"}> <img src="https://i.imgur.com/9IKqpzf.png" /> <span>Ad-hoc Code Review</span> </VideoLink> </Content> ); const GrabAPermalink = ( <Content> <h2>Share Code Anywhere</h2> Technical discussion is often spread across different services: project management, team chat, documentation wikis and code hosts just to name a few. Until now, if you wanted to share a block of code that would still refer to the same location in your codebase over time, you were pretty much out of luck. <br /> <br /> CodeStream's permalinks allow you to select a block of code and share a link to it, and that link will stay <b>live</b>, pointing to the right locaion within your codebase, even as your code evolves and you merge new code in. <VideoLink href={"FIXME"} style={{ display: "none" }}> <img src="https://i.imgur.com/9IKqpzf.png" /> <span>How do live permalinks work?</span> </VideoLink> </Content> ); const CheckTeamStatus = ( <Content> <h2>Check Your Teammates' Status</h2> Live View allows you to (optionally) see your teammates’ local changes at-a-glance, and highlights potential merge conflicts pre-commit. <br /> <br /> As your teammates create new branches, grab tickets, and make progress writing code, everything is shared on one team dashboard giving you unprecedented visibility into who is working on what. <VideoLink href={"https://youtu.be/h5KI3svlq-0"}> <img src="https://i.imgur.com/9IKqpzf.png" /> <span>CodeStream Live View</span> </VideoLink> </Content> ); const FLOW_CONTENT = { adhoc: [CommentOnCode, FileAnIssue, GrabAPermalink, RequestFeedback, CheckTeamStatus], simplified: [ GrabATicket, StartWritingCode, RequestFeedback, DiscussAndRefine, GetFinalApproval, CommitAndPush ], standard: [ CreateBranch, StartWritingCode, RequestFeedback, DiscussAndRefine, GetFinalApproval, CreatePRAndMerge, FinalThought ] // rigorous: [ // CreateBranch, // StartWritingCode, // CommitAndPush, // RequestFeedback, // DiscussAndRefine, // GetPreliminaryApproval, // CreatePRAndRequestApproval // ] }; export const FlowPanel = () => { const dispatch = useDispatch(); const [activeTab, setActiveTab] = React.useState("1"); return ( <Dialog maximizable wide noPadding onClose={() => dispatch(closePanel())}> <PanelHeader title="CodeStream Flow"> <div style={{ height: "5px" }} /> </PanelHeader> <div style={{ padding: "20px" }}> <Tabs style={{ marginTop: 0 }}> <Tab onClick={e => setActiveTab(e.target.id)} active={activeTab === "1"} id="1"> The Basics </Tab> <Tab onClick={e => setActiveTab(e.target.id)} active={activeTab === "2"} id="2"> Trunk Flow </Tab> <Tab onClick={e => setActiveTab(e.target.id)} active={activeTab === "3"} id="3"> Branch Flow </Tab> </Tabs> {activeTab === "1" && ( <Content active> <Flow flow="adhoc" /> </Content> )} {activeTab === "2" && ( <Content active> <Flow flow="simplified" /> </Content> )} {activeTab === "3" && ( <Content active> <Flow flow="standard" /> </Content> )} </div> </Dialog> ); }; export const Flow = (props: { flow: "adhoc" | "simplified" | "standard"; active?: number }) => { // const [flow, setFlow] = React.useState("standard"); const [active, setActive] = React.useState(props.active || 0); const [rotate, setRotate] = React.useState(false); const rootRef = React.useRef(null); const rootDimensions = useRect(rootRef, []); const scale = Math.min(rootDimensions.width / 600, 1); const { flow } = props; const clickAction = index => { setActive(index); if (flow === "simplified" && index === 3) setRotate(!rotate); if (flow === "standard" && index === 3) setRotate(!rotate); HostApi.instance.track("Flow Step Viewed", { "Tour Step": flow === "adhoc" ? "The Basics" : flow === "simplified" ? "Trunk Flow" : "Branch Flow", "Flow Step Viewed": index }); // if (flow === "rigorous" && index === 4) setRotate(!rotate); }; const setFlow = () => {}; const clickFlow = e => { // setFlow(e.target.id); setActive(0); }; const flowDescriptions = { adhoc: ( <Desc> Examples of ad-hoc CodeStream use cases that can help in all stages of product development. </Desc> ), simplified: ( <Desc> Ultra-lightweight, discussion-driven, trunk-based workflow with frequent code review. Best for smaller teams, or teams where work is divided into very small chunks. </Desc> ), standard: ( <Desc> Lightweight, discussion-driven, branch-based workflow with frequent code review. Best for larger teams, or teams with longer-lived feature branches. </Desc> ), rigorous: ( <Desc> Branch-based flow with frequent pushes, frequent code review, and final signoff on GitHub. </Desc> ) }; // <p> // CodeStream Flow is an ultra-lightweight, discussion-based workflow that supports teams and // projects where code is reviewed and merged regularly. This guide explains how CodeStream can // make every step of the process easier for you and your team. // </p> const height = flow === "adhoc" ? 100 : flow === "simplified" ? 150 : 200; return ( <Root ref={rootRef}> {flowDescriptions[flow]} <div style={{ transform: `scale(${scale})`, position: "absolute", width: "100%", transformOrigin: "top left", textAlign: "center", marginTop: flow === "simplified" ? `${-50 * scale}px` : 0 }} className={flow} > <Diagram> {flow === "adhoc" && ( <Contents> <Comment className={active === 0 ? "active" : ""} onClick={() => clickAction(0)}> <Icon name="comment" /> </Comment> <Issue className={active === 1 ? "active" : ""} onClick={() => clickAction(1)}> <Icon name="issue" /> </Issue> <Permalink className={active === 2 ? "active" : ""} onClick={() => clickAction(2)}> <Icon name="link" /> </Permalink> <Review className={active === 3 ? "active" : ""} onClick={() => clickAction(3)}> <Icon name="review" /> </Review> <Team className={active === 4 ? "active" : ""} onClick={() => clickAction(4)}> <Icon name="team" /> </Team> </Contents> )} {flow === "simplified" && ( <Contents> <GitTimeline /> <GrabTicket className={active === 0 ? "active" : ""} onClick={() => clickAction(0)}> <Icon name="ticket" /> </GrabTicket> <Edit className={active === 1 ? "active" : ""} onClick={() => clickAction(1)}> <Icon name="pencil" /> </Edit> <Review className={active === 2 ? "active" : ""} onClick={() => clickAction(2)}> <Icon name="review" /> </Review> <DiscussionCircle> <DiscussionAnimate className={rotate ? "rotate" : ""}> <Comment className={active === 3 ? "active" : ""} onClick={() => clickAction(3)}> <Icon name="comment" /> </Comment> <Issue className={active === 3 ? "active" : ""} onClick={() => clickAction(3)}> <Icon name="issue" /> </Issue> <Amend className={active === 3 ? "active" : ""} onClick={() => clickAction(3)}> <Icon name="plus" /> </Amend> <Fix className={active === 3 ? "active" : ""} onClick={() => clickAction(3)}> <Icon name="checked-checkbox" /> </Fix> </DiscussionAnimate> </DiscussionCircle> <Approve className={active === 4 ? "active" : ""} onClick={() => clickAction(4)}> <Icon name="thumbsup" /> </Approve> <Upload className={active === 5 ? "active" : ""} onClick={() => clickAction(5)}> <Icon name="upload" /> </Upload> </Contents> )} {flow === "standard" && ( <Contents> <GitTimeline /> <BranchLineDown /> <BranchCurve /> <BranchLineAcross /> <GitBranch className={active === 0 ? "active" : ""} onClick={() => clickAction(0)}> <Icon name="git-branch" /> </GitBranch> <Edit className={active === 1 ? "active" : ""} onClick={() => clickAction(1)}> <Icon name="pencil" /> </Edit> <Review className={active === 2 ? "active" : ""} onClick={() => clickAction(2)}> <Icon name="review" /> </Review> <DiscussionCircle> <DiscussionAnimate className={rotate ? "rotate" : ""}> <Comment className={active === 3 ? "active" : ""} onClick={() => clickAction(3)}> <Icon name="comment" /> </Comment> <Issue className={active === 3 ? "active" : ""} onClick={() => clickAction(3)}> <Icon name="issue" /> </Issue> <Amend className={active === 3 ? "active" : ""} onClick={() => clickAction(3)}> <Icon name="plus" /> </Amend> <Fix className={active === 3 ? "active" : ""} onClick={() => clickAction(3)}> <Icon name="checked-checkbox" /> </Fix> </DiscussionAnimate> </DiscussionCircle> <Approve className={active === 4 ? "active" : ""} onClick={() => clickAction(4)}> <Icon name="thumbsup" /> </Approve> <CreatePR className={active === 5 ? "active" : ""} onClick={() => clickAction(5)}> <Icon name="pull-request" /> </CreatePR> <MergeLineAcross /> <MergeCurve /> <MergeLineDown /> </Contents> )} {false && ( <Contents> <GitTimeline /> <BranchLineDown /> <BranchCurve /> <BranchLineAcross /> <GitBranch className={active === 0 ? "active" : ""} onClick={() => clickAction(0)}> <Icon name="git-branch" /> </GitBranch> <Edit className={active === 1 ? "active" : ""} onClick={() => clickAction(1)}> <Icon name="pencil" /> </Edit> <div className={active === 2 ? "active" : ""} onClick={() => clickAction(2)}> <Commit /> <Commit className="second" /> <Commit className="third" /> <Commit className="fourth" /> <Commit className="fifth" /> </div> <Review className={active === 3 ? "active" : ""} onClick={() => clickAction(3)}> <Icon name="review" /> </Review> <DiscussionCircle> <DiscussionAnimate className={rotate ? "rotate" : ""}> <Comment className={active === 4 ? "active" : ""} onClick={() => clickAction(4)}> <Icon name="comment" /> </Comment> <Issue className={active === 4 ? "active" : ""} onClick={() => clickAction(4)}> <Icon name="issue" /> </Issue> <Amend className={active === 4 ? "active" : ""} onClick={() => clickAction(4)}> <Icon name="plus" /> </Amend> <Fix className={active === 4 ? "active" : ""} onClick={() => clickAction(4)}> <Icon name="checked-checkbox" /> </Fix> </DiscussionAnimate> </DiscussionCircle> <Approve className={active === 5 ? "active" : ""} onClick={() => clickAction(5)}> <Icon name="thumbsup" /> </Approve> <CreatePR className={active === 6 ? "active" : ""} onClick={() => clickAction(6)}> <Icon name="pull-request" /> </CreatePR> <MergeLineAcross /> <MergeCurve /> <MergeLineDown /> </Contents> )} </Diagram> </div> <div style={{ marginTop: `${scale * height}px`, textAlign: "center" }}> <Carousel active={active} lastContent={FLOW_CONTENT[flow].length - 1} onChange={value => clickAction(value)} > {FLOW_CONTENT[flow][active]} </Carousel> </div> </Root> ); };
the_stack
import { AvNodeTransform, InitialInterfaceLock, MinimalPose, minimalPoseFromTransform, EndpointAddr } from '@aardvarkxr/aardvark-shared'; import bind from 'bind-decorator'; import { EntityComponent } from './aardvark_composed_entity'; import { ActiveInterface } from './aardvark_interface_entity'; import { NetworkedGadgetComponent, NetworkGadgetEvent, NetworkGadgetEventType, NGESendEvent, NGESetGadgetInfo, NGESetItemInfo, NGESetTransformState, NetworkItemTransform } from './component_networked_gadget'; import { AvEntityChild } from './aardvark_entity_child'; import { AvTransform } from './aardvark_transform'; import * as React from 'react'; export enum NetworkUniverseEventType { /** Sent when the remote universe should start a gadget on behalf of the the network universe. */ CreateRemoteGadget = "create_remote_gadget", /** Sent when the remote universe should destroy a gadget on behalf of the network universe. */ DestroyRemoteGadget = "destoy_remote_gadget", /** Sent when the remote universe should update a remote gadget's transform relative to the universe. */ UpdateRemoteGadgetTransform = "update_remote_gadget_transform", /** Sent when the network universe is conveying an event from a networked gadget to a remote gadget. */ BroadcastRemoteGadgetEvent = "broadcast_remote_gadget_event", /** Sent when a remote universe is is conveying an even from a remote gadget to the networked gadget. */ SendMasterGadgetEvent = "send_master_gadget_event", /** Sent when an item in a remote gadget is being moved around and wants to override the transform * of the source gadget's item. */ UpdateNetworkItemTransform = "update_network_item_transform", /** Starts a grab from the remote side. Local side should stop being grabbable and start obeying * remote transform updates. */ StartItemGrab = "start_item_grab", /** Ends a grab from the remote side. Local side should start being grabbable and stop obeying * remote transform updates. */ EndItemGrab = "end_item_grab", } export interface NetworkUniverseEvent { type: NetworkUniverseEventType; remoteGadgetId: number; itemId?: string; gadgetUrl?: string; remoteInterfaceLocks?: InitialInterfaceLock[]; universeFromGadget?: MinimalPose; event?: object; gadgetInfo?: NetworkedGadgetInfo; } export interface NetworkedItemInfo { itemId: string; remoteUniverseFromItem: MinimalPose; } export interface NetworkedGadgetInfo { remoteGadgetId: number; url: string; remoteLocks: InitialInterfaceLock[]; universeFromGadget: MinimalPose; items: NetworkedItemInfo[]; } enum NetworkedGrabState { None, Remote, RemoteDropping, Local, } interface NetworkedItemInfoInternal { itemId: string; iface: ActiveInterface; remoteUniverseFromItem?: MinimalPose; grabState: NetworkedGrabState; } interface NetworkedGadgetInfoInternal { remoteGadgetId?: number; url?: string; remoteLocks?: InitialInterfaceLock[]; iface: ActiveInterface; items: Map< string, NetworkedItemInfoInternal >; } export interface UniverseInitInfo { gadgets: NetworkedGadgetInfo[]; } /** A network that can be used with AvComposedComponent. The arguments below are for the * provided callback function. * * @param event An object, opaque to the room itself, that allows the network universe to * communicate with its remote peers. * @param reliable If this argument is true, the room must deliver the message to every remote * universe or that universe will be out of synch with the network universe. */ export class NetworkUniverseComponent implements EntityComponent { private networkedGadgetsByEndpointId = new Map< number, NetworkedGadgetInfoInternal >(); private networkedGadgetsByRemoteId = new Map< number, NetworkedGadgetInfoInternal >(); static nextRemoteGadgetId = 1; private networkEventCallback: ( event: object, reliable: boolean ) => void; private entityCallback: () => void = null; constructor( networkEventCallback: ( event: object, reliable: boolean ) => void ) { this.networkEventCallback = networkEventCallback; } public onUpdate( callback: () => void ) { this.entityCallback = callback; } @bind private onNetworkInterface( activeNetworkedGadget: ActiveInterface ) { let gadgetInfo: NetworkedGadgetInfoInternal = this.networkedGadgetsByEndpointId.get( activeNetworkedGadget.peer.endpointId ); if( !gadgetInfo ) { gadgetInfo = { iface: activeNetworkedGadget, items: new Map<string, NetworkedItemInfoInternal>(), }; this.networkedGadgetsByEndpointId.set( activeNetworkedGadget.peer.endpointId, gadgetInfo ); } let itemInfo: NetworkedItemInfoInternal; activeNetworkedGadget.onEvent( ( event: NetworkGadgetEvent ) => { switch( event.type ) { case NetworkGadgetEventType.SetGadgetInfo: { let setInfo = event as NGESetGadgetInfo; let universeFromGadget = minimalPoseFromTransform( activeNetworkedGadget.selfFromPeer ); // some stuff we just always update gadgetInfo.remoteLocks = setInfo.locks; gadgetInfo.url = setInfo.url; // if we haven't seen a gadget info for this gadget yet, assign it an ID and tell // remote universes to spawn it if( !gadgetInfo.remoteGadgetId ) { gadgetInfo.remoteGadgetId = NetworkUniverseComponent.nextRemoteGadgetId++; this.networkedGadgetsByRemoteId.set( gadgetInfo.remoteGadgetId, gadgetInfo ); let createEvent: NetworkUniverseEvent = { type: NetworkUniverseEventType.CreateRemoteGadget, remoteGadgetId: gadgetInfo.remoteGadgetId, gadgetInfo: this.networkedGadgetInfoFromInternal( gadgetInfo ), }; this.networkEventCallback( createEvent, true ); } } break; case NetworkGadgetEventType.SetItemInfo: { let setInfo = event as NGESetItemInfo; if( !setInfo.itemId ) { console.log( "Ignoring falsy item ID", setInfo.itemId ); break; } if( !itemInfo ) { itemInfo = { iface: activeNetworkedGadget, itemId: setInfo.itemId, grabState: NetworkedGrabState.None, }; gadgetInfo.items.set( setInfo.itemId, itemInfo ); } this.updateRemoteTransform( activeNetworkedGadget.selfFromPeer, gadgetInfo, itemInfo ); } break; case NetworkGadgetEventType.SendEventToAllRemotes: { let sendEvent = event as NGESendEvent; if( gadgetInfo ) { let netEvent: NetworkUniverseEvent = { type: NetworkUniverseEventType.BroadcastRemoteGadgetEvent, remoteGadgetId: gadgetInfo.remoteGadgetId, itemId: itemInfo?.itemId, event: sendEvent.event, }; this.networkEventCallback( netEvent, sendEvent.reliable ); } } break; case NetworkGadgetEventType.DropComplete: { this.itemDropComplete( gadgetInfo.remoteGadgetId, itemInfo.itemId ); } break; } } ); activeNetworkedGadget.onEnded( () => { if( itemInfo ) { // this is just an item in the gadget } else if( gadgetInfo.remoteGadgetId ) { // this is the gadget itself this.networkedGadgetsByEndpointId.delete( activeNetworkedGadget.peer.endpointId ); if( gadgetInfo.remoteGadgetId ) { this.networkedGadgetsByRemoteId.delete( gadgetInfo.remoteGadgetId ); this.networkEventCallback( { type: NetworkUniverseEventType.DestroyRemoteGadget, remoteGadgetId: gadgetInfo.remoteGadgetId, } as NetworkUniverseEvent, true ); } } else { // this interface never identified itself as either an item or a gadget // if it's the only reference we have to the endpoint Id, clean that up if( gadgetInfo.items.size == 0 ) { this.networkedGadgetsByEndpointId.delete( activeNetworkedGadget.peer.endpointId ); } } } ); activeNetworkedGadget.onTransformUpdated( ( entityFromPeer: AvNodeTransform ) => { if( gadgetInfo ) { this.updateRemoteTransform( entityFromPeer, gadgetInfo, itemInfo ); } } ); } private updateRemoteTransform( entityFromPeer: AvNodeTransform, gadgetInfo: NetworkedGadgetInfoInternal, itemInfo: NetworkedItemInfoInternal ) { if( !gadgetInfo.remoteGadgetId ) return; let universeFromGadget = minimalPoseFromTransform( entityFromPeer ); this.networkEventCallback( { type: NetworkUniverseEventType.UpdateRemoteGadgetTransform, remoteGadgetId: gadgetInfo.remoteGadgetId, itemId: itemInfo?.itemId, universeFromGadget, } as NetworkUniverseEvent, false ); } public get receives() { return [ { iface: NetworkedGadgetComponent.interfaceName, processor: this.onNetworkInterface } ]; } public get wantsTransforms() { return true; } public remoteEvent( event: object ) { let e = event as NetworkUniverseEvent; switch( e.type ) { case NetworkUniverseEventType.SendMasterGadgetEvent: this.masterEvent( e.remoteGadgetId, e.itemId, e.event ); break; case NetworkUniverseEventType.UpdateNetworkItemTransform: this.updateNetworkItemTransform( e.remoteGadgetId, e.itemId, e.universeFromGadget ); break; case NetworkUniverseEventType.StartItemGrab: this.startItemGrab( e.remoteGadgetId, e.itemId, e.universeFromGadget ); break; case NetworkUniverseEventType.EndItemGrab: this.endItemGrab( e.remoteGadgetId, e.itemId, e.universeFromGadget ); break; } } private masterEvent( remoteGadgetId: number, itemId: string, event: object ) { let gadgetInfo = this.networkedGadgetsByRemoteId.get( remoteGadgetId ); if( !gadgetInfo ) { console.log( "Received master event for unknown remote gadget ", remoteGadgetId ); return; } let sendEvent: NGESendEvent = { type: NetworkGadgetEventType.ReceiveEventFromRemote, event, }; if( itemId ) { let itemInfo = gadgetInfo.items.get( itemId ); itemInfo?.iface?.sendEvent( sendEvent ); } else { gadgetInfo?.iface?.sendEvent( sendEvent ); } } private updateNetworkItemTransform( remoteGadgetId: number, itemId: string, universeFromItem: MinimalPose ) { let gadgetInfo = this.networkedGadgetsByRemoteId.get( remoteGadgetId ); if( !gadgetInfo ) return; let itemInfo = gadgetInfo.items.get( itemId ); if( !itemInfo ) return; itemInfo.remoteUniverseFromItem = universeFromItem; this.entityCallback?.(); } private startItemGrab( remoteGadgetId: number, itemId: string, universeFromItem: MinimalPose ) { let gadgetInfo = this.networkedGadgetsByRemoteId.get( remoteGadgetId ); if( !gadgetInfo ) return; let itemInfo = gadgetInfo.items.get( itemId ); if( !itemInfo ) return; itemInfo.remoteUniverseFromItem = universeFromItem; itemInfo.grabState = NetworkedGrabState.Remote; this.sendItemTransformState(gadgetInfo, itemInfo, NetworkItemTransform.Override ) this.entityCallback?.(); } private endItemGrab( remoteGadgetId: number, itemId: string, universeFromItem: MinimalPose ) { let gadgetInfo = this.networkedGadgetsByRemoteId.get( remoteGadgetId ); if( !gadgetInfo ) return; let itemInfo = gadgetInfo.items.get( itemId ); if( !itemInfo ) return; itemInfo.grabState = NetworkedGrabState.RemoteDropping; this.sendItemTransformState(gadgetInfo, itemInfo, NetworkItemTransform.Dropping, universeFromItem ) } private itemDropComplete( remoteGadgetId: number, itemId: string ) { let gadgetInfo = this.networkedGadgetsByRemoteId.get( remoteGadgetId ); if( !gadgetInfo ) return; let itemInfo = gadgetInfo.items.get( itemId ); if( !itemInfo ) return; itemInfo.remoteUniverseFromItem = null; itemInfo.grabState = NetworkedGrabState.None; this.sendItemTransformState(gadgetInfo, itemInfo, NetworkItemTransform.Normal ) this.entityCallback?.(); } private sendItemTransformState( gadgetInfo: NetworkedGadgetInfoInternal, itemInfo: NetworkedItemInfoInternal, newState: NetworkItemTransform, universeFromItem?: MinimalPose ) { let m: NGESetTransformState = { type: NetworkGadgetEventType.SetTransformState, newState, universeFromItem, } itemInfo.iface.sendEvent( m ); } /** The initialization info packet that the room needs to communicate to * any remote universe it is starting up. */ public get initInfo(): object { let gadgets: NetworkedGadgetInfo[] = []; for( let internalInfo of this.networkedGadgetsByRemoteId.values() ) { let gadgetInfo: NetworkedGadgetInfo = this.networkedGadgetInfoFromInternal( internalInfo ); gadgets.push( gadgetInfo ); } return { gadgets } as UniverseInitInfo; } private networkedGadgetInfoFromInternal( internalInfo: NetworkedGadgetInfoInternal ) { let gadgetInfo: NetworkedGadgetInfo = { url: internalInfo.url, remoteLocks: internalInfo.remoteLocks, universeFromGadget: minimalPoseFromTransform( internalInfo.iface.selfFromPeer ), remoteGadgetId: internalInfo.remoteGadgetId, items: [], }; for ( let internalItem of internalInfo.items.values() ) { if ( internalItem.itemId && internalItem.remoteUniverseFromItem ) { gadgetInfo.items.push( { itemId: internalItem.itemId, remoteUniverseFromItem: internalItem.remoteUniverseFromItem, } ); } } return gadgetInfo; } public render(): JSX.Element { let childTransforms: JSX.Element[] = []; for( let gadgetInfo of this.networkedGadgetsByRemoteId.values() ) { for( let itemInfo of gadgetInfo.items.values() ) { if( itemInfo.remoteUniverseFromItem && itemInfo.iface && itemInfo.grabState == NetworkedGrabState.Remote ) { let key=`${ gadgetInfo.remoteGadgetId }/${ itemInfo.itemId }`; childTransforms.push( <AvTransform key={ key } transform={ itemInfo.remoteUniverseFromItem }> <AvEntityChild child={ itemInfo.iface.peer }/> </AvTransform> ); } } } return <>{ childTransforms }</>; } }
the_stack
import CommentContract from '@DataContracts/CommentContract'; import PagingProperties from '@DataContracts/PagingPropertiesContract'; import PartialFindResultContract from '@DataContracts/PartialFindResultContract'; import SongInListContract from '@DataContracts/Song/SongInListContract'; import TagSelectionContract from '@DataContracts/Tag/TagSelectionContract'; import TagUsageForApiContract from '@DataContracts/Tag/TagUsageForApiContract'; import { SongOptionalField, SongOptionalFields, } from '@Models/EntryOptionalFields'; import EntryType from '@Models/EntryType'; import LoginManager from '@Models/LoginManager'; import PVServiceIcons from '@Models/PVServiceIcons'; import SongType from '@Models/Songs/SongType'; import ArtistRepository from '@Repositories/ArtistRepository'; import SongListRepository from '@Repositories/SongListRepository'; import SongRepository from '@Repositories/SongRepository'; import TagRepository from '@Repositories/TagRepository'; import UserRepository from '@Repositories/UserRepository'; import EntryUrlMapper from '@Shared/EntryUrlMapper'; import GlobalValues from '@Shared/GlobalValues'; import UrlMapper from '@Shared/UrlMapper'; import EditableCommentsStore from '@Stores/EditableCommentsStore'; import IStoreWithPaging from '@Stores/IStoreWithPaging'; import PVPlayerStore from '@Stores/PVs/PVPlayerStore'; import PVPlayersFactory from '@Stores/PVs/PVPlayersFactory'; import AdvancedSearchFilter from '@Stores/Search/AdvancedSearchFilter'; import AdvancedSearchFilters from '@Stores/Search/AdvancedSearchFilters'; import ArtistFilters from '@Stores/Search/ArtistFilters'; import { ISongSearchItem } from '@Stores/Search/SongSearchStore'; import TagFilter from '@Stores/Search/TagFilter'; import TagFilters from '@Stores/Search/TagFilters'; import ServerSidePagingStore from '@Stores/ServerSidePagingStore'; import PlayListRepositoryForSongListAdapter, { ISongListStore, } from '@Stores/Song/PlayList/PlayListRepositoryForSongListAdapter'; import PlayListStore from '@Stores/Song/PlayList/PlayListStore'; import SongWithPreviewStore from '@Stores/Song/SongWithPreviewStore'; import TagListStore from '@Stores/Tag/TagListStore'; import TagsEditStore from '@Stores/Tag/TagsEditStore'; import Ajv, { JSONSchemaType } from 'ajv'; import _ from 'lodash'; import { action, computed, makeObservable, observable, reaction, runInAction, } from 'mobx'; const loginManager = new LoginManager(vdb.values); interface SongListRouteParams { advancedFilters?: AdvancedSearchFilter[]; artistId?: number[]; artistParticipationStatus?: string /* TODO: enum */; childTags?: boolean; childVoicebanks?: boolean; page?: number; pageSize?: number; playlistMode?: boolean; query?: string; sort?: string /* TODO: enum */; songType?: string /* TODO: enum */; tagId?: number[]; } // TODO: Use single Ajv instance. See https://ajv.js.org/guide/managing-schemas.html. const ajv = new Ajv({ coerceTypes: true }); // TODO: Make sure that we compile schemas only once and re-use compiled validation functions. See https://ajv.js.org/guide/getting-started.html. const schema: JSONSchemaType<SongListRouteParams> = require('./SongListRouteParams.schema'); const validate = ajv.compile(schema); export default class SongListStore implements ISongListStore, IStoreWithPaging<SongListRouteParams> { public readonly advancedFilters = new AdvancedSearchFilters(); public readonly artistFilters: ArtistFilters; public readonly comments: EditableCommentsStore; @observable public loading = true; // Currently loading for data @observable public page: (SongInListContract & { song: ISongSearchItem; })[] = []; // Current page of items public readonly paging = new ServerSidePagingStore(20); // Paging view model public pauseNotifications = false; @observable public playlistMode = false; public readonly playlistStore: PlayListStore; public readonly pvPlayerStore: PVPlayerStore; public readonly pvServiceIcons: PVServiceIcons; @observable public query = ''; @observable public showAdvancedFilters = false; @observable public showTags = false; @observable public sort = '' /* TODO: enum */; @observable public songType = SongType[SongType.Unspecified] /* TODO: enum */; public readonly tagsEditStore: TagsEditStore; public readonly tagFilters: TagFilters; public readonly tagUsages: TagListStore; public constructor( private readonly values: GlobalValues, urlMapper: UrlMapper, private readonly songListRepo: SongListRepository, private readonly songRepo: SongRepository, tagRepo: TagRepository, private readonly userRepo: UserRepository, artistRepo: ArtistRepository, latestComments: CommentContract[], private readonly listId: number, tagUsages: TagUsageForApiContract[], pvPlayersFactory: PVPlayersFactory, canDeleteAllComments: boolean, ) { makeObservable(this); this.artistFilters = new ArtistFilters(values, artistRepo); this.comments = new EditableCommentsStore( loginManager, songListRepo.getComments({}), listId, canDeleteAllComments, canDeleteAllComments, false, latestComments, true, ); // TODO this.pvPlayerStore = new PVPlayerStore( values, songRepo, userRepo, pvPlayersFactory, ); const playListRepoAdapter = new PlayListRepositoryForSongListAdapter( songListRepo, listId, this, ); this.playlistStore = new PlayListStore( values, urlMapper, playListRepoAdapter, this.pvPlayerStore, ); this.pvServiceIcons = new PVServiceIcons(urlMapper); this.tagsEditStore = new TagsEditStore( { getTagSelections: (): Promise<TagSelectionContract[]> => userRepo.getSongListTagSelections({ songListId: this.listId }), saveTagSelections: (tags): Promise<void> => userRepo .updateSongListTags({ songListId: this.listId, tags: tags }) .then(this.tagUsages.updateTagUsages), }, EntryType.SongList, ); this.tagFilters = new TagFilters(values, tagRepo); this.tagUsages = new TagListStore(tagUsages); reaction(() => this.showTags, this.updateResultsWithTotalCount); } @computed public get childTags(): boolean { return this.tagFilters.childTags; } public set childTags(value: boolean) { this.tagFilters.childTags = value; } @computed public get tags(): TagFilter[] { return this.tagFilters.tags; } public set tags(value: TagFilter[]) { this.tagFilters.tags = value; } @computed public get tagIds(): number[] { return _.map(this.tags, (t) => t.id); } public set tagIds(value: number[]) { // OPTIMIZE this.tagFilters.tags = []; this.tagFilters.addTags(value); } public mapTagUrl = (tagUsage: TagUsageForApiContract): string => { return EntryUrlMapper.details_tag(tagUsage.tag.id, tagUsage.tag.urlSlug); }; public popState = false; public clearResultsByQueryKeys: (keyof SongListRouteParams)[] = [ 'advancedFilters', 'artistId', 'artistParticipationStatus', 'childTags', 'childVoicebanks', 'pageSize', 'songType', 'tagId', 'sort', 'playlistMode', 'query', ]; @computed.struct public get routeParams(): SongListRouteParams { return { advancedFilters: this.advancedFilters.filters.map((filter) => ({ description: filter.description, filterType: filter.filterType, negate: filter.negate, param: filter.param, })), artistId: this.artistFilters.artistIds, artistParticipationStatus: this.artistFilters.artistParticipationStatus, childTags: this.childTags, childVoicebanks: this.artistFilters.childVoicebanks, page: this.paging.page, pageSize: this.paging.pageSize, playlistMode: this.playlistMode, query: this.query, sort: this.sort, songType: this.songType, tagId: this.tagIds, }; } public set routeParams(value: SongListRouteParams) { this.advancedFilters.filters = value.advancedFilters ?? []; this.artistFilters.artistIds = ([] as number[]).concat( value.artistId ?? [], ); this.artistFilters.artistParticipationStatus = value.artistParticipationStatus ?? 'Everything'; this.childTags = value.childTags ?? false; this.artistFilters.childVoicebanks = value.childVoicebanks ?? false; this.paging.page = value.page ?? 1; this.paging.pageSize = value.pageSize ?? 20; this.playlistMode = value.playlistMode ?? false; this.query = value.query ?? ''; this.sort = value.sort ?? ''; this.songType = value.songType ?? SongType[SongType.Unspecified]; this.tagIds = ([] as number[]).concat(value.tagId ?? []); } public validateRouteParams = (data: any): data is SongListRouteParams => validate(data); private loadResults = ( pagingProperties: PagingProperties, ): Promise<PartialFindResultContract<SongInListContract>> => { if (this.playlistMode) { this.playlistStore.updateResultsWithTotalCount(); return Promise.resolve({ items: [], totalCount: 0 }); } else { const fields = [ SongOptionalField.AdditionalNames, SongOptionalField.ThumbUrl, ]; if (this.showTags) fields.push(SongOptionalField.Tags); return this.songListRepo.getSongs({ listId: this.listId, query: this.query, songTypes: this.songType !== SongType[SongType.Unspecified] ? this.songType : undefined, tagIds: this.tagIds, childTags: this.childTags, artistIds: this.artistFilters.artistIds, artistParticipationStatus: this.artistFilters.artistParticipationStatus, childVoicebanks: this.artistFilters.childVoicebanks, advancedFilters: this.advancedFilters.filters, pvServices: undefined, paging: pagingProperties, fields: new SongOptionalFields(fields), sort: this.sort, lang: this.values.languagePreference, }); } }; @action public updateResults = (clearResults: boolean): void => { // Disable duplicate updates if (this.pauseNotifications) return; this.pauseNotifications = true; this.loading = true; const pagingProperties = this.paging.getPagingProperties(clearResults); this.loadResults(pagingProperties).then((result) => { _.each(result.items, (item) => { const song = item.song; const songAny: any = song; if (song.pvServices && song.pvServices !== 'Nothing') { songAny.previewStore = new SongWithPreviewStore( this.songRepo, this.userRepo, song.id, song.pvServices, ); // TODO: songAny.previewViewModel.ratingComplete = ui.showThankYouForRatingMessage; } else { songAny.previewStore = undefined; } }); this.pauseNotifications = false; runInAction(() => { if (pagingProperties.getTotalCount) this.paging.totalItems = result.totalCount; this.page = result.items; this.loading = false; }); }); }; public updateResultsWithTotalCount = (): void => this.updateResults(true); public updateResultsWithoutTotalCount = (): void => this.updateResults(false); }
the_stack
import type Duplex from "./duplex.ts"; import type Writable from "./writable.ts"; import type { WritableState } from "./writable.ts"; import { kDestroy } from "./symbols.ts"; import { ERR_MULTIPLE_CALLBACK, ERR_STREAM_DESTROYED } from "../_errors.ts"; export type writeV = ( // deno-lint-ignore no-explicit-any chunks: Array<{ chunk: any; encoding: string }>, callback: (error?: Error | null) => void, ) => void; export type AfterWriteTick = { cb: (error?: Error) => void; count: number; state: WritableState; stream: Writable; }; export const kOnFinished = Symbol("kOnFinished"); function _destroy( self: Writable, err?: Error | null, cb?: (error?: Error | null) => void, ) { self._destroy(err || null, (err) => { const w = self._writableState; if (err) { // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 err.stack; if (!w.errored) { w.errored = err; } } w.closed = true; if (typeof cb === "function") { cb(err); } if (err) { queueMicrotask(() => { if (!w.errorEmitted) { w.errorEmitted = true; self.emit("error", err); } w.closeEmitted = true; if (w.emitClose) { self.emit("close"); } }); } else { queueMicrotask(() => { w.closeEmitted = true; if (w.emitClose) { self.emit("close"); } }); } }); } export function afterWrite( stream: Writable, state: WritableState, count: number, cb: (error?: Error) => void, ) { const needDrain = !state.ending && !stream.destroyed && state.length === 0 && state.needDrain; if (needDrain) { state.needDrain = false; stream.emit("drain"); } while (count-- > 0) { state.pendingcb--; cb(); } if (state.destroyed) { errorBuffer(state); } finishMaybe(stream, state); } export function afterWriteTick({ cb, count, state, stream, }: AfterWriteTick) { state.afterWriteTickInfo = null; return afterWrite(stream, state, count, cb); } /** If there's something in the buffer waiting, then process it.*/ export function clearBuffer(stream: Duplex | Writable, state: WritableState) { if ( state.corked || state.bufferProcessing || state.destroyed || !state.constructed ) { return; } const { buffered, bufferedIndex, objectMode } = state; const bufferedLength = buffered.length - bufferedIndex; if (!bufferedLength) { return; } let i = bufferedIndex; state.bufferProcessing = true; if (bufferedLength > 1 && stream._writev) { state.pendingcb -= bufferedLength - 1; const callback = state.allNoop ? nop : (err: Error) => { for (let n = i; n < buffered.length; ++n) { buffered[n]!.callback(err); } }; const chunks = state.allNoop && i === 0 ? buffered : buffered.slice(i); doWrite(stream, state, true, state.length, chunks, "", callback); resetBuffer(state); } else { do { const { chunk, encoding, callback } = buffered[i]!; buffered[i++] = null; const len = objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, callback); } while (i < buffered.length && !state.writing); if (i === buffered.length) { resetBuffer(state); } else if (i > 256) { buffered.splice(0, i); state.bufferedIndex = 0; } else { state.bufferedIndex = i; } } state.bufferProcessing = false; } export function destroy(this: Writable, err?: Error | null, cb?: () => void) { const w = this._writableState; if (w.destroyed) { if (typeof cb === "function") { cb(); } return this; } if (err) { // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 err.stack; if (!w.errored) { w.errored = err; } } w.destroyed = true; if (!w.constructed) { this.once(kDestroy, (er) => { _destroy(this, err || er, cb); }); } else { _destroy(this, err, cb); } return this; } function doWrite( stream: Duplex | Writable, state: WritableState, writev: boolean, len: number, // deno-lint-ignore no-explicit-any chunk: any, encoding: string, cb: (error: Error) => void, ) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; if (state.destroyed) { state.onwrite(new ERR_STREAM_DESTROYED("write")); } else if (writev) { (stream._writev as unknown as writeV)(chunk, state.onwrite); } else { stream._write(chunk, encoding, state.onwrite); } state.sync = false; } /** If there's something in the buffer waiting, then invoke callbacks.*/ export function errorBuffer(state: WritableState) { if (state.writing) { return; } for (let n = state.bufferedIndex; n < state.buffered.length; ++n) { const { chunk, callback } = state.buffered[n]!; const len = state.objectMode ? 1 : chunk.length; state.length -= len; callback(new ERR_STREAM_DESTROYED("write")); } for (const callback of state[kOnFinished].splice(0)) { callback(new ERR_STREAM_DESTROYED("end")); } resetBuffer(state); } export function errorOrDestroy(stream: Writable, err: Error, sync = false) { const w = stream._writableState; if (w.destroyed) { return stream; } if (w.autoDestroy) { stream.destroy(err); } else if (err) { // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 err.stack; if (!w.errored) { w.errored = err; } if (sync) { queueMicrotask(() => { if (w.errorEmitted) { return; } w.errorEmitted = true; stream.emit("error", err); }); } else { if (w.errorEmitted) { return; } w.errorEmitted = true; stream.emit("error", err); } } } function finish(stream: Writable, state: WritableState) { state.pendingcb--; if (state.errorEmitted || state.closeEmitted) { return; } state.finished = true; for (const callback of state[kOnFinished].splice(0)) { callback(); } stream.emit("finish"); if (state.autoDestroy) { stream.destroy(); } } export function finishMaybe( stream: Writable, state: WritableState, sync?: boolean, ) { if (needFinish(state)) { prefinish(stream, state); if (state.pendingcb === 0 && needFinish(state)) { state.pendingcb++; if (sync) { queueMicrotask(() => finish(stream, state)); } else { finish(stream, state); } } } } export function needFinish(state: WritableState) { return (state.ending && state.constructed && state.length === 0 && !state.errored && state.buffered.length === 0 && !state.finished && !state.writing); } export function nop() {} export function resetBuffer(state: WritableState) { state.buffered = []; state.bufferedIndex = 0; state.allBuffers = true; state.allNoop = true; } function onwriteError( stream: Writable, state: WritableState, er: Error, cb: (error: Error) => void, ) { --state.pendingcb; cb(er); errorBuffer(state); errorOrDestroy(stream, er); } export function onwrite(stream: Writable, er?: Error | null) { const state = stream._writableState; const sync = state.sync; const cb = state.writecb; if (typeof cb !== "function") { errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK()); return; } state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; if (er) { // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 er.stack; if (!state.errored) { state.errored = er; } if (sync) { queueMicrotask(() => onwriteError(stream, state, er, cb)); } else { onwriteError(stream, state, er, cb); } } else { if (state.buffered.length > state.bufferedIndex) { clearBuffer(stream, state); } if (sync) { if ( state.afterWriteTickInfo !== null && state.afterWriteTickInfo.cb === cb ) { state.afterWriteTickInfo.count++; } else { state.afterWriteTickInfo = { count: 1, cb: (cb as (error?: Error) => void), stream, state, }; queueMicrotask(() => afterWriteTick(state.afterWriteTickInfo as AfterWriteTick) ); } } else { afterWrite(stream, state, 1, cb as (error?: Error) => void); } } } export function prefinish(stream: Writable, state: WritableState) { if (!state.prefinished && !state.finalCalled) { if (typeof stream._final === "function" && !state.destroyed) { state.finalCalled = true; state.sync = true; state.pendingcb++; stream._final((err) => { state.pendingcb--; if (err) { for (const callback of state[kOnFinished].splice(0)) { callback(err); } errorOrDestroy(stream, err, state.sync); } else if (needFinish(state)) { state.prefinished = true; stream.emit("prefinish"); state.pendingcb++; queueMicrotask(() => finish(stream, state)); } }); state.sync = false; } else { state.prefinished = true; stream.emit("prefinish"); } } } export function writeOrBuffer( stream: Duplex | Writable, state: WritableState, // deno-lint-ignore no-explicit-any chunk: any, encoding: string, callback: (error: Error) => void, ) { const len = state.objectMode ? 1 : chunk.length; state.length += len; const ret = state.length < state.highWaterMark; if (!ret) { state.needDrain = true; } if (state.writing || state.corked || state.errored || !state.constructed) { state.buffered.push({ chunk, encoding, callback }); if (state.allBuffers && encoding !== "buffer") { state.allBuffers = false; } if (state.allNoop && callback !== nop) { state.allNoop = false; } } else { state.writelen = len; state.writecb = callback; state.writing = true; state.sync = true; stream._write(chunk, encoding, state.onwrite); state.sync = false; } return ret && !state.errored && !state.destroyed; }
the_stack
'use strict'; import * as vscode from 'vscode'; import { Card } from 'neuron-ipe-types'; import { WebviewController } from "./webviewController"; import { Interpreter } from "./interpreter"; import { UserInteraction } from "./userInteraction"; import { JupyterManager } from './jupyterManager'; import { CardManager } from './cardManager'; import { JSONObject } from '@phosphor/coreutils'; import { ContentHelpers } from './contentHelpers'; export function activate(context: vscode.ExtensionContext) { /** * Webview controller used to generate the output pane. */ let webview: WebviewController = new WebviewController(context); /** * Interpreter instance, allows code execution. */ let interpreter = new Interpreter(); /** * Manages the interaction between VSCode ui elements and the user. */ let userInteraction: UserInteraction = new UserInteraction(context); /** * Boolean which keeps track of the state of the output pane. */ let panelInitialised: boolean = false; /** * Boolean, true when Jupyter Notebook is initialised from * within jupyterManager in the current workspace. */ let localJupyter: boolean = false; /** * Manages the cards in the backend and allows import from and export to * Jupyter Notebook files (.pynb). */ let cardManager: CardManager = new CardManager(); // Link webview events to the corresponding cardManager functions webview.onMoveCardUp(index => cardManager.moveCardUp(index)); webview.onMoveCardDown(index => cardManager.moveCardDown(index)); webview.onDeleteCard(index => cardManager.deleteCard(index)); webview.onDeleteSelectedCards(indexes => cardManager.deleteSelectedCards(indexes)); webview.onChangeTitle(data => cardManager.changeTitle(data.index, data.newTitle)); webview.onCollapseCode(data => cardManager.collapseCode(data.index, data.value)); webview.onCollapseOutput(data => cardManager.collapseOutput(data.index, data.value)); webview.onCollapseCard(data => cardManager.collapseCard(data.index, data.value)); webview.onAddCustomCard(card => cardManager.addCustomCard(card)); webview.onEditCustomCard(data => cardManager.editCustomCard(data.index, data.card)); webview.onJupyterExport(indexes => cardManager.exportToJupyter(indexes)); webview.onSavePdf(pdf => UserInteraction.savePdf(pdf)); webview.onOpenInBrowser(index => { // Export card to a .pynb file let cardId = cardManager.getCardId(index); let fileName = 'exportedCardTmp_' + cardId + '.ipynb'; cardManager.exportToJupyter([index], fileName); if (localJupyter) { // If the jupyter has been initialised in the current workspace, open file directly interpreter.openNotebookInBrowser(fileName); } else { // Otherwise tell the user to select the file created manually vscode.window.showInformationMessage('Please open ' + fileName + ' in the Jupyter window'); interpreter.openNotebookInBrowser(null); } }); webview.undoClicked(() => { // Restore the deleted cards if the undo button is pressed by the user cardManager.lastDeletedCards.map(card => { // Cards are restored both in the backend and frontend cardManager.addCard(card); webview.addCard(card); }) cardManager.lastDeletedCards = []; }); // Link cardManager open in notebook event to the interpreter function which provides the functionality cardManager.onOpenNotebook(fileName => interpreter.openNotebookInBrowser(fileName)); // Whenever the status of Jupyter Notebook changes, the status bar is updated // Jupyter: idle || Jupyter: busy ContentHelpers.onStatusChanged(status => { userInteraction.updateStatus(`Jupyter: ${status}`); }); ContentHelpers.onCardReady((card: Card) => { // Add new cards to both the frontend and the backend cardManager.addCard(card); webview.addCard(card); }); /** * Initialise the output pane and set up the interpreter. * @param param0 interface containing the base url and the token of the current Jupyter Notebook. */ function initialisePanel({ baseUrl, token }) { // Connect to the server defined interpreter.connectToServer(baseUrl, token); // Start needed kernel interpreter.startKernel(UserInteraction.determineKernel()); // Execute code when new card is created userInteraction.onNewCard(sourceCode => { interpreter.executeCode(sourceCode, UserInteraction.determineKernel()); }); webview.show(); context.subscriptions.push(vscode.commands.registerCommand('ipe.exportToJupyter', () => { cardManager.exportToJupyter(); })); panelInitialised = true; // If the kernel is python3, look for module imports if (UserInteraction.determineKernel() === 'python3') { interpreter.autoImportModules(); } } /** * Define callback function of show output pane button. */ userInteraction.onShowPane(() => { if (!panelInitialised) { // Check if user wants to use a remote kernel if (vscode.workspace.getConfiguration('VSNotebooks').get('remoteKernel')) { let config = { baseUrl: vscode.workspace.getConfiguration('VSNotebooks').get('remoteKernelAddress'), token: vscode.workspace.getConfiguration('VSNotebooks').get('remoteKernelToken'), } initialisePanel(config); } // else just try to run it locally else { // custom location for jupyter? localJupyter = initialiseJupyterLocally(initialisePanel, localJupyter); } } else { webview.show(); // Reset the state of the backend card array when the output pane is closed and opened again cardManager.resetState(); } }); /** * Define callback function called when a full setup * of Jupyter Notebook is requested by the user. */ userInteraction.onFullSetup(() => { if (!panelInitialised) { // Check if Jupyter Manager is installed on the local machine let choices = ['Create a new notebook', 'Enter details manually']; let runningNotebooks = JupyterManager.getRunningNotebooks(); runningNotebooks.map(input => { choices.push(input.url); }); /** * Propose different options to the user: * - Create a new Jupyter Notebook automatically. * - Enter the infos of an existing Jupyter Notebook instance manually. * - Choose an existing session of Jupyter Notebook running on the current machine. */ vscode.window.showQuickPick(choices).then(choice => { switch (choice) { // Create a new notebook case choices[0]: localJupyter = initialiseJupyterLocally(initialisePanel, localJupyter); break; // Enter details maually - Remote kernel case choices[1]: UserInteraction.askJupyterInfo().then(initialisePanel); break; default: if (choice) { initialisePanel(runningNotebooks.filter(input => input.url === choice)[0].info); } break; } }); } }); /** * Define callback function called whenever the * user requests a kernel restart. */ userInteraction.onRestartKernels(() => { if (panelInitialised) { interpreter.restartKernels(); } else { vscode.window.showInformationMessage("Output pane has not been initialised!"); } }); /** * Define callback function called when the * user wants to import a notebook. */ userInteraction.onImportNotebook(() => { if (panelInitialised) { let options: vscode.OpenDialogOptions = { canSelectMany: true, filters: { 'Jupyter Notebook': ['ipynb'] } }; vscode.window.showOpenDialog(options).then(fileUris => { fileUris.map(fileUri => { vscode.window.showTextDocument(fileUri).then(textEditor => { let jsonContent: JSONObject = JSON.parse(textEditor.document.getText()); cardManager.importJupyter(jsonContent); }) }) }); } else { vscode.window.showInformationMessage("Output pane has not been initialised!"); } }); /** * Determine the right kernel for code execution when * the file being edited by the user changes. */ vscode.window.onDidChangeActiveTextEditor(input => { if (panelInitialised) { // Open new kernel if new file is in a different language let kernel = UserInteraction.determineKernel(); interpreter.startKernel(kernel); if (kernel === "python3") { interpreter.autoImportModules(); } } }); } /** * Initialise Jupyter locally at a specific path or general path wherever appropriate. * @param initialisePanel call back to initialisePanel * @param localJupyter current val of Local Jupyter */ function initialiseJupyterLocally(initialisePanel: ({ baseUrl, token }: { baseUrl: any; token: any; }) => void, localJupyter: boolean) { if (JupyterManager.getScriptsLocation()) { if (!JupyterManager.isJupyterInPath(JupyterManager.getScriptsLocation())) { // If its fallen in here then Jupyter doesn't exist in the custom env or path. vscode.window.showErrorMessage('VS Notebooks cannot find Jupyter in your custom environment or general path. Install using pip? Note: This defaults to the pip available on your path not environment.', 'Install') .then(data => JupyterManager.installJupyter(data)); } else { let jupyterManager = new JupyterManager(); jupyterManager.getJupyterAddressAndToken() .then(info => { initialisePanel(info); if (jupyterManager.workspaceSet) { localJupyter = true; } }) .catch(error => vscode.window.showErrorMessage('Error could not start: ' + error)); } } // use default path. else { if (!JupyterManager.isJupyterInPath()) { // Ask the user to install Jupyter Notebook if not present vscode.window.showInformationMessage('The IPE extension requires Jupyter to be installed. Install now?', 'Install') .then(data => JupyterManager.installJupyter(data)); } else { // Create a Jupyter Notebook instance automatically let jupyterManager = new JupyterManager(); jupyterManager.getJupyterAddressAndToken() .then(info => { initialisePanel(info); if (jupyterManager.workspaceSet) { localJupyter = true; } }) .catch(error => vscode.window.showErrorMessage('Error could not start: ' + error)); } } return localJupyter; } /** * Called when the extension is closed. * Disposes the running instance of Jupyter Notebook. */ export function deactivate(context: vscode.ExtensionContext) { JupyterManager.disposeNotebook(); }
the_stack
import * as vscode from 'vscode'; import { Utils } from 'vscode-uri'; import { angularCollectionName, angularConfigFileNames } from '../defaults'; import { isSchematicsProActive, Output } from '../utils'; import { formatCliCommandOptions } from '../generation'; import { Collections } from './schematics'; import { AngularConfig, AngularProject, AngularJsonSchematicsOptionsSchema } from './angular'; import { ModuleShortcut, ComponentShortcut, ShortcutsTypes } from './shortcuts'; import { LintConfig } from './angular/lint'; export class WorkspaceFolderConfig implements vscode.WorkspaceFolder { uri: vscode.Uri; name: string; index: number; collections!: Collections; private lintConfig!: LintConfig; private angularConfig!: AngularConfig; private componentShortcut!: ComponentShortcut; private moduleShorcut!: ModuleShortcut; private fileWatchers: vscode.FileSystemWatcher[] = []; private preferencesWatcher: vscode.Disposable | undefined; constructor(workspaceFolder: vscode.WorkspaceFolder) { this.uri = workspaceFolder.uri; this.name = workspaceFolder.name; this.index = workspaceFolder.index; } /** * Initialize `tsconfig.json` configuration. * **Must** be called after each `new WorkspaceFolderConfig()` * (delegated because `async` is not possible on a constructor). */ async init(): Promise<void> { /* Cancel previous file watchers */ this.disposeWatchers(); Output.logInfo(`Loading Angular configuration.`); const angularConfigUri = await this.findAngularConfigUri({ uri: this.uri, name: this.name, index: this.index, }); const angularWatchers: vscode.FileSystemWatcher[] = []; /* Keep only the directory part */ const workspaceFolderUri = Utils.dirname(angularConfigUri); if (workspaceFolderUri.path !== this.uri.path) { Output.logInfo(`Your Angular project is not at the root of your "${this.name}" workspace folder. Real path: ${workspaceFolderUri.path}`); } /* Update the workspace folder URI */ this.uri = workspaceFolderUri; const angularConfig = new AngularConfig(); angularWatchers.push(...(await angularConfig.init({ uri: this.uri, name: this.name, index: this.index, }, angularConfigUri))); this.angularConfig = angularConfig; Output.logInfo(`Loading global lint configuration.`); const lintConfig = new LintConfig(); const lintWatcher = await lintConfig.init(this.uri); this.lintConfig = lintConfig; Output.logInfo(`Loading schematics configuration.`); const collections = new Collections(); const collectionsWatchers = await collections.init({ uri: this.uri, name: this.name, index: this.index, }, this.getDefaultCollections()); this.collections = collections; const componentShortcut = new ComponentShortcut(); await componentShortcut.init({ uri: this.uri, name: this.name, index: this.index, }); this.componentShortcut = componentShortcut; /* Check if the `--route` option exists in Angular `module` schematic (Angular >= 8.1) */ const hasLazyModuleType = this.collections.getCollection(angularCollectionName)?.getSchematic('module')?.hasOption('route') ?? false; Output.logInfo(`Lazy-loaded module type: ${hasLazyModuleType ? `enabled` : `disabled`}`); const moduleShorcut = new ModuleShortcut(); moduleShorcut.init(hasLazyModuleType); this.moduleShorcut = moduleShorcut; /* Watch config files */ this.fileWatchers.push( ...angularWatchers, ...collectionsWatchers, ); if (lintWatcher) { this.fileWatchers.push(lintWatcher); } for (const watcher of this.fileWatchers) { watcher.onDidChange(() => { if (!isSchematicsProActive()) { Output.logInfo(`Reloading "${this.name}" workspace folder configuration.`); this.init().catch(() => { }); } else { watcher.dispose(); } }); } /* Watch Code preferences */ this.preferencesWatcher = vscode.workspace.onDidChangeConfiguration(() => { if (!isSchematicsProActive()) { Output.logInfo(`Reloading "${this.name}" workspace folder configuration.`); this.init().catch(() => { }); } else { this.preferencesWatcher?.dispose(); } }); } /** * Get user default collection, otherwise official Angular CLI default collection. */ getDefaultUserCollection(): string { return this.angularConfig.defaultUserCollection; } /** * Get default collections (user one + official one). */ getDefaultCollections(): string[] { return this.angularConfig?.defaultCollections ?? []; } /** * Get an Angular projects based on its name, or `undefined`. */ getAngularProject(name: string): AngularProject | undefined { return this.angularConfig.projects.get(name); } /** * Get all Angular projects. */ getAngularProjects(): Map<string, AngularProject> { return this.angularConfig.projects; } /** * Get component types */ getComponentTypes(projectName: string): ShortcutsTypes { /* Types can be different from one Angular project to another */ const types = this.getAngularProject(projectName)?.componentShortcut.types ?? this.componentShortcut.types; /* `--type` is only supported in Angular >= 9 */ const hasTypeOption = this.collections.getCollection(angularCollectionName)?.getSchematic('component')?.hasOption('type') ?? false; for (const [, config] of types) { if (config.options.has('type')) { const suffix = config.options.get('type') as string; /* `--type` is only supported in Angular >= 9 and the component suffix must be authorized in lint configuration */ if (!hasTypeOption || !this.hasComponentSuffix(projectName, suffix)) { config.options.delete('type'); config.choice.description = formatCliCommandOptions(config.options); } } } return types; } /** * Get module types */ getModuleTypes(): ShortcutsTypes { return this.moduleShorcut.types; } /** * Get the user default value for an option of a schematics * @param schematicsFullName Must be the full schematics name (eg. "@schematics/angular") */ getSchematicsOptionDefaultValue<T extends keyof AngularJsonSchematicsOptionsSchema>( angularProjectName: string, schematicsFullName: string, optionName: T, ): AngularJsonSchematicsOptionsSchema[T] | undefined { const projectDefault = this.getAngularProject(angularProjectName)?.getSchematicsOptionDefaultValue(schematicsFullName, optionName); /* Suffixes can be defined at, in order of priority: * 1. project level * 2. workspace folder level */ return projectDefault ?? this.angularConfig.getSchematicsOptionDefaultValue(schematicsFullName, optionName); } /** * Tells if a project is the root Angular application */ isRootAngularProject(name: string): boolean { return (this.angularConfig.rootProjectName === name); } /** * Tells if a component suffix is authorized in lint configuration */ hasComponentSuffix(angularProjectName: string, suffix: string): boolean { const angularProject = this.getAngularProject(angularProjectName); /* Suffixes can be defined at, in order of priority: * 1. project level * 2. workspace folder level */ return (angularProject && (angularProject.getComponentSuffixes().length ?? 0) > 0) ? angularProject.hasComponentSuffix(suffix) : this.lintConfig.hasComponentSuffix(suffix); } /** * Cancel all file watchers */ disposeWatchers(): void { for (const watcher of this.fileWatchers) { watcher.dispose(); } this.fileWatchers = []; this.preferencesWatcher?.dispose(); } /** * Try to find the Angular config file's fs path, or `undefined` */ private async findAngularConfigUri(workspaceFolder: vscode.WorkspaceFolder): Promise<vscode.Uri> { /* Search in root folder only first for performance */ /* Required to look only in the current workspace folder (otherwise it searches in all folders) */ const rootPattern = new vscode.RelativePattern(workspaceFolder, `{${angularConfigFileNames.join(',')}}`); /* Third param is the maximum number of results */ let searchMatches = await vscode.workspace.findFiles(rootPattern, '**/node_modules/**', 1); /* Otherwise, search in all subfolders */ if (searchMatches.length === 0) { /* Required to look only in the current workspace folder (otherwise it searches in all folders) */ const everywherePattern = new vscode.RelativePattern(workspaceFolder, `**/{${angularConfigFileNames.join(',')}}`); searchMatches = await vscode.workspace.findFiles(everywherePattern, '**/node_modules/**'); } if (searchMatches.length > 0) { if (searchMatches.length === 1) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion Output.logInfo(`Angular config file for "${this.name}" workspace folder found at: ${searchMatches[0]!.path}`); } else { const errorMessage = `More than one Angular config file found for "${this.name}" workspace folder. If you work with multiple Angular repositories at once, you need to open them as different workspaces in Visual Studio Code.`; const docLabel = `Open VS Code workspaces documentation`; Output.logError(errorMessage); vscode.window.showErrorMessage(errorMessage, 'OK', docLabel).then((action) => { if (action === docLabel) { vscode.env.openExternal(vscode.Uri.parse('https://code.visualstudio.com/docs/editor/multi-root-workspaces')).then(() => { }, () => { }); } }).then(() => { }, () => { }); /* Unfortunately the results' order from VS Code search is inconsistent from one time to another, * so we sort based on paths' nesting length to keep the directory closest to the root folder */ searchMatches.sort((a, b) => (a.path.split('/').length < b.path.split('/').length) ? -1 : 1); } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return searchMatches[0]!; } throw new Error(); } }
the_stack
export const description = ` Unit tests for parameterization helpers. `; import { kUnitCaseParamsBuilder, CaseSubcaseIterable, ParamsBuilderBase, builderIterateCasesWithSubcases, } from '../common/framework/params_builder.js'; import { makeTestGroup } from '../common/framework/test_group.js'; import { mergeParams, publicParamsEquals } from '../common/internal/params_utils.js'; import { assert, objectEquals } from '../common/util/util.js'; import { UnitTest } from './unit_test.js'; class ParamsTest extends UnitTest { expectParams<CaseP, SubcaseP>( act: ParamsBuilderBase<CaseP, SubcaseP>, exp: CaseSubcaseIterable<{}, {}> ): void { const a = Array.from(builderIterateCasesWithSubcases(act)).map(([caseP, subcases]) => [ caseP, subcases ? Array.from(subcases) : undefined, ]); const e = Array.from(exp); this.expect( objectEquals(a, e), ` got ${JSON.stringify(a)} expected ${JSON.stringify(e)}` ); } } export const g = makeTestGroup(ParamsTest); const u = kUnitCaseParamsBuilder; g.test('combine').fn(t => { t.expectParams<{ hello: number }, {}>(u.combine('hello', [1, 2, 3]), [ [{ hello: 1 }, undefined], [{ hello: 2 }, undefined], [{ hello: 3 }, undefined], ]); t.expectParams<{ hello: 1 | 2 | 3 }, {}>(u.combine('hello', [1, 2, 3] as const), [ [{ hello: 1 }, undefined], [{ hello: 2 }, undefined], [{ hello: 3 }, undefined], ]); t.expectParams<{}, { hello: number }>(u.beginSubcases().combine('hello', [1, 2, 3]), [ [{}, [{ hello: 1 }, { hello: 2 }, { hello: 3 }]], ]); t.expectParams<{}, { hello: 1 | 2 | 3 }>(u.beginSubcases().combine('hello', [1, 2, 3] as const), [ [{}, [{ hello: 1 }, { hello: 2 }, { hello: 3 }]], ]); }); g.test('empty').fn(t => { t.expectParams<{}, {}>(u, [ [{}, undefined], // ]); t.expectParams<{}, {}>(u.beginSubcases(), [ [{}, [{}]], // ]); }); g.test('combine,zeroes_and_ones').fn(t => { t.expectParams<{}, {}>(u.combineWithParams([]).combineWithParams([]), []); t.expectParams<{}, {}>(u.combineWithParams([]).combineWithParams([{}]), []); t.expectParams<{}, {}>(u.combineWithParams([{}]).combineWithParams([]), []); t.expectParams<{}, {}>(u.combineWithParams([{}]).combineWithParams([{}]), [ [{}, undefined], // ]); t.expectParams<{}, {}>(u.combine('x', []).combine('y', []), []); t.expectParams<{}, {}>(u.combine('x', []).combine('y', [1]), []); t.expectParams<{}, {}>(u.combine('x', [1]).combine('y', []), []); t.expectParams<{}, {}>(u.combine('x', [1]).combine('y', [1]), [ [{ x: 1, y: 1 }, undefined], // ]); }); g.test('combine,mixed').fn(t => { t.expectParams<{ x: number; y: string; p: number | undefined; q: number | undefined }, {}>( u .combine('x', [1, 2]) .combine('y', ['a', 'b']) .combineWithParams([{ p: 4 }, { q: 5 }]) .combineWithParams([{}]), [ [{ x: 1, y: 'a', p: 4 }, undefined], [{ x: 1, y: 'a', q: 5 }, undefined], [{ x: 1, y: 'b', p: 4 }, undefined], [{ x: 1, y: 'b', q: 5 }, undefined], [{ x: 2, y: 'a', p: 4 }, undefined], [{ x: 2, y: 'a', q: 5 }, undefined], [{ x: 2, y: 'b', p: 4 }, undefined], [{ x: 2, y: 'b', q: 5 }, undefined], ] ); }); g.test('filter').fn(t => { t.expectParams<{ a: boolean; x: number | undefined; y: number | undefined }, {}>( u .combineWithParams([ { a: true, x: 1 }, { a: false, y: 2 }, ]) .filter(p => p.a), [ [{ a: true, x: 1 }, undefined], // ] ); t.expectParams<{ a: boolean; x: number | undefined; y: number | undefined }, {}>( u .combineWithParams([ { a: true, x: 1 }, { a: false, y: 2 }, ]) .beginSubcases() .filter(p => p.a), [ [{ a: true, x: 1 }, [{}]], // // Case with no subcases is filtered out. ] ); t.expectParams<{}, { a: boolean; x: number | undefined; y: number | undefined }>( u .beginSubcases() .combineWithParams([ { a: true, x: 1 }, { a: false, y: 2 }, ]) .filter(p => p.a), [ [{}, [{ a: true, x: 1 }]], // ] ); }); g.test('unless').fn(t => { t.expectParams<{ a: boolean; x: number | undefined; y: number | undefined }, {}>( u .combineWithParams([ { a: true, x: 1 }, { a: false, y: 2 }, ]) .unless(p => p.a), [ [{ a: false, y: 2 }, undefined], // ] ); t.expectParams<{ a: boolean; x: number | undefined; y: number | undefined }, {}>( u .combineWithParams([ { a: true, x: 1 }, { a: false, y: 2 }, ]) .beginSubcases() .unless(p => p.a), [ // Case with no subcases is filtered out. [{ a: false, y: 2 }, [{}]], // ] ); t.expectParams<{}, { a: boolean; x: number | undefined; y: number | undefined }>( u .beginSubcases() .combineWithParams([ { a: true, x: 1 }, { a: false, y: 2 }, ]) .unless(p => p.a), [ [{}, [{ a: false, y: 2 }]], // ] ); }); g.test('expandP').fn(t => { // simple t.expectParams<{}, {}>( u.expandWithParams(function* () {}), [] ); t.expectParams<{}, {}>( u.expandWithParams(function* () { yield {}; }), [[{}, undefined]] ); t.expectParams<{ z: number | undefined; w: number | undefined }, {}>( u.expandWithParams(function* () { yield* kUnitCaseParamsBuilder.combine('z', [3, 4]); yield { w: 5 }; }), [ [{ z: 3 }, undefined], [{ z: 4 }, undefined], [{ w: 5 }, undefined], ] ); t.expectParams<{}, { z: number | undefined; w: number | undefined }>( u.beginSubcases().expandWithParams(function* () { yield* kUnitCaseParamsBuilder.combine('z', [3, 4]); yield { w: 5 }; }), [[{}, [{ z: 3 }, { z: 4 }, { w: 5 }]]] ); // more complex t.expectParams< { a: boolean; x: number | undefined; y: number | undefined; z: number | undefined; w: number | undefined; }, {} >( u .combineWithParams([ { a: true, x: 1 }, { a: false, y: 2 }, ]) .expandWithParams(function* (p) { if (p.a) { yield { z: 3 }; yield { z: 4 }; } else { yield { w: 5 }; } }), [ [{ a: true, x: 1, z: 3 }, undefined], [{ a: true, x: 1, z: 4 }, undefined], [{ a: false, y: 2, w: 5 }, undefined], ] ); t.expectParams< { a: boolean; x: number | undefined; y: number | undefined }, { z: number | undefined; w: number | undefined } >( u .combineWithParams([ { a: true, x: 1 }, { a: false, y: 2 }, ]) .beginSubcases() .expandWithParams(function* (p) { if (p.a) { yield { z: 3 }; yield { z: 4 }; } else { yield { w: 5 }; } }), [ [{ a: true, x: 1 }, [{ z: 3 }, { z: 4 }]], [{ a: false, y: 2 }, [{ w: 5 }]], ] ); }); g.test('expand').fn(t => { // simple t.expectParams<{}, {}>( u.expand('x', function* () {}), [] ); t.expectParams<{ z: number }, {}>( u.expand('z', function* () { yield 3; yield 4; }), [ [{ z: 3 }, undefined], [{ z: 4 }, undefined], ] ); t.expectParams<{}, { z: number }>( u.beginSubcases().expand('z', function* () { yield 3; yield 4; }), [[{}, [{ z: 3 }, { z: 4 }]]] ); // more complex t.expectParams<{ a: boolean; x: number | undefined; y: number | undefined; z: number }, {}>( u .combineWithParams([ { a: true, x: 1 }, { a: false, y: 2 }, ]) .expand('z', function* (p) { if (p.a) { yield 3; } else { yield 5; } }), [ [{ a: true, x: 1, z: 3 }, undefined], [{ a: false, y: 2, z: 5 }, undefined], ] ); t.expectParams<{ a: boolean; x: number | undefined; y: number | undefined }, { z: number }>( u .combineWithParams([ { a: true, x: 1 }, { a: false, y: 2 }, ]) .beginSubcases() .expand('z', function* (p) { if (p.a) { yield 3; } else { yield 5; } }), [ [{ a: true, x: 1 }, [{ z: 3 }]], [{ a: false, y: 2 }, [{ z: 5 }]], ] ); }); g.test('invalid,shadowing').fn(t => { // Existing CaseP is shadowed by a new CaseP. { const p = u .combineWithParams([ { a: true, x: 1 }, { a: false, x: 2 }, ]) .expandWithParams(function* (p) { if (p.a) { yield { x: 3 }; } else { yield { w: 5 }; } }); // Iterating causes e.g. mergeParams({x:1}, {x:3}), which fails. t.shouldThrow('Error', () => { Array.from(p.iterateCasesWithSubcases()); }); } // Existing SubcaseP is shadowed by a new SubcaseP. { const p = u .beginSubcases() .combineWithParams([ { a: true, x: 1 }, { a: false, x: 2 }, ]) .expandWithParams(function* (p) { if (p.a) { yield { x: 3 }; } else { yield { w: 5 }; } }); // Iterating causes e.g. mergeParams({x:1}, {x:3}), which fails. t.shouldThrow('Error', () => { Array.from(p.iterateCasesWithSubcases()); }); } // Existing CaseP is shadowed by a new SubcaseP. { const p = u .combineWithParams([ { a: true, x: 1 }, { a: false, x: 2 }, ]) .beginSubcases() .expandWithParams(function* (p) { if (p.a) { yield { x: 3 }; } else { yield { w: 5 }; } }); const cases = Array.from(p.iterateCasesWithSubcases()); // Iterating cases is fine... for (const [caseP, subcases] of cases) { assert(subcases !== undefined); // Iterating subcases is fine... for (const subcaseP of subcases) { if (caseP.a) { assert(subcases !== undefined); // Only errors once we try to e.g. mergeParams({x:1}, {x:3}). t.shouldThrow('Error', () => { mergeParams(caseP, subcaseP); }); } else { mergeParams(caseP, subcaseP); } } } } }); g.test('undefined').fn(t => { t.expect(!publicParamsEquals({ a: undefined }, {})); t.expect(!publicParamsEquals({}, { a: undefined })); }); g.test('private').fn(t => { t.expect(publicParamsEquals({ _a: 0 }, {})); t.expect(publicParamsEquals({}, { _a: 0 })); }); g.test('value,array').fn(t => { t.expectParams<{ a: number[] }, {}>(u.combineWithParams([{ a: [1, 2] }]), [ [{ a: [1, 2] }, undefined], // ]); t.expectParams<{}, { a: number[] }>(u.beginSubcases().combineWithParams([{ a: [1, 2] }]), [ [{}, [{ a: [1, 2] }]], // ]); }); g.test('value,object').fn(t => { t.expectParams<{ a: { [k: string]: number } }, {}>(u.combineWithParams([{ a: { x: 1 } }]), [ [{ a: { x: 1 } }, undefined], // ]); t.expectParams<{}, { a: { [k: string]: number } }>( u.beginSubcases().combineWithParams([{ a: { x: 1 } }]), [ [{}, [{ a: { x: 1 } }]], // ] ); });
the_stack
import * as React from 'react'; import { Checkbox, ICheckboxStyles, DefaultPalette, Dropdown, IDropdownOption, Slider, Stack, IStackStyles, IStackItemStyles, IStackTokens, IStackProps, TextField, } from '@fluentui/react'; import { useBoolean } from '@fluentui/react-hooks'; import { range } from '@fluentui/example-data'; export interface IExampleOptions { numItems: number; showBoxShadow: boolean; preventOverflow: boolean; wrap: boolean; wrapperWidth: number; disableShrink: boolean; columnGap: number; rowGap: number; paddingLeft: number; paddingRight: number; paddingTop: number; paddingBottom: number; horizontalAlignment: IStackProps['horizontalAlign']; verticalAlignment: IStackProps['verticalAlign']; hideEmptyChildren: boolean; emptyChildren: string[]; } // Alignment options const horizontalAlignmentOptions: IDropdownOption[] = [ { key: 'start', text: 'Left' }, { key: 'center', text: 'Center' }, { key: 'end', text: 'Right' }, { key: 'space-around', text: 'Space around' }, { key: 'space-between', text: 'Space between' }, { key: 'space-evenly', text: 'Space evenly' }, ]; const verticalAlignmentOptions: IDropdownOption[] = [ { key: 'start', text: 'Top' }, { key: 'center', text: 'Center' }, { key: 'end', text: 'Bottom' }, ]; // Tokens definition const sectionStackTokens: IStackTokens = { childrenGap: 10 }; const configureStackTokens: IStackTokens = { childrenGap: 20 }; const shadowItemCheckboxStyles: Partial<ICheckboxStyles> = { root: { marginRight: 10 } }; const wrapItemCheckboxStyles: Partial<ICheckboxStyles> = { root: { marginBottom: 10 } }; const HorizontalStackConfigureExampleContent: React.FunctionComponent<IExampleOptions> = props => { const { numItems, showBoxShadow, preventOverflow, wrap, wrapperWidth, disableShrink, columnGap, rowGap, paddingLeft, paddingRight, paddingTop, paddingBottom, horizontalAlignment, verticalAlignment, hideEmptyChildren, emptyChildren, } = props; // Styles definition const stackStyles: IStackStyles = { root: [ { background: DefaultPalette.themeTertiary, marginLeft: 10, marginRight: 10, minHeight: 100, width: `calc(${wrapperWidth}% - 20px)`, }, preventOverflow && { overflow: 'hidden' as 'hidden', }, ], inner: { overflow: preventOverflow ? 'hidden' : ('visible' as 'hidden' | 'visible'), }, }; const stackItemStyles: IStackItemStyles = { root: { alignItems: 'center', background: DefaultPalette.themePrimary, boxShadow: showBoxShadow ? `0px 0px 10px 5px ${DefaultPalette.themeDarker}` : '', color: DefaultPalette.white, display: 'flex', height: 50, justifyContent: 'center', width: 50, }, }; // Tokens definition const exampleStackTokens: IStackTokens = { childrenGap: rowGap + ' ' + columnGap, padding: `${paddingTop}px ${paddingRight}px ${paddingBottom}px ${paddingLeft}px`, }; return ( <Stack horizontal wrap={wrap} disableShrink={disableShrink} horizontalAlign={horizontalAlignment} verticalAlign={verticalAlignment} styles={stackStyles} tokens={exampleStackTokens} > {range(1, numItems).map((value: number, index: number) => { if (emptyChildren.indexOf(value.toString()) !== -1) { return hideEmptyChildren ? ( <Stack.Item key={index} styles={stackItemStyles} /> ) : ( <span key={index} style={stackItemStyles.root as React.CSSProperties} /> ); } return ( <span key={index} style={stackItemStyles.root as React.CSSProperties}> {value} </span> ); })} </Stack> ); }; export const HorizontalStackConfigureExample: React.FunctionComponent = () => { const [numItems, setNumItems] = React.useState<number>(5); const [showBoxShadow, { toggle: toggleShowBoxShadow }] = useBoolean(false); const [wrap, { toggle: toggleWrap }] = useBoolean(false); const [preventOverflow, { toggle: togglePreventOverflow }] = useBoolean(false); const [disableShrink, { toggle: toggleDisableShrink }] = useBoolean(true); const [wrapperWidth, setWrapperWidth] = React.useState<number>(100); const [columnGap, setColumnGap] = React.useState<number>(0); const [rowGap, setRowGap] = React.useState<number>(0); const [paddingLeft, setPaddingLeft] = React.useState<number>(0); const [paddingRight, setPaddingRight] = React.useState<number>(0); const [paddingTop, setPaddingTop] = React.useState<number>(0); const [paddingBottom, setPaddingBottom] = React.useState<number>(0); const [horizontalAlignment, setHorizontalAlignment] = React.useState<IStackProps['horizontalAlign']>('start'); const [verticalAlignment, setVerticalAlignment] = React.useState<IStackProps['verticalAlign']>('start'); const [hideEmptyChildren, { toggle: toggleHideEmptyChildren }] = useBoolean(false); const [emptyChildren, setEmptyChildren] = React.useState<string[]>([]); return ( <Stack tokens={sectionStackTokens}> <Stack horizontal disableShrink> <Stack.Item grow> <Stack> <Slider label="Number of items:" min={1} max={30} step={1} defaultValue={5} showValue onChange={setNumItems} /> <Stack horizontal disableShrink> <Checkbox label="Shadow around items" onChange={toggleShowBoxShadow} styles={shadowItemCheckboxStyles} /> <Checkbox label="Prevent item overflow" onChange={togglePreventOverflow} /> </Stack> </Stack> </Stack.Item> <Stack.Item grow> <Stack horizontal disableShrink tokens={configureStackTokens}> <Stack> <Checkbox label="Wrap items" onChange={toggleWrap} styles={wrapItemCheckboxStyles} /> <Checkbox label="Shrink items" onChange={toggleDisableShrink} /> </Stack> <Stack.Item grow> <Slider label="Container width:" min={1} max={100} step={1} defaultValue={100} showValue onChange={setWrapperWidth} /> </Stack.Item> </Stack> </Stack.Item> </Stack> <Stack horizontal disableShrink tokens={configureStackTokens}> <Stack.Item grow> <Stack> <Slider label="Horizontal gap between items:" min={0} max={50} step={1} defaultValue={0} showValue onChange={setColumnGap} /> <Slider label="Vertical gap between items:" min={0} max={50} step={1} defaultValue={0} showValue onChange={setRowGap} /> </Stack> </Stack.Item> <Stack.Item grow> <Stack> <Slider label="Left padding:" min={0} max={50} step={1} defaultValue={0} showValue onChange={setPaddingLeft} /> <Slider label="Right padding:" min={0} max={50} step={1} defaultValue={0} showValue onChange={setPaddingRight} /> </Stack> </Stack.Item> <Stack.Item grow> <Stack> <Slider label="Top padding:" min={0} max={50} step={1} defaultValue={0} showValue onChange={setPaddingTop} /> <Slider label="Bottom padding:" min={0} max={50} step={1} defaultValue={0} showValue onChange={setPaddingBottom} /> </Stack> </Stack.Item> </Stack> <Stack horizontal disableShrink verticalAlign="end" tokens={configureStackTokens}> <Stack.Item grow> <Dropdown selectedKey={horizontalAlignment} placeholder="Select Horizontal Alignment" label="Horizontal alignment:" options={horizontalAlignmentOptions} // eslint-disable-next-line react/jsx-no-bind onChange={(ev: React.FormEvent<HTMLDivElement>, option: IDropdownOption): void => setHorizontalAlignment(option.key as IStackProps['horizontalAlign']) } /> </Stack.Item> <Stack.Item grow> <Dropdown selectedKey={verticalAlignment} placeholder="Select Vertical Alignment" label="Vertical alignment:" options={verticalAlignmentOptions} // eslint-disable-next-line react/jsx-no-bind onChange={(ev: React.FormEvent<HTMLDivElement>, option: IDropdownOption): void => setVerticalAlignment(option.key as IStackProps['verticalAlign']) } /> </Stack.Item> <Stack.Item> <Checkbox label="Hide empty children" onChange={toggleHideEmptyChildren} /> </Stack.Item> <Stack.Item grow> <TextField label="Enter a space-separated list of empty children (e.g. 1 2 3):" // eslint-disable-next-line react/jsx-no-bind onChange={(ev: React.FormEvent<HTMLInputElement>, value?: string): void => { if (value === undefined) { return; } setEmptyChildren(value.replace(/,/g, '').split(' ')); }} /> </Stack.Item> </Stack> <HorizontalStackConfigureExampleContent {...{ numItems, showBoxShadow, preventOverflow, wrap, wrapperWidth, disableShrink, columnGap, rowGap, paddingLeft, paddingRight, paddingTop, paddingBottom, horizontalAlignment, verticalAlignment, hideEmptyChildren, emptyChildren, }} /> </Stack> ); };
the_stack
import { testTokenization } from '../test/testRunner'; testTokenization('scala', [ [ { line: 'var a = 1', tokens: [ { startIndex: 0, type: 'keyword.scala' }, { startIndex: 3, type: 'white.scala' }, { startIndex: 4, type: 'variable.scala' }, { startIndex: 5, type: 'white.scala' }, { startIndex: 6, type: 'operator.scala' }, { startIndex: 7, type: 'white.scala' }, { startIndex: 8, type: 'number.scala' } ] } ], // Comments - single line [ { line: '//', tokens: [{ startIndex: 0, type: 'comment.scala' }] } ], [ { line: ' // a comment', tokens: [ { startIndex: 0, type: 'white.scala' }, { startIndex: 4, type: 'comment.scala' } ] } ], // Broken nested tokens due to invalid comment tokenization [ { line: '/* //*/ a', tokens: [{ startIndex: 0, type: 'comment.scala' }] } ], [ { line: '// a comment', tokens: [{ startIndex: 0, type: 'comment.scala' }] } ], [ { line: '//sticky comment', tokens: [{ startIndex: 0, type: 'comment.scala' }] } ], [ { line: '/almost a comment', tokens: [ { startIndex: 0, type: 'operator.scala' }, { startIndex: 1, type: 'identifier.scala' }, { startIndex: 7, type: 'white.scala' }, { startIndex: 8, type: 'identifier.scala' }, { startIndex: 9, type: 'white.scala' }, { startIndex: 10, type: 'identifier.scala' } ] } ], [ { line: '1 / 2; /* comment', tokens: [ { startIndex: 0, type: 'number.scala' }, { startIndex: 1, type: 'white.scala' }, { startIndex: 2, type: 'operator.scala' }, { startIndex: 3, type: 'white.scala' }, { startIndex: 4, type: 'number.scala' }, { startIndex: 5, type: 'delimiter.scala' }, { startIndex: 6, type: 'white.scala' }, { startIndex: 7, type: 'comment.scala' } ] } ], [ { line: 'val x: Int = 1; // my comment // is a nice one', tokens: [ { startIndex: 0, type: 'keyword.scala' }, { startIndex: 3, type: 'white.scala' }, { startIndex: 4, type: 'variable.scala' }, { startIndex: 5, type: 'operator.scala' }, { startIndex: 6, type: 'white.scala' }, { startIndex: 7, type: 'type.scala' }, { startIndex: 10, type: 'white.scala' }, { startIndex: 11, type: 'operator.scala' }, { startIndex: 12, type: 'white.scala' }, { startIndex: 13, type: 'number.scala' }, { startIndex: 14, type: 'delimiter.scala' }, { startIndex: 15, type: 'white.scala' }, { startIndex: 16, type: 'comment.scala' } ] } ], // Comments - range comment, single line [ { line: '/* a simple comment */', tokens: [{ startIndex: 0, type: 'comment.scala' }] } ], [ { line: 'val x: Int = /* a simple comment */ 1;', tokens: [ { startIndex: 0, type: 'keyword.scala' }, { startIndex: 3, type: 'white.scala' }, { startIndex: 4, type: 'variable.scala' }, { startIndex: 5, type: 'operator.scala' }, { startIndex: 6, type: 'white.scala' }, { startIndex: 7, type: 'type.scala' }, { startIndex: 10, type: 'white.scala' }, { startIndex: 11, type: 'operator.scala' }, { startIndex: 12, type: 'white.scala' }, { startIndex: 13, type: 'comment.scala' }, { startIndex: 35, type: 'white.scala' }, { startIndex: 36, type: 'number.scala' }, { startIndex: 37, type: 'delimiter.scala' } ] } ], [ { line: 'val x: Int = /* a simple comment */ 1; */', tokens: [ { startIndex: 0, type: 'keyword.scala' }, { startIndex: 3, type: 'white.scala' }, { startIndex: 4, type: 'variable.scala' }, { startIndex: 5, type: 'operator.scala' }, { startIndex: 6, type: 'white.scala' }, { startIndex: 7, type: 'type.scala' }, { startIndex: 10, type: 'white.scala' }, { startIndex: 11, type: 'operator.scala' }, { startIndex: 12, type: 'white.scala' }, { startIndex: 13, type: 'comment.scala' }, { startIndex: 35, type: 'white.scala' }, { startIndex: 36, type: 'number.scala' }, { startIndex: 37, type: 'delimiter.scala' }, { startIndex: 38, type: 'white.scala' }, { startIndex: 39, type: 'operator.scala' } ] } ], [ { line: 'x = /**/;', tokens: [ { startIndex: 0, type: 'identifier.scala' }, { startIndex: 1, type: 'white.scala' }, { startIndex: 2, type: 'operator.scala' }, { startIndex: 3, type: 'white.scala' }, { startIndex: 4, type: 'comment.scala' }, { startIndex: 8, type: 'delimiter.scala' } ] } ], [ { line: 'x = /*/;', tokens: [ { startIndex: 0, type: 'identifier.scala' }, { startIndex: 1, type: 'white.scala' }, { startIndex: 2, type: 'operator.scala' }, { startIndex: 3, type: 'white.scala' }, { startIndex: 4, type: 'comment.scala' } ] } ], // Comments - range comment, multiple lines [ { line: '/* start of multiline comment', tokens: [{ startIndex: 0, type: 'comment.scala' }] }, { line: 'a comment between without a star', tokens: [{ startIndex: 0, type: 'comment.scala' }] }, { line: 'end of multiline comment*/', tokens: [{ startIndex: 0, type: 'comment.scala' }] } ], [ { line: 'val x: Int = /* start a comment', tokens: [ { startIndex: 0, type: 'keyword.scala' }, { startIndex: 3, type: 'white.scala' }, { startIndex: 4, type: 'variable.scala' }, { startIndex: 5, type: 'operator.scala' }, { startIndex: 6, type: 'white.scala' }, { startIndex: 7, type: 'type.scala' }, { startIndex: 10, type: 'white.scala' }, { startIndex: 11, type: 'operator.scala' }, { startIndex: 12, type: 'white.scala' }, { startIndex: 13, type: 'comment.scala' } ] }, { line: ' a ', tokens: [{ startIndex: 0, type: 'comment.scala' }] }, { line: 'and end it */ 2;', tokens: [ { startIndex: 0, type: 'comment.scala' }, { startIndex: 13, type: 'white.scala' }, { startIndex: 14, type: 'number.scala' }, { startIndex: 15, type: 'delimiter.scala' } ] } ], // Scala Doc, multiple lines [ { line: '/** start of Scala Doc', tokens: [{ startIndex: 0, type: 'comment.scala' }] }, { line: 'a comment between without a star', tokens: [{ startIndex: 0, type: 'comment.scala' }] }, { line: 'end of multiline comment*/', tokens: [{ startIndex: 0, type: 'comment.scala' }] } ], // Keywords [ { line: 'package test; object Program { def main(args: Array[String]): Unit = {} }', tokens: [ { startIndex: 0, type: 'keyword.scala' }, { startIndex: 7, type: 'white.scala' }, { startIndex: 8, type: 'identifier.scala' }, { startIndex: 12, type: 'delimiter.scala' }, { startIndex: 13, type: 'white.scala' }, { startIndex: 14, type: 'keyword.scala' }, { startIndex: 20, type: 'white.scala' }, { startIndex: 21, type: 'type.scala' }, { startIndex: 28, type: 'white.scala' }, { startIndex: 29, type: 'delimiter.curly.scala' }, { startIndex: 30, type: 'white.scala' }, { startIndex: 31, type: 'keyword.scala' }, { startIndex: 34, type: 'white.scala' }, { startIndex: 35, type: 'identifier.scala' }, { startIndex: 39, type: 'delimiter.parenthesis.scala' }, { startIndex: 40, type: 'variable.scala' }, { startIndex: 44, type: 'operator.scala' }, { startIndex: 45, type: 'white.scala' }, { startIndex: 46, type: 'type.scala' }, { startIndex: 51, type: 'operator.square.scala' }, { startIndex: 52, type: 'type.scala' }, { startIndex: 58, type: 'operator.square.scala' }, { startIndex: 59, type: 'delimiter.parenthesis.scala' }, { startIndex: 60, type: 'operator.scala' }, { startIndex: 61, type: 'white.scala' }, { startIndex: 62, type: 'type.scala' }, { startIndex: 66, type: 'white.scala' }, { startIndex: 67, type: 'operator.scala' }, { startIndex: 68, type: 'white.scala' }, { startIndex: 69, type: 'delimiter.curly.scala' }, { startIndex: 71, type: 'white.scala' }, { startIndex: 72, type: 'delimiter.curly.scala' } ] } ], // Numbers [ { line: '0', tokens: [{ startIndex: 0, type: 'number.scala' }] } ], [ { line: '0.10', tokens: [{ startIndex: 0, type: 'number.float.scala' }] } ], [ { line: '0x', tokens: [ { startIndex: 0, type: 'number.scala' }, { startIndex: 1, type: 'identifier.scala' } ] } ], [ { line: '0x123', tokens: [{ startIndex: 0, type: 'number.hex.scala' }] } ], [ { line: '0x5_2', tokens: [{ startIndex: 0, type: 'number.hex.scala' }] } ], [ { line: '10e3', tokens: [{ startIndex: 0, type: 'number.float.scala' }] } ], [ { line: '10f', tokens: [{ startIndex: 0, type: 'number.float.scala' }] } ], [ { line: '23.5', tokens: [{ startIndex: 0, type: 'number.float.scala' }] } ], [ { line: '23.5e3', tokens: [{ startIndex: 0, type: 'number.float.scala' }] } ], [ { line: '23.5e-3', tokens: [{ startIndex: 0, type: 'number.float.scala' }] } ], [ { line: '23.5E3', tokens: [{ startIndex: 0, type: 'number.float.scala' }] } ], [ { line: '23.5E-3', tokens: [{ startIndex: 0, type: 'number.float.scala' }] } ], [ { line: '23.5F', tokens: [{ startIndex: 0, type: 'number.float.scala' }] } ], [ { line: '23.5f', tokens: [{ startIndex: 0, type: 'number.float.scala' }] } ], [ { line: '23.5D', tokens: [{ startIndex: 0, type: 'number.float.scala' }] } ], [ { line: '23.5d', tokens: [{ startIndex: 0, type: 'number.float.scala' }] } ], [ { line: '1.72E3D', tokens: [{ startIndex: 0, type: 'number.float.scala' }] } ], [ { line: '1.72E3d', tokens: [{ startIndex: 0, type: 'number.float.scala' }] } ], [ { line: '1.72E-3d', tokens: [{ startIndex: 0, type: 'number.float.scala' }] } ], [ { line: '1.72e3D', tokens: [{ startIndex: 0, type: 'number.float.scala' }] } ], [ { line: '1.72e3d', tokens: [{ startIndex: 0, type: 'number.float.scala' }] } ], [ { line: '1.72e-3d', tokens: [{ startIndex: 0, type: 'number.float.scala' }] } ], [ { line: '23L', tokens: [{ startIndex: 0, type: 'number.scala' }] } ], [ { line: '23l', tokens: [{ startIndex: 0, type: 'number.scala' }] } ], [ { line: '5_2', tokens: [{ startIndex: 0, type: 'number.scala' }] } ], [ { line: '5_______2', tokens: [{ startIndex: 0, type: 'number.scala' }] } ], [ { line: '3_.1415F', tokens: [ { startIndex: 0, type: 'number.scala' }, { startIndex: 1, type: 'keyword.scala' }, { startIndex: 2, type: 'delimiter.scala' }, { startIndex: 3, type: 'number.float.scala' } ] } ], [ { line: '3._1415F', tokens: [ { startIndex: 0, type: 'number.scala' }, { startIndex: 1, type: 'operator.scala' }, { startIndex: 2, type: 'identifier.scala' } ] } ], [ { line: '999_99_9999_L', tokens: [ { startIndex: 0, type: 'number.scala' }, { startIndex: 11, type: 'identifier.scala' } ] } ], [ { line: '52_', tokens: [ { startIndex: 0, type: 'number.scala' }, { startIndex: 2, type: 'keyword.scala' } ] } ], [ { line: '0_x52', tokens: [ { startIndex: 0, type: 'number.scala' }, { startIndex: 1, type: 'identifier.scala' } ] } ], [ { line: '0x_52', tokens: [ { startIndex: 0, type: 'number.scala' }, { startIndex: 1, type: 'identifier.scala' } ] } ], [ { line: '0x52_', tokens: [ { startIndex: 0, type: 'number.hex.scala' }, { startIndex: 4, type: 'keyword.scala' } // TODO ] } ], [ { line: '23.5L', tokens: [ { startIndex: 0, type: 'number.float.scala' }, { startIndex: 4, type: 'type.scala' } ] } ], [ { line: '0+0', tokens: [ { startIndex: 0, type: 'number.scala' }, { startIndex: 1, type: 'operator.scala' }, { startIndex: 2, type: 'number.scala' } ] } ], [ { line: '100+10', tokens: [ { startIndex: 0, type: 'number.scala' }, { startIndex: 3, type: 'operator.scala' }, { startIndex: 4, type: 'number.scala' } ] } ], [ { line: '0 + 0', tokens: [ { startIndex: 0, type: 'number.scala' }, { startIndex: 1, type: 'white.scala' }, { startIndex: 2, type: 'operator.scala' }, { startIndex: 3, type: 'white.scala' }, { startIndex: 4, type: 'number.scala' } ] } ], // single line Strings [ { line: 'val s: String = "I\'m a Scala String";', tokens: [ { startIndex: 0, type: 'keyword.scala' }, { startIndex: 3, type: 'white.scala' }, { startIndex: 4, type: 'variable.scala' }, { startIndex: 5, type: 'operator.scala' }, { startIndex: 6, type: 'white.scala' }, { startIndex: 7, type: 'type.scala' }, { startIndex: 13, type: 'white.scala' }, { startIndex: 14, type: 'operator.scala' }, { startIndex: 15, type: 'white.scala' }, { startIndex: 16, type: 'string.quote.scala' }, { startIndex: 17, type: 'string.scala' }, { startIndex: 35, type: 'string.quote.scala' }, { startIndex: 36, type: 'delimiter.scala' } ] } ], [ { line: 'val s: String = "concatenated" + " String" ;', tokens: [ { startIndex: 0, type: 'keyword.scala' }, { startIndex: 3, type: 'white.scala' }, { startIndex: 4, type: 'variable.scala' }, { startIndex: 5, type: 'operator.scala' }, { startIndex: 6, type: 'white.scala' }, { startIndex: 7, type: 'type.scala' }, { startIndex: 13, type: 'white.scala' }, { startIndex: 14, type: 'operator.scala' }, { startIndex: 15, type: 'white.scala' }, { startIndex: 16, type: 'string.quote.scala' }, { startIndex: 17, type: 'string.scala' }, { startIndex: 29, type: 'string.quote.scala' }, { startIndex: 30, type: 'white.scala' }, { startIndex: 31, type: 'operator.scala' }, { startIndex: 32, type: 'white.scala' }, { startIndex: 33, type: 'string.quote.scala' }, { startIndex: 34, type: 'string.scala' }, { startIndex: 41, type: 'string.quote.scala' }, { startIndex: 42, type: 'white.scala' }, { startIndex: 43, type: 'delimiter.scala' } ] } ], [ { line: '"quote in a string"', tokens: [ { startIndex: 0, type: 'string.quote.scala' }, { startIndex: 1, type: 'string.scala' }, { startIndex: 18, type: 'string.quote.scala' } ] } ], [ { line: '"escaping \\"quotes\\" is cool"', tokens: [ { startIndex: 0, type: 'string.quote.scala' }, { startIndex: 1, type: 'string.scala' }, { startIndex: 10, type: 'string.escape.scala' }, { startIndex: 12, type: 'string.scala' }, { startIndex: 18, type: 'string.escape.scala' }, { startIndex: 20, type: 'string.scala' }, { startIndex: 28, type: 'string.quote.scala' } ] } ], [ { line: '"\\"', tokens: [ { startIndex: 0, type: 'string.quote.scala' }, { startIndex: 1, type: 'string.escape.scala' } ] } ], // Annotations [ { line: '@', tokens: [{ startIndex: 0, type: 'operator.scala' }] } ], [ { line: '@uncheckedStable', tokens: [{ startIndex: 0, type: 'annotation.scala' }] } ], [ { line: '@silent("deprecated")', tokens: [ { startIndex: 0, type: 'annotation.scala' }, { startIndex: 7, type: 'delimiter.parenthesis.scala' }, { startIndex: 8, type: 'string.quote.scala' }, { startIndex: 9, type: 'string.scala' }, { startIndex: 19, type: 'string.quote.scala' }, { startIndex: 20, type: 'delimiter.parenthesis.scala' } ] } ], [ { line: '@AnnotationWithKeywordAfter private', tokens: [ { startIndex: 0, type: 'annotation.scala' }, { startIndex: 27, type: 'white.scala' }, { startIndex: 28, type: 'keyword.modifier.scala' } ] } ] ]);
the_stack
import * as dockerode from 'dockerode'; import * as sinon from 'sinon'; // Recursively convert properties of an object as optional type DeepPartial<T> = { [P in keyof T]?: T[P] extends Array<infer U> ? Array<DeepPartial<U>> : T[P] extends object ? DeepPartial<T[P]> : T[P]; }; // Partial container inspect info for receiving as testing data export type PartialContainerInspectInfo = DeepPartial< dockerode.ContainerInspectInfo > & { Id: string; }; export type PartialNetworkInspectInfo = DeepPartial< dockerode.NetworkInspectInfo > & { Id: string; }; export type PartialVolumeInspectInfo = DeepPartial< dockerode.VolumeInspectInfo > & { Name: string; }; export type PartialImageInspectInfo = DeepPartial< dockerode.ImageInspectInfo > & { Id: string; }; type Methods<T> = { [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : never; }; function createFake<Prototype extends object>(prototype: Prototype) { return (Object.getOwnPropertyNames(prototype) as Array<keyof Prototype>) .filter((fn) => fn === 'constructor' || typeof prototype[fn] === 'function') .reduce( (res, fn) => ({ ...res, [fn]: () => { throw Error( `Fake method not implemented: ${prototype.constructor.name}.${fn}()`, ); }, }), {} as Methods<Prototype>, ); } export function createNetwork(network: PartialNetworkInspectInfo) { const { Id, ...networkInspect } = network; const inspectInfo = { Id, Name: 'default', Created: '2015-01-06T15:47:31.485331387Z', Scope: 'local', Driver: 'bridge', EnableIPv6: false, Internal: false, Attachable: true, Ingress: false, IPAM: { Driver: 'default', Options: {}, Config: [ { Subnet: '172.18.0.0/16', Gateway: '172.18.0.1', }, ], }, Containers: {}, Options: {}, Labels: {}, // Add defaults ...networkInspect, }; const fakeNetwork = createFake(dockerode.Network.prototype); return { ...fakeNetwork, // by default all methods fail unless overriden id: Id, inspectInfo, inspect: () => Promise.resolve(inspectInfo), remove: (): Promise<boolean> => Promise.reject('Mock network not attached to an engine'), }; } export type MockNetwork = ReturnType<typeof createNetwork>; export function createContainer(container: PartialContainerInspectInfo) { const createContainerInspectInfo = ( partial: PartialContainerInspectInfo, ): dockerode.ContainerInspectInfo => { const { Id, State, Config, NetworkSettings, HostConfig, Mounts, ...ContainerInfo } = partial; return { Id, Created: '2015-01-06T15:47:31.485331387Z', Path: '/usr/bin/sleep', Args: ['infinity'], State: { Status: 'running', ExitCode: 0, Running: true, Paused: false, Restarting: false, OOMKilled: false, ...State, // User passed options }, Image: 'deadbeef', Name: 'main', HostConfig: { AutoRemove: false, Binds: [], LogConfig: { Type: 'journald', Config: {}, }, NetworkMode: 'bridge', PortBindings: {}, RestartPolicy: { Name: 'always', MaximumRetryCount: 0, }, VolumeDriver: '', CapAdd: [], CapDrop: [], Dns: [], DnsOptions: [], DnsSearch: [], ExtraHosts: [], GroupAdd: [], IpcMode: 'shareable', Privileged: false, SecurityOpt: [], ShmSize: 67108864, Memory: 0, MemoryReservation: 0, OomKillDisable: false, Devices: [], Ulimits: [], ...HostConfig, // User passed options }, Config: { Hostname: Id, Labels: {}, Cmd: ['/usr/bin/sleep', 'infinity'], Env: [] as string[], Volumes: {}, Image: 'alpine:latest', ...Config, // User passed options }, NetworkSettings: { Networks: { default: { Aliases: [], Gateway: '172.18.0.1', IPAddress: '172.18.0.2', IPPrefixLen: 16, MacAddress: '00:00:de:ad:be:ef', }, }, ...NetworkSettings, // User passed options }, Mounts: [ ...(Mounts || []).map(({ Name, ...opts }) => ({ Name, Type: 'volume', Source: `/var/lib/docker/volumes/${Name}/_data`, Destination: '/opt/${Name}/path', Driver: 'local', Mode: '', RW: true, Propagation: '', // Replace defaults ...opts, })), ], ...ContainerInfo, } as dockerode.ContainerInspectInfo; }; const createContainerInfo = ( containerInspectInfo: dockerode.ContainerInspectInfo, ): dockerode.ContainerInfo => { const { Id, Name, Created, Image, State, HostConfig, Config, Mounts, NetworkSettings, } = containerInspectInfo; const capitalizeFirst = (s: string) => s.charAt(0).toUpperCase() + s.slice(1); // Calculate summary from existing inspectInfo object return { Id, Names: [Name], ImageID: Image, Image: Config.Image, Created: Date.parse(Created), Command: Config.Cmd.join(' '), State: capitalizeFirst(State.Status), Status: `Exit ${State.ExitCode}`, HostConfig: { NetworkMode: HostConfig.NetworkMode!, }, Ports: [], Labels: Config.Labels, NetworkSettings: { Networks: NetworkSettings.Networks, }, Mounts: Mounts as dockerode.ContainerInfo['Mounts'], }; }; const inspectInfo = createContainerInspectInfo(container); const info = createContainerInfo(inspectInfo); const { Id: id } = inspectInfo; const fakeContainer = createFake(dockerode.Container.prototype); return { ...fakeContainer, // by default all methods fail unless overriden id, inspectInfo, info, inspect: () => Promise.resolve(inspectInfo), remove: (): Promise<boolean> => Promise.reject('Mock container not attached to an engine'), }; } export type MockContainer = ReturnType<typeof createContainer>; interface Reference { repository: string; tag?: string; digest?: string; toString: () => string; } const parseReference = (uri: string): Reference => { // https://github.com/docker/distribution/blob/release/2.7/reference/normalize.go#L62 // https://github.com/docker/distribution/blob/release/2.7/reference/regexp.go#L44 const match = uri.match( /^(?:(localhost|.*?[.:].*?)\/)?(.+?)(?::(.*?))?(?:@(.*?))?$/, ); if (!match) { throw new Error(`Could not parse the image: ${uri}`); } const [, registry, imageName, tagName, digest] = match; let tag = tagName; if (!digest && !tag) { tag = 'latest'; } const digestMatch = digest?.match( /^[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-f-A-F]{32,}$/, ); if (!imageName || (digest && !digestMatch)) { throw new Error( 'Invalid image name, expected [domain.tld/]repo/image[:tag][@digest] format', ); } const repository = [registry, imageName].filter((s) => !!s).join('/'); return { repository, tag, digest, toString: () => repository + (tagName ? `:${tagName}` : '') + (digest ? `@${digest}` : ''), }; }; export function createImage( // Do not allow RepoTags or RepoDigests to be provided. // References must be used instead image: Omit<PartialImageInspectInfo, 'RepoTags' | 'RepoDigests'>, { References = [] as string[] } = {}, ) { const createImageInspectInfo = ( partialImage: PartialImageInspectInfo, ): dockerode.ImageInspectInfo => { const { Id, ContainerConfig, Config, GraphDriver, RootFS, ...Info } = partialImage; return { Id, RepoTags: [], RepoDigests: [ 'registry2.resin.io/v2/8ddbe4a22e881f06def0f31400bfb6de@sha256:09b0db9e71cead5f91107fc9254b1af7088444cc6da55afa2da595940f72a34a', ], Parent: '', Comment: 'Not a real image', Created: '2018-08-15T12:43:06.43392045Z', Container: 'b6cc9227f272b905512a58926b6d515b38de34b604386031aa3c21e94d9dbb4a', ContainerConfig: { Hostname: 'f15babe8256c', Domainname: '', User: '', AttachStdin: false, AttachStdout: false, AttachStderr: false, Tty: false, OpenStdin: false, StdinOnce: false, Env: [ 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', ], Cmd: ['/usr/bin/sleep', 'infinity'], ArgsEscaped: true, Image: 'sha256:828d725f5e6d09ee9abc214f6c11fadf69192ba4871b050984cc9c4cec37b208', Volumes: {}, WorkingDir: '', Entrypoint: null, OnBuild: null, Labels: {}, ...ContainerConfig, } as dockerode.ImageInspectInfo['ContainerConfig'], DockerVersion: '17.05.0-ce', Author: '', Config: { Hostname: '', Domainname: '', User: '', AttachStdin: false, AttachStdout: false, AttachStderr: false, Tty: false, OpenStdin: false, StdinOnce: false, Env: [ 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', ], Cmd: ['/usr/bin/sleep', 'infinity'], ArgsEscaped: true, Image: 'sha256:828d725f5e6d09ee9abc214f6c11fadf69192ba4871b050984cc9c4cec37b208', Volumes: {}, WorkingDir: '/usr/src/app', Entrypoint: ['/usr/bin/entry.sh'], OnBuild: [], Labels: { ...(Config?.Labels ?? {}), }, ...Config, } as dockerode.ImageInspectInfo['Config'], Architecture: 'arm64', Os: 'linux', Size: 38692178, VirtualSize: 38692178, GraphDriver: { Data: { DeviceId: 'deadbeef', DeviceName: 'dummy', DeviceSize: '10m', }, Name: 'aufs', ...GraphDriver, } as dockerode.ImageInspectInfo['GraphDriver'], RootFS: { Type: 'layers', Layers: [ 'sha256:7c30ac6ce381873d5388b7d23b346af7d1e5f6af000a84b97e6203ed9e6dcab2', 'sha256:450b73019ae79e6a99774fcd37c18769f95065c8b271be936dfb3f93afadc4a8', 'sha256:6ab67aaf666bfb7001ab93deffe785f24775f4e0da3d6d421ad6096ba869fd0d', ], ...RootFS, } as dockerode.ImageInspectInfo['RootFS'], ...Info, }; }; const createImageInfo = (imageInspectInfo: dockerode.ImageInspectInfo) => { const { Id, Parent: ParentId, RepoTags, RepoDigests, Config, } = imageInspectInfo; const { Labels } = Config; return { Id, ParentId, RepoTags, RepoDigests, Created: 1474925151, Size: 103579269, VirtualSize: 103579269, SharedSize: 0, Labels, Containers: 0, }; }; const references = References.map((uri) => parseReference(uri)); // Generate image repo tags and digests for inspect const { tags, digests } = references.reduce( (pairs, ref) => { if (ref.tag) { pairs.tags.push([ref.repository, ref.tag].join(':')); } if (ref.digest) { pairs.digests.push([ref.repository, ref.digest].join('@')); } return pairs; }, { tags: [] as string[], digests: [] as string[] }, ); const inspectInfo = createImageInspectInfo({ ...image, // Use references to fill RepoTags and RepoDigests ignoring // those from the partial inspect info RepoTags: [...new Set([...tags])], RepoDigests: [...new Set([...digests])], }); const info = createImageInfo(inspectInfo); const { Id: id } = inspectInfo; const fakeImage = createFake(dockerode.Image.prototype); return { ...fakeImage, // by default all methods fail unless overriden id, info, inspectInfo, references, inspect: () => Promise.resolve(inspectInfo), remove: (_opts: any): Promise<boolean> => Promise.reject('Mock image not attached to an engine'), }; } export type MockImage = ReturnType<typeof createImage>; export function createVolume(volume: PartialVolumeInspectInfo) { const { Name, Labels, ...partialVolumeInfo } = volume; const inspectInfo: dockerode.VolumeInspectInfo = { Name, Driver: 'local', Mountpoint: '/var/lib/docker/volumes/resin-data', Labels: { ...Labels, } as dockerode.VolumeInspectInfo['Labels'], Scope: 'local', Options: {}, ...partialVolumeInfo, }; const fakeVolume = createFake(dockerode.Volume.prototype); return { ...fakeVolume, // by default all methods fail unless overriden name: Name, inspectInfo, inspect: () => Promise.resolve(inspectInfo), remove: (): Promise<boolean> => Promise.reject('Mock volume not attached to an engine'), }; } export type MockVolume = ReturnType<typeof createVolume>; export type MockEngineState = { containers?: MockContainer[]; networks?: MockNetwork[]; volumes?: MockVolume[]; images?: MockImage[]; }; // Good enough function go generate ids for mock engine // source: https://stackoverflow.com/a/2117523 function uuidv4() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { // tslint:disable const r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; return v.toString(16); }); } type Stubs<T> = { [K in keyof T]: T[K] extends (...args: infer TArgs) => infer TReturnValue ? sinon.SinonStub<TArgs, TReturnValue> : never; }; export class MockEngine { networks: Dictionary<MockNetwork> = {}; containers: Dictionary<MockContainer> = {}; images: Dictionary<MockImage> = {}; volumes: Dictionary<MockVolume> = {}; constructor({ networks = [], containers = [], images = [], volumes = [], }: MockEngineState) { // Key networks by id this.networks = networks.reduce((networkMap, network) => { const { id } = network; return { ...networkMap, [id]: { ...network, remove: () => this.removeNetwork(id) }, }; }, {}); this.containers = containers.reduce((containerMap, container) => { const { id } = container; return { ...containerMap, [id]: { ...container, remove: () => this.removeContainer(id), }, }; }, {}); this.images = images.reduce((imageMap, image) => { const { id } = image; return { ...imageMap, [id]: { ...image, remove: (options: any) => this.removeImage(id, options), }, }; }, {}); this.volumes = volumes.reduce((volumeMap, volume) => { const { name } = volume; return { ...volumeMap, [name]: { ...volume, remove: () => this.removeVolume(name), }, }; }, {}); } getNetwork(id: string) { const network = Object.values(this.networks).find( (n) => n.inspectInfo.Id === id || n.inspectInfo.Name === id, ); if (!network) { return { id, inspect: () => Promise.reject({ statusCode: 404, message: `No such network ${id}` }), remove: () => Promise.reject({ statusCode: 404, message: `No such network ${id}` }), } as MockNetwork; } return network; } listNetworks() { return Promise.resolve( Object.values(this.networks).map((network) => network.inspectInfo), ); } removeNetwork(id: string) { const network = Object.values(this.networks).find( (n) => n.inspectInfo.Id === id || n.inspectInfo.Name === id, ); // Throw an error if the network does not exist // this should never happen if (!network) { return Promise.reject({ statusCode: 404, message: `No such network ${id}`, }); } return Promise.resolve(delete this.networks[network.id]); } createNetwork(options: dockerode.NetworkCreateOptions) { const Id = uuidv4(); const network = createNetwork({ Id, ...options }); // Add to the list this.networks[Id] = network; } listContainers() { return Promise.resolve( // List containers returns ContainerInfo objects so we return summaries Object.values(this.containers).map((container) => container.info), ); } createContainer(options: dockerode.ContainerCreateOptions) { const Id = uuidv4(); const { name: Name, HostConfig, NetworkingConfig, ...Config } = options; const container = createContainer({ Id, Name, HostConfig, Config, NetworkSettings: { Networks: NetworkingConfig?.EndpointsConfig ?? {} }, State: { Status: 'created' }, }); // Add to the list this.containers[Id] = { ...container, remove: () => this.removeContainer(Id), }; } getContainer(id: string) { const container = Object.values(this.containers).find( (c) => c.inspectInfo.Id === id || c.inspectInfo.Name === id, ); if (!container) { return { id, inspect: () => Promise.reject({ statusCode: 404, message: `No such container ${id}`, }), } as MockContainer; } return { ...container, remove: () => this.removeContainer(id) }; } removeContainer(id: string) { const container = Object.values(this.containers).find( (c) => c.inspectInfo.Id === id || c.inspectInfo.Name === id, ); // Throw an error if the container does not exist // this should never happen if (!container) { return Promise.reject({ statusCode: 404, message: `No such container ${id}`, }); } return Promise.resolve(delete this.containers[container.id]); } listImages({ filters = { reference: [] as string[] } } = {}) { const filterList = [] as ((img: MockImage) => boolean)[]; const transformers = [] as ((img: MockImage) => MockImage)[]; // Add reference filters if (filters.reference?.length > 0) { const isMatchingReference = ({ repository, tag }: Reference) => filters.reference.includes(repository) || filters.reference.includes( [repository, tag].filter((s) => !!s).join(':'), ); // Create a filter for images matching the reference filterList.push((img) => img.references.some(isMatchingReference)); // Create a transformer removing unused references from the image transformers.push((img) => createImage(img.inspectInfo, { References: img.references .filter(isMatchingReference) .map((ref) => ref.toString()), }), ); } return Promise.resolve( Object.values(this.images) // Remove images that do not match the filter .filter((img) => filterList.every((fn) => fn(img))) // Transform the image if needed .map((image) => transformers.reduce((img, next) => next(img), image)) .map((image) => image.info), ); } getVolume(name: string) { const volume = Object.values(this.volumes).find((v) => v.name === name); if (!volume) { return { name, inspect: () => Promise.reject({ statusCode: 404, message: `No such volume ${name}`, }), remove: () => Promise.reject({ statusCode: 404, message: `No such volume ${name}`, }), }; } return volume; } listVolumes() { return Promise.resolve({ Volumes: Object.values(this.volumes).map((volume) => volume.inspectInfo), Warnings: [] as string[], }); } removeVolume(name: string) { return Promise.resolve(delete this.volumes[name]); } createVolume(options: PartialVolumeInspectInfo) { const { Name } = options; const volume = createVolume(options); // Add to the list this.volumes[Name] = volume; } // NOT a dockerode method // Implements this https://docs.docker.com/engine/reference/commandline/rmi/ // Removes (and un-tags) one or more images from the host node. // If an image has multiple tags, using this command with the tag as // a parameter only removes the tag. If the tag is the only one for the image, // both the image and the tag are removed. // Does not remove images from a registry. // You cannot remove an image of a running container unless you use the // -f option. To see all images on a host use the docker image ls command. // // You can remove an image using its short or long ID, its tag, or its digest. // If an image has one or more tags referencing it, you must remove all of them // before the image is removed. Digest references are removed automatically when // an image is removed by tag. removeImage(name: string, { force } = { force: false }) { const image = this.findImage(name); // Throw an error if the image does not exist if (!image) { return Promise.reject({ statusCode: 404, message: `No such image ${name}`, }); } // Get the id of the iamge const { Id: id } = image.inspectInfo; // If the given identifier is an id if (id === name) { if (!force && image.references.length > 1) { // If the name is an id and there are multiple tags // or digests referencing the image, don't delete unless the force option return Promise.reject({ statusCode: 409, message: `Unable to delete image ${name} with multiple references`, }); } return Promise.resolve(delete this.images[id]); } // If the name is not an id, then it must be a reference const ref = parseReference(name); const References = image.references .filter( (r) => r.repository !== ref.repository || (r.digest !== ref.digest && r.tag !== ref.tag), ) .map((r) => r.toString()); if (References.length > 0) { // If there are still digests or tags, just update the stored image this.images[id] = { ...createImage(image.inspectInfo, { References }), remove: (options: any) => this.removeImage(id, options), }; return Promise.resolve(true); } // Remove the original image return Promise.resolve(delete this.images[id]); } private findImage(name: string) { if (this.images[name]) { return this.images[name]; } // If the identifier is not an id it must be a reference const ref = parseReference(name); return Object.values(this.images).find((img) => img.references.some( (r) => // Find an image that has a reference with matching digest or tag r.repository === ref.repository && (r.digest === ref.digest || r.tag === ref.tag), ), ); } getImage(name: string) { const image = this.findImage(name); // If the image doesn't exist return an empty object if (!image) { return { id: name, inspect: () => Promise.reject({ statusCode: 404, message: `No such image ${name}` }), remove: () => Promise.reject({ statusCode: 404, message: `No such image ${name}` }), }; } return { ...image, remove: (options: any) => this.removeImage(name, options), }; } getEvents() { console.log(`Calling mockerode.getEvents 🐳`); return Promise.resolve({ on: () => void 0, pipe: () => void 0 }); } } export function createMockerode(engine: MockEngine) { const dockerodeStubs: Stubs<dockerode> = (Object.getOwnPropertyNames( dockerode.prototype, ) as (keyof dockerode)[]) .filter((fn) => typeof dockerode.prototype[fn] === 'function') .reduce((stubMap, fn) => { const stub = sinon.stub(dockerode.prototype, fn); if (MockEngine.prototype.hasOwnProperty(fn)) { stub.callsFake((MockEngine.prototype as any)[fn].bind(engine)); } else { // By default all unimplemented methods will throw to avoid the tests // silently failing stub.throws(`Not implemented: Dockerode.${fn}`); } return { ...stubMap, [fn]: stub }; }, {} as Stubs<dockerode>); const { removeImage, removeNetwork, removeVolume, removeContainer } = engine; // Add stubs to additional engine methods we want to // be able to check const mockEngineStubs = { removeImage: sinon .stub(engine, 'removeImage') .callsFake(removeImage.bind(engine)), removeNetwork: sinon .stub(engine, 'removeNetwork') .callsFake(removeNetwork.bind(engine)), removeVolume: sinon .stub(engine, 'removeVolume') .callsFake(removeVolume.bind(engine)), removeContainer: sinon .stub(engine, 'removeContainer') .callsFake(removeContainer.bind(engine)), }; return { ...dockerodeStubs, ...mockEngineStubs, restore: () => { Object.values(dockerodeStubs).forEach((stub) => stub.restore()); Object.values(mockEngineStubs).forEach((spy) => spy.restore()); }, resetHistory: () => { Object.values(dockerodeStubs).forEach((stub) => stub.resetHistory()); Object.values(mockEngineStubs).forEach((spy) => spy.resetHistory()); }, }; } export type Mockerode = ReturnType<typeof createMockerode>; export async function withMockerode( test: (dockerode: Mockerode) => Promise<any>, initialState: MockEngineState = { containers: [], networks: [], volumes: [], images: [], }, ) { const mockEngine = new MockEngine(initialState); const mockerode = createMockerode(mockEngine); try { // run the tests await test(mockerode); } finally { // restore stubs always mockerode.restore(); } }
the_stack
import camelcaseKeys from 'camelcase-keys'; import { ConsoleLogger as Logger, Credentials, getAmplifyUserAgent, } from '@aws-amplify/core'; import { Place as PlaceResult, SearchPlaceIndexForTextCommandInput, LocationClient, SearchPlaceIndexForTextCommand, SearchPlaceIndexForPositionCommand, SearchPlaceIndexForPositionCommandInput, BatchPutGeofenceCommand, BatchPutGeofenceCommandInput, BatchPutGeofenceRequestEntry, BatchPutGeofenceCommandOutput, GetGeofenceCommand, GetGeofenceCommandInput, GetGeofenceCommandOutput, ListGeofencesCommand, ListGeofencesCommandInput, ListGeofencesCommandOutput, BatchDeleteGeofenceCommand, BatchDeleteGeofenceCommandInput, BatchDeleteGeofenceCommandOutput, } from '@aws-sdk/client-location'; import { validateGeofenceId, validateGeofencesInput } from '../util'; import { GeoConfig, SearchByTextOptions, SearchByCoordinatesOptions, GeoProvider, Place, AmazonLocationServiceMapStyle, Coordinates, GeofenceId, GeofenceInput, AmazonLocationServiceGeofenceOptions, AmazonLocationServiceListGeofenceOptions, ListGeofenceResults, AmazonLocationServiceGeofenceStatus, SaveGeofencesResults, AmazonLocationServiceGeofence, GeofencePolygon, AmazonLocationServiceDeleteGeofencesResults, } from '../types'; const logger = new Logger('AmazonLocationServiceProvider'); export class AmazonLocationServiceProvider implements GeoProvider { static CATEGORY = 'Geo'; static PROVIDER_NAME = 'AmazonLocationService'; /** * @private */ private _config; /** * Initialize Geo with AWS configurations * @param {Object} config - Configuration object for Geo */ constructor(config?: GeoConfig) { this._config = config ? config : {}; logger.debug('Geo Options', this._config); } /** * get the category of the plugin * @returns {string} name of the category */ public getCategory(): string { return AmazonLocationServiceProvider.CATEGORY; } /** * get provider name of the plugin * @returns {string} name of the provider */ public getProviderName(): string { return AmazonLocationServiceProvider.PROVIDER_NAME; } /** * Configure Geo part with aws configuration * @param {Object} config - Configuration of the Geo * @return {Object} - Current configuration */ public configure(config?): object { logger.debug('configure Amazon Location Service Provider', config); if (!config) return this._config; this._config = Object.assign({}, this._config, config); return this._config; } /** * Get the map resources that are currently available through the provider * @returns {AmazonLocationServiceMapStyle[]}- Array of available map resources */ public getAvailableMaps(): AmazonLocationServiceMapStyle[] { this._verifyMapResources(); const mapStyles: AmazonLocationServiceMapStyle[] = []; const availableMaps = this._config.maps.items; const region = this._config.region; for (const mapName in availableMaps) { const style = availableMaps[mapName].style; mapStyles.push({ mapName, style, region }); } return mapStyles; } /** * Get the map resource set as default in amplify config * @returns {AmazonLocationServiceMapStyle} - Map resource set as the default in amplify config */ public getDefaultMap(): AmazonLocationServiceMapStyle { this._verifyMapResources(); const mapName = this._config.maps.default; const style = this._config.maps.items[mapName].style; const region = this._config.region; return { mapName, style, region }; } /** * Search by text input with optional parameters * @param {string} text - The text string that is to be searched for * @param {SearchByTextOptions} options? - Optional parameters to the search * @returns {Promise<Place[]>} - Promise resolves to a list of Places that match search parameters */ public async searchByText( text: string, options?: SearchByTextOptions ): Promise<Place[]> { const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { throw new Error('No credentials'); } this._verifySearchIndex(options?.searchIndexName); /** * Setup the searchInput */ const locationServiceInput: SearchPlaceIndexForTextCommandInput = { Text: text, IndexName: this._config.search_indices.default, }; /** * Map search options to Amazon Location Service input object */ if (options) { locationServiceInput.FilterCountries = options.countries; locationServiceInput.MaxResults = options.maxResults; if (options.searchIndexName) { locationServiceInput.IndexName = options.searchIndexName; } if (options['biasPosition'] && options['searchAreaConstraints']) { throw new Error( 'BiasPosition and SearchAreaConstraints are mutually exclusive, please remove one or the other from the options object' ); } if (options['biasPosition']) { locationServiceInput.BiasPosition = options['biasPosition']; } if (options['searchAreaConstraints']) { locationServiceInput.FilterBBox = options['searchAreaConstraints']; } } const client = new LocationClient({ credentials: this._config.credentials, region: this._config.region, customUserAgent: getAmplifyUserAgent(), }); const command = new SearchPlaceIndexForTextCommand(locationServiceInput); let response; try { response = await client.send(command); } catch (error) { logger.debug(error); throw error; } /** * The response from Amazon Location Service is a "Results" array of objects with a single `Place` item, * which are Place objects in PascalCase. * Here we want to flatten that to an array of results and change them to camelCase */ const PascalResults: PlaceResult[] = response.Results.map( result => result.Place ); const results: Place[] = camelcaseKeys(PascalResults, { deep: true, }) as undefined as Place[]; return results; } /** * Reverse geocoding search via a coordinate point on the map * @param coordinates - Coordinates array for the search input * @param options - Options parameters for the search * @returns {Promise<Place>} - Promise that resolves to a place matching search coordinates */ public async searchByCoordinates( coordinates: Coordinates, options?: SearchByCoordinatesOptions ): Promise<Place> { const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { throw new Error('No credentials'); } this._verifySearchIndex(options?.searchIndexName); const locationServiceInput: SearchPlaceIndexForPositionCommandInput = { Position: coordinates, IndexName: this._config.search_indices.default, }; if (options) { if (options.searchIndexName) { locationServiceInput.IndexName = options.searchIndexName; } locationServiceInput.MaxResults = options.maxResults; } const client = new LocationClient({ credentials: this._config.credentials, region: this._config.region, customUserAgent: getAmplifyUserAgent(), }); const command = new SearchPlaceIndexForPositionCommand( locationServiceInput ); let response; try { response = await client.send(command); } catch (error) { logger.debug(error); throw error; } /** * The response from Amazon Location Service is a "Results" array with a single `Place` object * which are Place objects in PascalCase. * Here we want to flatten that to an array of results and change them to camelCase */ const PascalResults = response.Results.map(result => result.Place); const results: Place = camelcaseKeys(PascalResults[0], { deep: true, }) as any as Place; return results; } /** * Create geofences inside of a geofence collection * @param geofences - Array of geofence objects to create * @param options? - Optional parameters for creating geofences * @returns {Promise<AmazonLocationServiceSaveGeofencesResults>} - Promise that resolves to an object with: * successes: list of geofences successfully created * errors: list of geofences that failed to create */ public async saveGeofences( geofences: GeofenceInput[], options?: AmazonLocationServiceGeofenceOptions ): Promise<SaveGeofencesResults> { if (geofences.length < 1) { throw new Error('Geofence input array is empty'); } const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { throw new Error('No credentials'); } // Verify geofence collection exists in aws-config.js try { this._verifyGeofenceCollections(options?.collectionName); } catch (error) { logger.debug(error); throw error; } validateGeofencesInput(geofences); // Convert geofences to PascalCase for Amazon Location Service format const PascalGeofences: BatchPutGeofenceRequestEntry[] = geofences.map( ({ geofenceId, geometry: { polygon } }) => { return { GeofenceId: geofenceId, Geometry: { Polygon: polygon, }, }; } ); const results: SaveGeofencesResults = { successes: [], errors: [], }; const geofenceBatches: BatchPutGeofenceRequestEntry[][] = []; while (PascalGeofences.length > 0) { // Splice off 10 geofences from input clone due to Amazon Location Service API limit const apiLimit = 10; geofenceBatches.push(PascalGeofences.splice(0, apiLimit)); } await Promise.all( geofenceBatches.map(async batch => { // Make API call for the 10 geofences let response: BatchPutGeofenceCommandOutput; try { response = await this._AmazonLocationServiceBatchPutGeofenceCall( batch, options?.collectionName || this._config.geofenceCollections.default ); } catch (error) { // If the API call fails, add the geofences to the errors array and move to next batch batch.forEach(geofence => { results.errors.push({ geofenceId: geofence.GeofenceId, error: { code: 'APIConnectionError', message: error.message, }, }); }); return; } // Push all successes to results response.Successes.forEach(success => { const { GeofenceId, CreateTime, UpdateTime } = success; results.successes.push({ geofenceId: GeofenceId, createTime: CreateTime, updateTime: UpdateTime, }); }); // Push all errors to results response.Errors.forEach(error => { const { Error: { Code, Message }, GeofenceId, } = error; results.errors.push({ error: { code: Code, message: Message, }, geofenceId: GeofenceId, }); }); }) ); return results; } /** * Get geofence from a geofence collection * @param geofenceId:string * @param options?: Optional parameters for getGeofence * @returns {Promise<AmazonLocationServiceGeofence>} - Promise that resolves to a geofence object */ public async getGeofence( geofenceId: GeofenceId, options?: AmazonLocationServiceGeofenceOptions ): Promise<AmazonLocationServiceGeofence> { const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { throw new Error('No credentials'); } // Verify geofence collection exists in aws-config.js try { this._verifyGeofenceCollections(options?.collectionName); } catch (error) { logger.debug(error); throw error; } validateGeofenceId(geofenceId); // Create Amazon Location Service Client const client = new LocationClient({ credentials: this._config.credentials, region: this._config.region, customUserAgent: getAmplifyUserAgent(), }); // Create Amazon Location Service command const commandInput: GetGeofenceCommandInput = { GeofenceId: geofenceId, CollectionName: options?.collectionName || this._config.geofenceCollections.default, }; const command = new GetGeofenceCommand(commandInput); // Make API call let response: GetGeofenceCommandOutput; try { response = await client.send(command); } catch (error) { logger.debug(error); throw error; } // Convert response to camelCase for return const { GeofenceId, CreateTime, UpdateTime, Status, Geometry } = response; const geofence: AmazonLocationServiceGeofence = { createTime: CreateTime, geofenceId: GeofenceId, geometry: { polygon: Geometry.Polygon as GeofencePolygon, }, status: Status as AmazonLocationServiceGeofenceStatus, updateTime: UpdateTime, }; return geofence; } /** * List geofences from a geofence collection * @param options?: ListGeofenceOptions * @returns {Promise<ListGeofencesResults>} - Promise that resolves to an object with: * entries: list of geofences - 100 geofences are listed per page * nextToken: token for next page of geofences */ public async listGeofences( options?: AmazonLocationServiceListGeofenceOptions ): Promise<ListGeofenceResults> { const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { throw new Error('No credentials'); } // Verify geofence collection exists in aws-config.js try { this._verifyGeofenceCollections(options?.collectionName); } catch (error) { logger.debug(error); throw error; } // Create Amazon Location Service Client const client = new LocationClient({ credentials: this._config.credentials, region: this._config.region, customUserAgent: getAmplifyUserAgent(), }); // Create Amazon Location Service input const listGeofencesInput: ListGeofencesCommandInput = { NextToken: options?.nextToken, CollectionName: options?.collectionName || this._config.geofenceCollections.default, }; // Create Amazon Location Service command const command: ListGeofencesCommand = new ListGeofencesCommand( listGeofencesInput ); // Make API call let response: ListGeofencesCommandOutput; try { response = await client.send(command); } catch (error) { logger.debug(error); throw error; } // Convert response to camelCase for return const { NextToken, Entries } = response; const results: ListGeofenceResults = { entries: Entries.map( ({ GeofenceId, CreateTime, UpdateTime, Status, Geometry: { Polygon }, }) => { return { geofenceId: GeofenceId, createTime: CreateTime, updateTime: UpdateTime, status: Status, geometry: { polygon: Polygon as GeofencePolygon, }, }; } ), nextToken: NextToken, }; return results; } /** * Delete geofences from a geofence collection * @param geofenceIds: string|string[] * @param options?: GeofenceOptions * @returns {Promise<DeleteGeofencesResults>} - Promise that resolves to an object with: * successes: list of geofences successfully deleted * errors: list of geofences that failed to delete */ public async deleteGeofences( geofenceIds: string[], options?: AmazonLocationServiceGeofenceOptions ): Promise<AmazonLocationServiceDeleteGeofencesResults> { if (geofenceIds.length < 1) { throw new Error('GeofenceId input array is empty'); } const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { throw new Error('No credentials'); } this._verifyGeofenceCollections(options?.collectionName); // Validate all geofenceIds are valid const badGeofenceIds = geofenceIds.filter(geofenceId => { try { validateGeofenceId(geofenceId); } catch (error) { return true; } }); if (badGeofenceIds.length > 0) { throw new Error(`Invalid geofence ids: ${badGeofenceIds.join(', ')}`); } const results: AmazonLocationServiceDeleteGeofencesResults = { successes: [], errors: [], }; const geofenceIdBatches: string[][] = []; let count = 0; while (count < geofenceIds.length) { geofenceIdBatches.push(geofenceIds.slice(count, (count += 10))); } await Promise.all( geofenceIdBatches.map(async batch => { let response; try { response = await this._AmazonLocationServiceBatchDeleteGeofenceCall( batch, options?.collectionName || this._config.geofenceCollections.default ); } catch (error) { // If the API call fails, add the geofences to the errors array and move to next batch batch.forEach(geofenceId => { const errorObject = { geofenceId, error: { code: error.message, message: error.message, }, }; results.errors.push(errorObject); }); return; } const badGeofenceIds = response.Errors.map( ({ geofenceId }) => geofenceId ); results.successes.push( ...batch.filter(Id => !badGeofenceIds.includes(Id)) ); }) ); return results; } /** * @private */ private async _ensureCredentials(): Promise<boolean> { try { const credentials = await Credentials.get(); if (!credentials) return false; const cred = Credentials.shear(credentials); logger.debug('Set credentials for storage. Credentials are:', cred); this._config.credentials = cred; return true; } catch (error) { logger.debug('Ensure credentials error. Credentials are:', error); return false; } } private _verifyMapResources() { if (!this._config.maps) { const errorString = "No map resources found in amplify config, run 'amplify add geo' to create one and run `amplify push` after"; logger.debug(errorString); throw new Error(errorString); } if (!this._config.maps.default) { const errorString = "No default map resource found in amplify config, run 'amplify add geo' to create one and run `amplify push` after"; logger.debug(errorString); throw new Error(errorString); } } private _verifySearchIndex(optionalSearchIndex?: string) { if ( (!this._config.search_indices || !this._config.search_indices.default) && !optionalSearchIndex ) { const errorString = 'No Search Index found in amplify config, please run `amplify add geo` to create one and run `amplify push` after.'; logger.debug(errorString); throw new Error(errorString); } } private _verifyGeofenceCollections(optionalGeofenceCollectionName?: string) { if ( (!this._config.geofenceCollections || !this._config.geofenceCollections.default) && !optionalGeofenceCollectionName ) { const errorString = 'No Geofence Collections found, please run `amplify add geo` to create one and run `amplify push` after.'; logger.debug(errorString); throw new Error(errorString); } } private async _AmazonLocationServiceBatchPutGeofenceCall( PascalGeofences: BatchPutGeofenceRequestEntry[], collectionName?: string ) { // Create the BatchPutGeofence input const geofenceInput: BatchPutGeofenceCommandInput = { Entries: PascalGeofences, CollectionName: collectionName || this._config.geofenceCollections.default, }; const client = new LocationClient({ credentials: this._config.credentials, region: this._config.region, customUserAgent: getAmplifyUserAgent(), }); const command = new BatchPutGeofenceCommand(geofenceInput); let response: BatchPutGeofenceCommandOutput; try { response = await client.send(command); } catch (error) { throw error; } return response; } private async _AmazonLocationServiceBatchDeleteGeofenceCall( geofenceIds: string[], collectionName?: string ): Promise<BatchDeleteGeofenceCommandOutput> { // Create the BatchDeleteGeofence input const deleteGeofencesInput: BatchDeleteGeofenceCommandInput = { GeofenceIds: geofenceIds, CollectionName: collectionName || this._config.geofenceCollections.default, }; const client = new LocationClient({ credentials: this._config.credentials, region: this._config.region, customUserAgent: getAmplifyUserAgent(), }); const command = new BatchDeleteGeofenceCommand(deleteGeofencesInput); let response: BatchDeleteGeofenceCommandOutput; try { response = await client.send(command); } catch (error) { throw error; } return response; } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/iotDpsResourceMappers"; import * as Parameters from "../models/parameters"; import { IotDpsClientContext } from "../iotDpsClientContext"; /** Class representing a IotDpsResource. */ export class IotDpsResource { private readonly client: IotDpsClientContext; /** * Create a IotDpsResource. * @param {IotDpsClientContext} client Reference to the service client. */ constructor(client: IotDpsClientContext) { this.client = client; } /** * Get the metadata of the provisioning service without SAS keys. * @summary Get the non-security related metadata of the provisioning service. * @param provisioningServiceName Name of the provisioning service to retrieve. * @param resourceGroupName Resource group name. * @param [options] The optional parameters * @returns Promise<Models.IotDpsResourceGetResponse> */ get(provisioningServiceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.IotDpsResourceGetResponse>; /** * @param provisioningServiceName Name of the provisioning service to retrieve. * @param resourceGroupName Resource group name. * @param callback The callback */ get(provisioningServiceName: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.ProvisioningServiceDescription>): void; /** * @param provisioningServiceName Name of the provisioning service to retrieve. * @param resourceGroupName Resource group name. * @param options The optional parameters * @param callback The callback */ get(provisioningServiceName: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProvisioningServiceDescription>): void; get(provisioningServiceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProvisioningServiceDescription>, callback?: msRest.ServiceCallback<Models.ProvisioningServiceDescription>): Promise<Models.IotDpsResourceGetResponse> { return this.client.sendOperationRequest( { provisioningServiceName, resourceGroupName, options }, getOperationSpec, callback) as Promise<Models.IotDpsResourceGetResponse>; } /** * Create or update the metadata of the provisioning service. The usual pattern to modify a * property is to retrieve the provisioning service metadata and security metadata, and then * combine them with the modified values in a new body to update the provisioning service. * @summary Create or update the metadata of the provisioning service. * @param resourceGroupName Resource group identifier. * @param provisioningServiceName Name of provisioning service to create or update. * @param iotDpsDescription Description of the provisioning service to create or update. * @param [options] The optional parameters * @returns Promise<Models.IotDpsResourceCreateOrUpdateResponse> */ createOrUpdate(resourceGroupName: string, provisioningServiceName: string, iotDpsDescription: Models.ProvisioningServiceDescription, options?: msRest.RequestOptionsBase): Promise<Models.IotDpsResourceCreateOrUpdateResponse> { return this.beginCreateOrUpdate(resourceGroupName,provisioningServiceName,iotDpsDescription,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.IotDpsResourceCreateOrUpdateResponse>; } /** * Update an existing provisioning service's tags. to update other fields use the CreateOrUpdate * method * @summary Update an existing provisioning service's tags. * @param resourceGroupName Resource group identifier. * @param provisioningServiceName Name of provisioning service to create or update. * @param provisioningServiceTags Updated tag information to set into the provisioning service * instance. * @param [options] The optional parameters * @returns Promise<Models.IotDpsResourceUpdateResponse> */ update(resourceGroupName: string, provisioningServiceName: string, provisioningServiceTags: Models.TagsResource, options?: msRest.RequestOptionsBase): Promise<Models.IotDpsResourceUpdateResponse> { return this.beginUpdate(resourceGroupName,provisioningServiceName,provisioningServiceTags,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.IotDpsResourceUpdateResponse>; } /** * Deletes the Provisioning Service. * @summary Delete the Provisioning Service * @param provisioningServiceName Name of provisioning service to delete. * @param resourceGroupName Resource group identifier. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(provisioningServiceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginDeleteMethod(provisioningServiceName,resourceGroupName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * List all the provisioning services for a given subscription id. * @summary Get all the provisioning services in a subscription. * @param [options] The optional parameters * @returns Promise<Models.IotDpsResourceListBySubscriptionResponse> */ listBySubscription(options?: msRest.RequestOptionsBase): Promise<Models.IotDpsResourceListBySubscriptionResponse>; /** * @param callback The callback */ listBySubscription(callback: msRest.ServiceCallback<Models.ProvisioningServiceDescriptionListResult>): void; /** * @param options The optional parameters * @param callback The callback */ listBySubscription(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProvisioningServiceDescriptionListResult>): void; listBySubscription(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProvisioningServiceDescriptionListResult>, callback?: msRest.ServiceCallback<Models.ProvisioningServiceDescriptionListResult>): Promise<Models.IotDpsResourceListBySubscriptionResponse> { return this.client.sendOperationRequest( { options }, listBySubscriptionOperationSpec, callback) as Promise<Models.IotDpsResourceListBySubscriptionResponse>; } /** * Get a list of all provisioning services in the given resource group. * @param resourceGroupName Resource group identifier. * @param [options] The optional parameters * @returns Promise<Models.IotDpsResourceListByResourceGroupResponse> */ listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.IotDpsResourceListByResourceGroupResponse>; /** * @param resourceGroupName Resource group identifier. * @param callback The callback */ listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.ProvisioningServiceDescriptionListResult>): void; /** * @param resourceGroupName Resource group identifier. * @param options The optional parameters * @param callback The callback */ listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProvisioningServiceDescriptionListResult>): void; listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProvisioningServiceDescriptionListResult>, callback?: msRest.ServiceCallback<Models.ProvisioningServiceDescriptionListResult>): Promise<Models.IotDpsResourceListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec, callback) as Promise<Models.IotDpsResourceListByResourceGroupResponse>; } /** * Gets the status of a long running operation, such as create, update or delete a provisioning * service. * @param operationId Operation id corresponding to long running operation. Use this to poll for * the status. * @param resourceGroupName Resource group identifier. * @param provisioningServiceName Name of provisioning service that the operation is running on. * @param asyncinfo Async header used to poll on the status of the operation, obtained while * creating the long running operation. * @param [options] The optional parameters * @returns Promise<Models.IotDpsResourceGetOperationResultResponse> */ getOperationResult(operationId: string, resourceGroupName: string, provisioningServiceName: string, asyncinfo: string, options?: msRest.RequestOptionsBase): Promise<Models.IotDpsResourceGetOperationResultResponse>; /** * @param operationId Operation id corresponding to long running operation. Use this to poll for * the status. * @param resourceGroupName Resource group identifier. * @param provisioningServiceName Name of provisioning service that the operation is running on. * @param asyncinfo Async header used to poll on the status of the operation, obtained while * creating the long running operation. * @param callback The callback */ getOperationResult(operationId: string, resourceGroupName: string, provisioningServiceName: string, asyncinfo: string, callback: msRest.ServiceCallback<Models.AsyncOperationResult>): void; /** * @param operationId Operation id corresponding to long running operation. Use this to poll for * the status. * @param resourceGroupName Resource group identifier. * @param provisioningServiceName Name of provisioning service that the operation is running on. * @param asyncinfo Async header used to poll on the status of the operation, obtained while * creating the long running operation. * @param options The optional parameters * @param callback The callback */ getOperationResult(operationId: string, resourceGroupName: string, provisioningServiceName: string, asyncinfo: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AsyncOperationResult>): void; getOperationResult(operationId: string, resourceGroupName: string, provisioningServiceName: string, asyncinfo: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AsyncOperationResult>, callback?: msRest.ServiceCallback<Models.AsyncOperationResult>): Promise<Models.IotDpsResourceGetOperationResultResponse> { return this.client.sendOperationRequest( { operationId, resourceGroupName, provisioningServiceName, asyncinfo, options }, getOperationResultOperationSpec, callback) as Promise<Models.IotDpsResourceGetOperationResultResponse>; } /** * Gets the list of valid SKUs and tiers for a provisioning service. * @summary Get the list of valid SKUs for a provisioning service. * @param provisioningServiceName Name of provisioning service. * @param resourceGroupName Name of resource group. * @param [options] The optional parameters * @returns Promise<Models.IotDpsResourceListValidSkusResponse> */ listValidSkus(provisioningServiceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.IotDpsResourceListValidSkusResponse>; /** * @param provisioningServiceName Name of provisioning service. * @param resourceGroupName Name of resource group. * @param callback The callback */ listValidSkus(provisioningServiceName: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.IotDpsSkuDefinitionListResult>): void; /** * @param provisioningServiceName Name of provisioning service. * @param resourceGroupName Name of resource group. * @param options The optional parameters * @param callback The callback */ listValidSkus(provisioningServiceName: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.IotDpsSkuDefinitionListResult>): void; listValidSkus(provisioningServiceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.IotDpsSkuDefinitionListResult>, callback?: msRest.ServiceCallback<Models.IotDpsSkuDefinitionListResult>): Promise<Models.IotDpsResourceListValidSkusResponse> { return this.client.sendOperationRequest( { provisioningServiceName, resourceGroupName, options }, listValidSkusOperationSpec, callback) as Promise<Models.IotDpsResourceListValidSkusResponse>; } /** * Check if a provisioning service name is available. This will validate if the name is * syntactically valid and if the name is usable * @summary Check if a provisioning service name is available. * @param argumentsParameter Set the name parameter in the OperationInputs structure to the name of * the provisioning service to check. * @param [options] The optional parameters * @returns Promise<Models.IotDpsResourceCheckProvisioningServiceNameAvailabilityResponse> */ checkProvisioningServiceNameAvailability(argumentsParameter: Models.OperationInputs, options?: msRest.RequestOptionsBase): Promise<Models.IotDpsResourceCheckProvisioningServiceNameAvailabilityResponse>; /** * @param argumentsParameter Set the name parameter in the OperationInputs structure to the name of * the provisioning service to check. * @param callback The callback */ checkProvisioningServiceNameAvailability(argumentsParameter: Models.OperationInputs, callback: msRest.ServiceCallback<Models.NameAvailabilityInfo>): void; /** * @param argumentsParameter Set the name parameter in the OperationInputs structure to the name of * the provisioning service to check. * @param options The optional parameters * @param callback The callback */ checkProvisioningServiceNameAvailability(argumentsParameter: Models.OperationInputs, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.NameAvailabilityInfo>): void; checkProvisioningServiceNameAvailability(argumentsParameter: Models.OperationInputs, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.NameAvailabilityInfo>, callback?: msRest.ServiceCallback<Models.NameAvailabilityInfo>): Promise<Models.IotDpsResourceCheckProvisioningServiceNameAvailabilityResponse> { return this.client.sendOperationRequest( { argumentsParameter, options }, checkProvisioningServiceNameAvailabilityOperationSpec, callback) as Promise<Models.IotDpsResourceCheckProvisioningServiceNameAvailabilityResponse>; } /** * List the primary and secondary keys for a provisioning service. * @summary Get the security metadata for a provisioning service. * @param provisioningServiceName The provisioning service name to get the shared access keys for. * @param resourceGroupName resource group name * @param [options] The optional parameters * @returns Promise<Models.IotDpsResourceListKeysResponse> */ listKeys(provisioningServiceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.IotDpsResourceListKeysResponse>; /** * @param provisioningServiceName The provisioning service name to get the shared access keys for. * @param resourceGroupName resource group name * @param callback The callback */ listKeys(provisioningServiceName: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleListResult>): void; /** * @param provisioningServiceName The provisioning service name to get the shared access keys for. * @param resourceGroupName resource group name * @param options The optional parameters * @param callback The callback */ listKeys(provisioningServiceName: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleListResult>): void; listKeys(provisioningServiceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleListResult>, callback?: msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleListResult>): Promise<Models.IotDpsResourceListKeysResponse> { return this.client.sendOperationRequest( { provisioningServiceName, resourceGroupName, options }, listKeysOperationSpec, callback) as Promise<Models.IotDpsResourceListKeysResponse>; } /** * List primary and secondary keys for a specific key name * @summary Get a shared access policy by name from a provisioning service. * @param provisioningServiceName Name of the provisioning service. * @param keyName Logical key name to get key-values for. * @param resourceGroupName The name of the resource group that contains the provisioning service. * @param [options] The optional parameters * @returns Promise<Models.IotDpsResourceListKeysForKeyNameResponse> */ listKeysForKeyName(provisioningServiceName: string, keyName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.IotDpsResourceListKeysForKeyNameResponse>; /** * @param provisioningServiceName Name of the provisioning service. * @param keyName Logical key name to get key-values for. * @param resourceGroupName The name of the resource group that contains the provisioning service. * @param callback The callback */ listKeysForKeyName(provisioningServiceName: string, keyName: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleAccessRightsDescription>): void; /** * @param provisioningServiceName Name of the provisioning service. * @param keyName Logical key name to get key-values for. * @param resourceGroupName The name of the resource group that contains the provisioning service. * @param options The optional parameters * @param callback The callback */ listKeysForKeyName(provisioningServiceName: string, keyName: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleAccessRightsDescription>): void; listKeysForKeyName(provisioningServiceName: string, keyName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleAccessRightsDescription>, callback?: msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleAccessRightsDescription>): Promise<Models.IotDpsResourceListKeysForKeyNameResponse> { return this.client.sendOperationRequest( { provisioningServiceName, keyName, resourceGroupName, options }, listKeysForKeyNameOperationSpec, callback) as Promise<Models.IotDpsResourceListKeysForKeyNameResponse>; } /** * Create or update the metadata of the provisioning service. The usual pattern to modify a * property is to retrieve the provisioning service metadata and security metadata, and then * combine them with the modified values in a new body to update the provisioning service. * @summary Create or update the metadata of the provisioning service. * @param resourceGroupName Resource group identifier. * @param provisioningServiceName Name of provisioning service to create or update. * @param iotDpsDescription Description of the provisioning service to create or update. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdate(resourceGroupName: string, provisioningServiceName: string, iotDpsDescription: Models.ProvisioningServiceDescription, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, provisioningServiceName, iotDpsDescription, options }, beginCreateOrUpdateOperationSpec, options); } /** * Update an existing provisioning service's tags. to update other fields use the CreateOrUpdate * method * @summary Update an existing provisioning service's tags. * @param resourceGroupName Resource group identifier. * @param provisioningServiceName Name of provisioning service to create or update. * @param provisioningServiceTags Updated tag information to set into the provisioning service * instance. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginUpdate(resourceGroupName: string, provisioningServiceName: string, provisioningServiceTags: Models.TagsResource, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, provisioningServiceName, provisioningServiceTags, options }, beginUpdateOperationSpec, options); } /** * Deletes the Provisioning Service. * @summary Delete the Provisioning Service * @param provisioningServiceName Name of provisioning service to delete. * @param resourceGroupName Resource group identifier. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(provisioningServiceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { provisioningServiceName, resourceGroupName, options }, beginDeleteMethodOperationSpec, options); } /** * List all the provisioning services for a given subscription id. * @summary Get all the provisioning services in a subscription. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.IotDpsResourceListBySubscriptionNextResponse> */ listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.IotDpsResourceListBySubscriptionNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listBySubscriptionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ProvisioningServiceDescriptionListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listBySubscriptionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProvisioningServiceDescriptionListResult>): void; listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProvisioningServiceDescriptionListResult>, callback?: msRest.ServiceCallback<Models.ProvisioningServiceDescriptionListResult>): Promise<Models.IotDpsResourceListBySubscriptionNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listBySubscriptionNextOperationSpec, callback) as Promise<Models.IotDpsResourceListBySubscriptionNextResponse>; } /** * Get a list of all provisioning services in the given resource group. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.IotDpsResourceListByResourceGroupNextResponse> */ listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.IotDpsResourceListByResourceGroupNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ProvisioningServiceDescriptionListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProvisioningServiceDescriptionListResult>): void; listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProvisioningServiceDescriptionListResult>, callback?: msRest.ServiceCallback<Models.ProvisioningServiceDescriptionListResult>): Promise<Models.IotDpsResourceListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByResourceGroupNextOperationSpec, callback) as Promise<Models.IotDpsResourceListByResourceGroupNextResponse>; } /** * Gets the list of valid SKUs and tiers for a provisioning service. * @summary Get the list of valid SKUs for a provisioning service. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.IotDpsResourceListValidSkusNextResponse> */ listValidSkusNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.IotDpsResourceListValidSkusNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listValidSkusNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.IotDpsSkuDefinitionListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listValidSkusNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.IotDpsSkuDefinitionListResult>): void; listValidSkusNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.IotDpsSkuDefinitionListResult>, callback?: msRest.ServiceCallback<Models.IotDpsSkuDefinitionListResult>): Promise<Models.IotDpsResourceListValidSkusNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listValidSkusNextOperationSpec, callback) as Promise<Models.IotDpsResourceListValidSkusNextResponse>; } /** * List the primary and secondary keys for a provisioning service. * @summary Get the security metadata for a provisioning service. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.IotDpsResourceListKeysNextResponse> */ listKeysNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.IotDpsResourceListKeysNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listKeysNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listKeysNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleListResult>): void; listKeysNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleListResult>, callback?: msRest.ServiceCallback<Models.SharedAccessSignatureAuthorizationRuleListResult>): Promise<Models.IotDpsResourceListKeysNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listKeysNextOperationSpec, callback) as Promise<Models.IotDpsResourceListKeysNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}", urlParameters: [ Parameters.provisioningServiceName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ProvisioningServiceDescription }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const listBySubscriptionOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/providers/Microsoft.Devices/provisioningServices", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ProvisioningServiceDescriptionListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const listByResourceGroupOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ProvisioningServiceDescriptionListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const getOperationResultOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}/operationresults/{operationId}", urlParameters: [ Parameters.operationId, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.provisioningServiceName ], queryParameters: [ Parameters.asyncinfo, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.AsyncOperationResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const listValidSkusOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}/skus", urlParameters: [ Parameters.provisioningServiceName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.IotDpsSkuDefinitionListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const checkProvisioningServiceNameAvailabilityOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/providers/Microsoft.Devices/checkProvisioningServiceNameAvailability", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "argumentsParameter", mapper: { ...Mappers.OperationInputs, required: true } }, responses: { 200: { bodyMapper: Mappers.NameAvailabilityInfo }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const listKeysOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}/listkeys", urlParameters: [ Parameters.provisioningServiceName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SharedAccessSignatureAuthorizationRuleListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const listKeysForKeyNameOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}/keys/{keyName}/listkeys", urlParameters: [ Parameters.provisioningServiceName, Parameters.keyName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SharedAccessSignatureAuthorizationRuleAccessRightsDescription }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.provisioningServiceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "iotDpsDescription", mapper: { ...Mappers.ProvisioningServiceDescription, required: true } }, responses: { 200: { bodyMapper: Mappers.ProvisioningServiceDescription }, 201: { bodyMapper: Mappers.ProvisioningServiceDescription }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const beginUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.provisioningServiceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "provisioningServiceTags", mapper: { ...Mappers.TagsResource, required: true } }, responses: { 200: { bodyMapper: Mappers.ProvisioningServiceDescription }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}", urlParameters: [ Parameters.provisioningServiceName, Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, 204: {}, 404: {}, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const listBySubscriptionNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ProvisioningServiceDescriptionListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const listByResourceGroupNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ProvisioningServiceDescriptionListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const listValidSkusNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.IotDpsSkuDefinitionListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer }; const listKeysNextOperationSpec: msRest.OperationSpec = { httpMethod: "POST", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SharedAccessSignatureAuthorizationRuleListResult }, default: { bodyMapper: Mappers.ErrorDetails } }, serializer };
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type BuyNowArtworksRailTestsQueryVariables = { id: string; }; export type BuyNowArtworksRailTestsQueryResponse = { readonly sale: { readonly " $fragmentRefs": FragmentRefs<"BuyNowArtworksRail_sale">; } | null; }; export type BuyNowArtworksRailTestsQuery = { readonly response: BuyNowArtworksRailTestsQueryResponse; readonly variables: BuyNowArtworksRailTestsQueryVariables; }; /* query BuyNowArtworksRailTestsQuery( $id: String! ) { sale(id: $id) { ...BuyNowArtworksRail_sale id } } fragment BuyNowArtworksRail_sale on Sale { internalID promotedSale { saleArtworksConnection(first: 4) { edges { node { artwork { id title date saleMessage artistNames href image { imageURL } partner { name id } } id __typename } cursor } pageInfo { endCursor hasNextPage } } id } } */ const node: ConcreteRequest = (function(){ var v0 = [ { "defaultValue": null, "kind": "LocalArgument", "name": "id" } ], v1 = [ { "kind": "Variable", "name": "id", "variableName": "id" } ], v2 = [ { "kind": "Literal", "name": "first", "value": 4 } ], v3 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v4 = { "enumValues": null, "nullable": true, "plural": false, "type": "Sale" }, v5 = { "enumValues": null, "nullable": false, "plural": false, "type": "ID" }, v6 = { "enumValues": null, "nullable": false, "plural": false, "type": "String" }, v7 = { "enumValues": null, "nullable": true, "plural": false, "type": "String" }; return { "fragment": { "argumentDefinitions": (v0/*: any*/), "kind": "Fragment", "metadata": null, "name": "BuyNowArtworksRailTestsQuery", "selections": [ { "alias": null, "args": (v1/*: any*/), "concreteType": "Sale", "kind": "LinkedField", "name": "sale", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "BuyNowArtworksRail_sale" } ], "storageKey": null } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": (v0/*: any*/), "kind": "Operation", "name": "BuyNowArtworksRailTestsQuery", "selections": [ { "alias": null, "args": (v1/*: any*/), "concreteType": "Sale", "kind": "LinkedField", "name": "sale", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Sale", "kind": "LinkedField", "name": "promotedSale", "plural": false, "selections": [ { "alias": null, "args": (v2/*: any*/), "concreteType": "SaleArtworkConnection", "kind": "LinkedField", "name": "saleArtworksConnection", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "SaleArtworkEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "SaleArtwork", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "artwork", "plural": false, "selections": [ (v3/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "title", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "date", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "saleMessage", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "artistNames", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "href", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "image", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "imageURL", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "Partner", "kind": "LinkedField", "name": "partner", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }, (v3/*: any*/) ], "storageKey": null } ], "storageKey": null }, (v3/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "__typename", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "cursor", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "PageInfo", "kind": "LinkedField", "name": "pageInfo", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "endCursor", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "hasNextPage", "storageKey": null } ], "storageKey": null } ], "storageKey": "saleArtworksConnection(first:4)" }, { "alias": null, "args": (v2/*: any*/), "filters": null, "handle": "connection", "key": "Sale_saleArtworksConnection", "kind": "LinkedHandle", "name": "saleArtworksConnection" }, (v3/*: any*/) ], "storageKey": null }, (v3/*: any*/) ], "storageKey": null } ] }, "params": { "id": "10625b74cabb209977b5cafa69ad905c", "metadata": { "relayTestingSelectionTypeInfo": { "sale": (v4/*: any*/), "sale.id": (v5/*: any*/), "sale.internalID": (v5/*: any*/), "sale.promotedSale": (v4/*: any*/), "sale.promotedSale.id": (v5/*: any*/), "sale.promotedSale.saleArtworksConnection": { "enumValues": null, "nullable": true, "plural": false, "type": "SaleArtworkConnection" }, "sale.promotedSale.saleArtworksConnection.edges": { "enumValues": null, "nullable": true, "plural": true, "type": "SaleArtworkEdge" }, "sale.promotedSale.saleArtworksConnection.edges.cursor": (v6/*: any*/), "sale.promotedSale.saleArtworksConnection.edges.node": { "enumValues": null, "nullable": true, "plural": false, "type": "SaleArtwork" }, "sale.promotedSale.saleArtworksConnection.edges.node.__typename": (v6/*: any*/), "sale.promotedSale.saleArtworksConnection.edges.node.artwork": { "enumValues": null, "nullable": true, "plural": false, "type": "Artwork" }, "sale.promotedSale.saleArtworksConnection.edges.node.artwork.artistNames": (v7/*: any*/), "sale.promotedSale.saleArtworksConnection.edges.node.artwork.date": (v7/*: any*/), "sale.promotedSale.saleArtworksConnection.edges.node.artwork.href": (v7/*: any*/), "sale.promotedSale.saleArtworksConnection.edges.node.artwork.id": (v5/*: any*/), "sale.promotedSale.saleArtworksConnection.edges.node.artwork.image": { "enumValues": null, "nullable": true, "plural": false, "type": "Image" }, "sale.promotedSale.saleArtworksConnection.edges.node.artwork.image.imageURL": (v7/*: any*/), "sale.promotedSale.saleArtworksConnection.edges.node.artwork.partner": { "enumValues": null, "nullable": true, "plural": false, "type": "Partner" }, "sale.promotedSale.saleArtworksConnection.edges.node.artwork.partner.id": (v5/*: any*/), "sale.promotedSale.saleArtworksConnection.edges.node.artwork.partner.name": (v7/*: any*/), "sale.promotedSale.saleArtworksConnection.edges.node.artwork.saleMessage": (v7/*: any*/), "sale.promotedSale.saleArtworksConnection.edges.node.artwork.title": (v7/*: any*/), "sale.promotedSale.saleArtworksConnection.edges.node.id": (v5/*: any*/), "sale.promotedSale.saleArtworksConnection.pageInfo": { "enumValues": null, "nullable": false, "plural": false, "type": "PageInfo" }, "sale.promotedSale.saleArtworksConnection.pageInfo.endCursor": (v7/*: any*/), "sale.promotedSale.saleArtworksConnection.pageInfo.hasNextPage": { "enumValues": null, "nullable": false, "plural": false, "type": "Boolean" } } }, "name": "BuyNowArtworksRailTestsQuery", "operationKind": "query", "text": null } }; })(); (node as any).hash = '83497160b713fbb1057034de3ab1812a'; export default node;
the_stack
import { getFiberFlags } from "./utils/getFiberFlags"; import type { CoreApi } from "./core"; import { Fiber, ReactInterationApi, NativeType, SerializedElement, } from "../types"; const MOUNTING = 1; const MOUNTED = 2; const UNMOUNTED = 3; export function createReactInteractionApi({ ReactTypeOfSideEffect, ReactTypeOfWork, getFiberIdThrows, getFiberById, getElementTypeForFiber, getDisplayNameForFiber, getRootPseudoKey, shouldFilterFiber, findFiberByHostInstance, }: CoreApi): ReactInterationApi { const { Incomplete, NoFlags, Placement } = ReactTypeOfSideEffect; const { HostRoot, HostComponent, HostText, SuspenseComponent } = ReactTypeOfWork; function findAllCurrentHostFibers(id: number) { const fibers: Fiber[] = []; const fiber = findCurrentFiberUsingSlowPathById(id); if (!fiber) { return fibers; } // Next we'll drill down this component to find all HostComponent/Text. let node = fiber; while (true) { if (node.tag === HostComponent || node.tag === HostText) { fibers.push(node); } else if (node.child) { node.child.return = node; node = node.child; continue; } if (node === fiber) { return fibers; } while (!node.sibling) { if (!node.return || node.return === fiber) { return fibers; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } } function findNativeNodesForFiberID(id: number) { try { let fiber = findCurrentFiberUsingSlowPathById(id); if (fiber === null) { return null; } // Special case for a timed-out Suspense. const isTimedOutSuspense = fiber.tag === SuspenseComponent && fiber.memoizedState !== null; if (isTimedOutSuspense) { // A timed-out Suspense's findDOMNode is useless. // Try our best to find the fallback directly. const maybeFallbackFiber = fiber.child && fiber.child.sibling; if (maybeFallbackFiber != null) { fiber = maybeFallbackFiber; } } const hostFibers = findAllCurrentHostFibers(id); return hostFibers.map(hostFiber => hostFiber.stateNode).filter(Boolean); } catch (err) { // The fiber might have unmounted by now. return null; } } function getDisplayNameForFiberID(id: number) { const fiber = getFiberById(id); return fiber !== null ? getDisplayNameForFiber(fiber) : null; } function getFiberIDForNative( hostInstance: NativeType, findNearestUnfilteredAncestor = false ) { let fiber = findFiberByHostInstance(hostInstance); if (fiber === null) { return null; } if (findNearestUnfilteredAncestor) { while (fiber !== null && shouldFilterFiber(fiber)) { fiber = fiber.return; } } return fiber && getFiberIdThrows(fiber); } // This function is copied from React and should be kept in sync: // https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactFiberTreeReflection.js function isFiberMountedImpl(fiber: Fiber) { let node = fiber; let prevNode = null; if (!fiber.alternate) { // If there is no alternate, this might be a new tree that isn't inserted // yet. If it is, then it will have a pending insertion effect on it. if ((getFiberFlags(node) & Placement) !== NoFlags) { return MOUNTING; } // This indicates an error during render. if ((getFiberFlags(node) & Incomplete) !== NoFlags) { return UNMOUNTED; } while (node.return) { prevNode = node; node = node.return; if ((getFiberFlags(node) & Placement) !== NoFlags) { return MOUNTING; } // This indicates an error during render. if ((getFiberFlags(node) & Incomplete) !== NoFlags) { return UNMOUNTED; } // If this node is inside of a timed out suspense subtree, we should also ignore errors/warnings. const isTimedOutSuspense = node.tag === SuspenseComponent && node.memoizedState !== null; if (isTimedOutSuspense) { // Note that this does not include errors/warnings in the Fallback tree though! const primaryChildFragment = node.child; const fallbackChildFragment = primaryChildFragment ? primaryChildFragment.sibling : null; if (prevNode !== fallbackChildFragment) { return UNMOUNTED; } } } } else { while (node.return) { node = node.return; } } if (node.tag === HostRoot) { // TODO: Check if this was a nested HostRoot when used with // renderContainerIntoSubtree. return MOUNTED; } // If we didn't hit the root, that means that we're in an disconnected tree // that has been unmounted. return UNMOUNTED; } // This function is copied from React and should be kept in sync: // https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactFiberTreeReflection.js // It would be nice if we updated React to inject this function directly (vs just indirectly via findDOMNode). // BEGIN copied code function findCurrentFiberUsingSlowPathById(id: number) { const fiber = getFiberById(id); if (fiber === null) { console.warn(`Could not find Fiber with id "${id}"`); return null; } const { alternate } = fiber; if (!alternate) { // If there is no alternate, then we only need to check if it is mounted. const state = isFiberMountedImpl(fiber); if (state === UNMOUNTED) { throw Error("Unable to find node on an unmounted component."); } if (state === MOUNTING) { return null; } return fiber; } // If we have two possible branches, we'll walk backwards up to the root // to see what path the root points to. On the way we may hit one of the // special cases and we'll deal with them. let a = fiber; let b = alternate; while (true) { const parentA = a.return; if (parentA === null) { // We're at the root. break; } const parentB = parentA.alternate; if (parentB === null) { // There is no alternate. This is an unusual case. Currently, it only // happens when a Suspense component is hidden. An extra fragment fiber // is inserted in between the Suspense fiber and its children. Skip // over this extra fragment fiber and proceed to the next parent. const nextParent = parentA.return; if (nextParent !== null) { a = b = nextParent; continue; } // If there's no parent, we're at the root. break; } // If both copies of the parent fiber point to the same child, we can // assume that the child is current. This happens when we bailout on low // priority: the bailed out fiber's child reuses the current child. if (parentA.child === parentB.child) { let child = parentA.child; while (child) { if (child === a) { // We've determined that A is the current branch. if (isFiberMountedImpl(parentA) !== MOUNTED) { throw Error("Unable to find node on an unmounted component."); } return fiber; } if (child === b) { // We've determined that B is the current branch. if (isFiberMountedImpl(parentA) !== MOUNTED) { throw Error("Unable to find node on an unmounted component."); } return alternate; } child = child.sibling; } // We should never have an alternate for any mounting node. So the only // way this could possibly happen is if this was unmounted, if at all. throw Error("Unable to find node on an unmounted component."); } if (a.return !== b.return) { // The return pointer of A and the return pointer of B point to different // fibers. We assume that return pointers never criss-cross, so A must // belong to the child set of A.return, and B must belong to the child // set of B.return. a = parentA; b = parentB; } else { // The return pointers point to the same fiber. We'll have to use the // default, slow path: scan the child sets of each parent alternate to see // which child belongs to which set. // // Search parent A's child set let didFindChild = false; let child = parentA.child; while (child) { if (child === a) { didFindChild = true; a = parentA; b = parentB; break; } if (child === b) { didFindChild = true; b = parentA; a = parentB; break; } child = child.sibling; } if (!didFindChild) { // Search parent B's child set child = parentB.child; while (child) { if (child === a) { didFindChild = true; a = parentB; b = parentA; break; } if (child === b) { didFindChild = true; b = parentB; a = parentA; break; } child = child.sibling; } if (!didFindChild) { throw Error( "Child was not found in either parent set. This indicates a bug " + "in React related to the return pointer. Please file an issue." ); } } } if (a.alternate !== b) { throw Error( "Return fibers should always be each others' alternates. " + "This error is likely caused by a bug in React. Please file an issue." ); } } // If the root is not a host container, we're in a disconnected tree. I.e. // unmounted. if (a.tag !== HostRoot) { throw Error("Unable to find node on an unmounted component."); } if (a.stateNode.current === a) { // We've determined that A is the current branch. return fiber; } // Otherwise B has to be current branch. return alternate; } // END copied code function fiberToSerializedElement(fiber: Fiber): SerializedElement { return { displayName: getDisplayNameForFiber(fiber) || "Anonymous", id: getFiberIdThrows(fiber), key: fiber.key, type: getElementTypeForFiber(fiber), }; } function getOwnersList(id: number) { const fiber = findCurrentFiberUsingSlowPathById(id); if (fiber === null) { return null; } const { _debugOwner = null } = fiber; const owners = [fiberToSerializedElement(fiber)]; if (_debugOwner) { let owner: Fiber | null = _debugOwner; while (owner !== null) { owners.unshift(fiberToSerializedElement(owner)); owner = owner._debugOwner || null; } } return owners; } function getPathFrame(fiber: Fiber) { const { key } = fiber; const index = fiber.index; let displayName = getDisplayNameForFiber(fiber); switch (fiber.tag) { case HostRoot: // Roots don't have a real displayName, index, or key. // Instead, we'll use the pseudo key (childDisplayName:indexWithThatName). const id = getFiberIdThrows(fiber); const pseudoKey = getRootPseudoKey(id); if (pseudoKey === null) { throw new Error("Expected mounted root to have known pseudo key."); } displayName = pseudoKey; break; case HostComponent: displayName = fiber.type; break; } return { displayName, key, index, }; } // Produces a serializable representation that does a best effort // of identifying a particular Fiber between page reloads. // The return path will contain Fibers that are "invisible" to the store // because their keys and indexes are important to restoring the selection. function getPathForElement(id: number) { let fiber = getFiberById(id); if (fiber === null) { return null; } const keyPath = []; while (fiber !== null) { keyPath.push(getPathFrame(fiber)); fiber = fiber.return; } return keyPath.reverse(); } return { findNativeNodesForFiberID, getDisplayNameForFiberID, getFiberIDForNative, getOwnersList, getPathForElement, }; }
the_stack
import { html } from 'lit'; import { removeTestElement, createTestElement, componentIsStable } from '@cds/core/test'; import { listenForAttributeChange } from '@cds/core/internal'; import { CdsIcon } from '@cds/core/icon/icon.element.js'; import { CdsControl, ControlLabelLayout, CdsControlMessage } from '@cds/core/forms'; import '@cds/core/forms/register.js'; import '@cds/core/icon/register.js'; describe('cds-control', () => { let element: HTMLElement; let control: CdsControl; let controlInGroup: CdsControl; let controlCustomId: CdsControl; let message: CdsControlMessage; let label: HTMLLabelElement; let input: HTMLInputElement; let datalist: HTMLDataListElement; const getStatusIcon = () => control.shadowRoot.querySelector<CdsIcon>('cds-icon'); beforeEach(async () => { element = await createTestElement(html` <cds-control validate> <label>control</label> <input type="text" require /> <datalist> <option value="item 1"></option> <option value="item 2"></option> <option value="item 3"></option> </datalist> <cds-control-message error="valueMissing">message text</cds-control-message> </cds-control> <div cds-control-group> <cds-control id="control-in-group"> <label>control in group</label> <input type="text" /> </cds-control> </div> <cds-control id="custom-id-control"> <label>control in group</label> <input type="text" id="custom-id" /> </cds-control> `); control = element.querySelector<CdsControl>('cds-control'); controlInGroup = element.querySelector<CdsControl>('#control-in-group'); controlCustomId = element.querySelector<CdsControl>('#custom-id-control'); label = element.querySelector<HTMLLabelElement>('label'); input = element.querySelector<HTMLInputElement>('input'); datalist = element.querySelector<HTMLDataListElement>('datalist'); message = element.querySelector<CdsControlMessage>('cds-control-message'); }); afterEach(() => { removeTestElement(element); }); it('should associate the label and input', () => { expect(label.getAttribute('for')).toBe(input.getAttribute('id')); }); it('should associate the input and messages', () => { expect(input.getAttribute('aria-describedby').trim()).toBe(message.id); }); it('should associate the input and datalist if available', async () => { await componentIsStable(control); expect(input.id.length > 0).toBe(true); expect(datalist.id).toBe(input.id + '-datalist'); expect(input.getAttribute('list')).toBe(datalist.id); }); it('should use provided id when available', async () => { await componentIsStable(control); expect(controlCustomId.inputControl.id).toBe('custom-id'); }); it('should show appropriate status icon', async () => { await componentIsStable(control); expect(getStatusIcon()).toBe(null); control.status = 'error'; await componentIsStable(control); expect(getStatusIcon().status).toBe('danger'); control.status = 'success'; await componentIsStable(control); expect(getStatusIcon().status).toBe('success'); }); it('should apply disabled styles when native input is disabled', async () => { await componentIsStable(control); expect(input.hasAttribute('disabled')).toBe(false); input.setAttribute('disabled', ''); await componentIsStable(control); expect(control.hasAttribute('_disabled')).toBe(true); input.removeAttribute('disabled'); await componentIsStable(control); expect(control.hasAttribute('_disabled')).toBe(false); input.disabled = true; await componentIsStable(control); expect(control.hasAttribute('_disabled')).toBe(true); }); it('should allow control of the input width', async () => { control.style.width = '500px'; control.controlWidth = 'stretch'; await componentIsStable(control); const initialInputWidth = input.getBoundingClientRect().width; control.controlWidth = 'shrink'; await componentIsStable(control); const updatedInputWidth = input.getBoundingClientRect().width; expect(initialInputWidth > updatedInputWidth).toBe(true); }); it('should hide label appropriately for a11y when set for inline groups', async () => { await componentIsStable(control); expect(control.shadowRoot.querySelector('cds-internal-control-label')).toBeTruthy(); control.labelLayout = 'input-group' as ControlLabelLayout; // enum causes Jasmine to timeout from type not loading control.status = 'error'; await componentIsStable(control); expect(control.shadowRoot.querySelector('cds-icon[status=error]')).toBe(null); expect(control.shadowRoot.querySelector('cds-internal-control-label')).toBe(null); expect(control.shadowRoot.querySelector('slot[name=label]').parentElement.getAttribute('cds-layout')).toBe( 'display:screen-reader-only' ); }); it('should mark layout as stable when using a hidden label layout', async () => { await componentIsStable(control); control.labelLayout = 'hidden-label' as ControlLabelLayout; // enum causes Jasmine to timeout from type not loading expect(control.layoutStable).toBe(true); }); it('should apply focus style attribute when native element is focused', async () => { input.dispatchEvent(new Event('focusin')); await componentIsStable(control); expect(control.getAttribute('_focused')).toBe(''); input.dispatchEvent(new Event('focusout')); await componentIsStable(control); expect(control.getAttribute('_focused')).toBe(null); }); it('should apply disabled style attribute when native input is disabled', done => { expect(control.getAttribute('disabled')).toBe(null); listenForAttributeChange(control, '_disabled', () => { expect(control.getAttribute('_disabled')).toBe(''); done(); }); input.setAttribute('disabled', ''); }); it('should apply readonly style attribute when native input is readonly', done => { expect(control.getAttribute('readonly')).toBe(null); listenForAttributeChange(control, '_readonly', () => { expect(control.getAttribute('_readonly')).toBe(''); done(); }); input.setAttribute('readonly', ''); }); it('should convert form layout types to control layout types', () => { (control.layout as any) = 'horizontal-inline'; expect(control.layout).toBe('horizontal'); (control.layout as any) = 'vertical-inline'; expect(control.layout).toBe('vertical'); control.layout = null; expect(control.layout).toBe('horizontal'); }); it('should setup native html validation if set', async () => { await componentIsStable(control); expect(message.getAttribute('hidden')).toBe(''); }); it('should adjust style for RTL language support', async () => { expect(control.shadowRoot.querySelector('.rtl')).toBe(null); control.style.direction = 'rtl'; control.requestUpdate(); await componentIsStable(control); expect(control.shadowRoot.querySelector('.rtl')).toBeTruthy(); }); it('should not set input inline padding style if no control actions are used', async () => { await componentIsStable(control); expect(control.inputControl.hasAttribute('style')).toBe(false); }); it('should set the control slot if created in a control group element', async () => { await componentIsStable(controlInGroup); await componentIsStable(control); expect(controlInGroup.getAttribute('slot')).toBe('controls'); expect(control.getAttribute('slot')).toBe(null); }); }); describe('cds-control validation', () => { let element: HTMLElement; let message: CdsControlMessage; beforeEach(async () => { element = await createTestElement(html` <form novalidate> <cds-control validate> <label>control</label> <input type="text" require /> <cds-control-message error="valueMissing">message text</cds-control-message> </cds-control> </form> `); message = element.querySelector<CdsControlMessage>('cds-control-message'); }); afterEach(() => { removeTestElement(element); }); it('should prevent native html validation setup if form is set to novalidate', () => { expect(message.getAttribute('hidden')).toBe(null); }); }); describe('cds-control responsive', () => { let element: HTMLElement; let control: CdsControl; beforeEach(async () => { element = await createTestElement(html` <cds-control layout="compact"> <label>control</label> <input type="text" /> <cds-control-message>message text</cds-control-message> </cds-control> `); control = element.querySelector<CdsControl>('cds-control'); }); afterEach(() => { removeTestElement(element); }); xit('should adjust layout based on available width', async () => { await componentIsStable(control); expect(control.getAttribute('layout')).toBe('compact'); // control.addEventListener('layoutChange', () => { // expect(control.layout).toBe('vertical'); // done(); // }); // control.style.width = '100px'; // await componentIsStable(control); // expect(control.layout).toBe('vertical'); }); }); describe('cds-control with aria-label', () => { let element: HTMLElement; let control: CdsControl; beforeEach(async () => { element = await createTestElement(html` <cds-control layout="compact"> <input type="text" aria-label="control" /> <cds-control-message>message text</cds-control-message> </cds-control> `); control = element.querySelector<CdsControl>('cds-control'); }); afterEach(() => { removeTestElement(element); }); it('should not enable hidden label', async () => { await componentIsStable(control); expect(control.labelLayout).toBe(ControlLabelLayout.ariaLabel); }); }); describe('cds-control with aria-labelledby', () => { let element: HTMLElement; let control: CdsControl; beforeEach(async () => { element = await createTestElement(html` <cds-control layout="compact"> <input type="text" aria-labelledby="label" /> </cds-control> <p id="label">input label</p> `); control = element.querySelector<CdsControl>('cds-control'); }); afterEach(() => { removeTestElement(element); }); it('should not enable hidden label', async () => { await componentIsStable(control); expect(control.labelLayout).toBe(ControlLabelLayout.ariaLabel); }); }); describe('cds-control with label control action', () => { let element: HTMLElement; let control: CdsControl; let input: HTMLElement; beforeEach(async () => { element = await createTestElement(html` <cds-control> <label>with label control action</label> <cds-control-action action="label" aria-label="get more details"> <cds-icon shape="unknown"></cds-icon> </cds-control-action> <input placeholder="example" /> </cds-control> `); control = element.querySelector<CdsControl>('cds-control'); input = control.querySelector<HTMLElement>('input'); }); afterEach(() => { removeTestElement(element); }); it('should not apply padding inline styles to generic control', async () => { await componentIsStable(control); expect(input.getAttribute('style')).toBeNull(); }); }); describe('cds-control with non-input as control', () => { let element: HTMLElement; let control: CdsControl; let para: HTMLElement; beforeEach(async () => { element = await createTestElement(html` <cds-control> <label>control without native input</label> <p cds-text="body" cds-control aria-disabled="true">aria disabled</p> <cds-control-message error="valueMissing">message text</cds-control-message> </cds-control> `); control = element.querySelector<CdsControl>('cds-control'); para = control.querySelector<HTMLElement>('p[cds-control]'); }); afterEach(() => { removeTestElement(element); }); it('should apply disabled styles when non-input has aria-disabled', async () => { await componentIsStable(control); expect(control.hasAttribute('_disabled')).toBe(true, 'true aria-disabled is true'); para.setAttribute('aria-disabled', ''); await componentIsStable(control); expect(control.hasAttribute('_disabled')).toBe(false, 'non-true aria-disabled is false'); para.removeAttribute('aria-disabled'); await componentIsStable(control); expect(control.hasAttribute('_disabled')).toBe(false, 'no aria-disabled is false'); para.setAttribute('aria-disabled', 'true'); await componentIsStable(control); expect(control.hasAttribute('_disabled')).toBe(true, 'set aria-disabled is respected'); }); }); describe('cds-control status icon sizing', () => { let element: HTMLElement; let control: CdsControl; let controlWithSuccessStatus: CdsControl; let controlWithErrorStatus: CdsControl; let controlWithNeutralStatus: CdsControl; beforeEach(async () => { element = await createTestElement(html` <cds-control class="a-control"> <label>control with no status</label> <input placeholder="example" /> <cds-control-message>message text</cds-control-message> </cds-control> <cds-control class="a-control-with-neutral-status" status="neutral"> <label>control with neutral status</label> <input placeholder="example" /> <cds-control-message status="neutral">message text</cds-control-message> </cds-control> <cds-control class="a-control-with-success-status" status="success"> <label>control without native input</label> <input placeholder="example" /> <cds-control-message status="success">message text</cds-control-message> </cds-control> <cds-control class="a-control-with-error-status" status="success"> <label>control without native input</label> <input placeholder="example" /> <cds-control-message status="success">message text</cds-control-message> </cds-control> `); control = element.querySelector<CdsControl>('.a-control'); controlWithNeutralStatus = element.querySelector<CdsControl>('.a-control-with-neutral-status'); controlWithSuccessStatus = element.querySelector<CdsControl>('.a-control-with-success-status'); controlWithErrorStatus = element.querySelector<CdsControl>('.a-control-with-error-status'); }); afterEach(() => { removeTestElement(element); }); it('should apply .with-status-icon classname to controls with status', async () => { await componentIsStable(control); const containerWithNoStatus = control.shadowRoot.querySelector('.input-container'); const containerWithNeutralStatus = controlWithNeutralStatus.shadowRoot.querySelector('.input-container'); const containerWithSuccessStatus = controlWithSuccessStatus.shadowRoot.querySelector('.input-container'); const containerWithErrorStatus = controlWithErrorStatus.shadowRoot.querySelector('.input-container'); expect(containerWithNoStatus.classList.contains('with-status-icon')).toBe( false, 'no status means no class gets added' ); expect(containerWithNeutralStatus.classList.contains('with-status-icon')).toBe( false, 'neutral status means no class gets added' ); expect(containerWithSuccessStatus.classList.contains('with-status-icon')).toBe( true, 'success status means class gets added' ); expect(containerWithErrorStatus.classList.contains('with-status-icon')).toBe( true, 'error status means class gets added' ); }); });
the_stack
import {getShader} from './util'; import {RendererData} from './rendererData'; import {ModelInterp} from './modelInterp'; import {FilterMode, Layer, LayerShading, Material, RibbonEmitter} from '../model'; import {mat4, vec3} from 'gl-matrix'; let gl: WebGLRenderingContext; let shaderProgram: WebGLProgram; const shaderProgramLocations: any = {}; const vertexShader = ` attribute vec3 aVertexPosition; attribute vec2 aTextureCoord; uniform mat4 uMVMatrix; uniform mat4 uPMatrix; varying vec2 vTextureCoord; void main(void) { vec4 position = vec4(aVertexPosition, 1.0); gl_Position = uPMatrix * uMVMatrix * position; vTextureCoord = aTextureCoord; } `; const fragmentShader = ` precision mediump float; varying vec2 vTextureCoord; uniform sampler2D uSampler; uniform vec3 uReplaceableColor; uniform float uReplaceableType; uniform float uDiscardAlphaLevel; uniform vec4 uColor; float hypot (vec2 z) { float t; float x = abs(z.x); float y = abs(z.y); t = min(x, y); x = max(x, y); t = t / x; return (z.x == 0.0 && z.y == 0.0) ? 0.0 : x * sqrt(1.0 + t * t); } void main(void) { vec2 coords = vec2(vTextureCoord.s, vTextureCoord.t); if (uReplaceableType == 0.) { gl_FragColor = texture2D(uSampler, coords); } else if (uReplaceableType == 1.) { gl_FragColor = vec4(uReplaceableColor, 1.0); } else if (uReplaceableType == 2.) { float dist = hypot(coords - vec2(0.5, 0.5)) * 2.; float truncateDist = clamp(1. - dist * 1.4, 0., 1.); float alpha = sin(truncateDist); gl_FragColor = vec4(uReplaceableColor * alpha, 1.0); } gl_FragColor *= uColor; if (gl_FragColor[3] < uDiscardAlphaLevel) { discard; } } `; interface RibbonEmitterWrapper { emission: number; props: RibbonEmitter; capacity: number; baseCapacity: number; creationTimes: number[]; // xyz vertices: Float32Array; vertexBuffer: WebGLBuffer; // xy texCoords: Float32Array; texCoordBuffer: WebGLBuffer; } export class RibbonsController { public static initGL (glContext: WebGLRenderingContext): void { gl = glContext; RibbonsController.initShaders(); } private static initShaders (): void { const vertex = getShader(gl, vertexShader, gl.VERTEX_SHADER); const fragment = getShader(gl, fragmentShader, gl.FRAGMENT_SHADER); shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertex); gl.attachShader(shaderProgram, fragment); gl.linkProgram(shaderProgram); if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { alert('Could not initialise shaders'); } gl.useProgram(shaderProgram); shaderProgramLocations.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, 'aVertexPosition'); shaderProgramLocations.textureCoordAttribute = gl.getAttribLocation(shaderProgram, 'aTextureCoord'); shaderProgramLocations.pMatrixUniform = gl.getUniformLocation(shaderProgram, 'uPMatrix'); shaderProgramLocations.mvMatrixUniform = gl.getUniformLocation(shaderProgram, 'uMVMatrix'); shaderProgramLocations.samplerUniform = gl.getUniformLocation(shaderProgram, 'uSampler'); shaderProgramLocations.replaceableColorUniform = gl.getUniformLocation(shaderProgram, 'uReplaceableColor'); shaderProgramLocations.replaceableTypeUniform = gl.getUniformLocation(shaderProgram, 'uReplaceableType'); shaderProgramLocations.discardAlphaLevelUniform = gl.getUniformLocation(shaderProgram, 'uDiscardAlphaLevel'); shaderProgramLocations.colorUniform = gl.getUniformLocation(shaderProgram, 'uColor'); } private static resizeEmitterBuffers (emitter: RibbonEmitterWrapper, size: number): void { if (size <= emitter.capacity) { return; } size = Math.min(size, emitter.baseCapacity); const vertices = new Float32Array(size * 2 * 3); // 2 vertices * xyz const texCoords = new Float32Array(size * 2 * 2); // 2 vertices * xy if (emitter.vertices) { vertices.set(emitter.vertices); } emitter.vertices = vertices; emitter.texCoords = texCoords; emitter.capacity = size; if (!emitter.vertexBuffer) { emitter.vertexBuffer = gl.createBuffer(); emitter.texCoordBuffer = gl.createBuffer(); } } private interp: ModelInterp; private rendererData: RendererData; private emitters: RibbonEmitterWrapper[]; constructor (interp: ModelInterp, rendererData: RendererData) { this.interp = interp; this.rendererData = rendererData; this.emitters = []; if (rendererData.model.RibbonEmitters.length) { for (const ribbonEmitter of rendererData.model.RibbonEmitters) { const emitter: RibbonEmitterWrapper = { emission: 0, props: ribbonEmitter, capacity: 0, baseCapacity: 0, creationTimes: [], vertices: null, vertexBuffer: null, texCoords: null, texCoordBuffer: null }; emitter.baseCapacity = Math.ceil( ModelInterp.maxAnimVectorVal(emitter.props.EmissionRate) * emitter.props.LifeSpan ) + 1; // extra points this.emitters.push(emitter); } } } public update (delta: number): void { for (const emitter of this.emitters) { this.updateEmitter(emitter, delta); } } public render (mvMatrix: mat4, pMatrix: mat4): void { gl.useProgram(shaderProgram); gl.uniformMatrix4fv(shaderProgramLocations.pMatrixUniform, false, pMatrix); gl.uniformMatrix4fv(shaderProgramLocations.mvMatrixUniform, false, mvMatrix); gl.enableVertexAttribArray(shaderProgramLocations.vertexPositionAttribute); gl.enableVertexAttribArray(shaderProgramLocations.textureCoordAttribute); for (const emitter of this.emitters) { if (emitter.creationTimes.length < 2) { continue; } gl.uniform4f(shaderProgramLocations.colorUniform, emitter.props.Color[0], emitter.props.Color[1], emitter.props.Color[2], this.interp.animVectorVal(emitter.props.Alpha, 1) ); this.setGeneralBuffers(emitter); const materialID: number = emitter.props.MaterialID; const material: Material = this.rendererData.model.Materials[materialID]; for (let j = 0; j < material.Layers.length; ++j) { this.setLayerProps(material.Layers[j], this.rendererData.materialLayerTextureID[materialID][j]); this.renderEmitter(emitter); } } gl.disableVertexAttribArray(shaderProgramLocations.vertexPositionAttribute); gl.disableVertexAttribArray(shaderProgramLocations.textureCoordAttribute); } private updateEmitter (emitter: RibbonEmitterWrapper, delta: number): void { const now = Date.now(); const visibility = this.interp.animVectorVal(emitter.props.Visibility, 1); if (visibility > 0) { const emissionRate = emitter.props.EmissionRate; emitter.emission += emissionRate * delta; if (emitter.emission >= 1000) { // only once per tick emitter.emission = emitter.emission % 1000; if (emitter.creationTimes.length + 1 > emitter.capacity) { RibbonsController.resizeEmitterBuffers(emitter, emitter.creationTimes.length + 1); } this.appendVertices(emitter); emitter.creationTimes.push(now); } } if (emitter.creationTimes.length) { while (emitter.creationTimes[0] + emitter.props.LifeSpan * 1000 < now) { emitter.creationTimes.shift(); for (let i = 0; i + 6 + 5 < emitter.vertices.length; i += 6) { emitter.vertices[i] = emitter.vertices[i + 6]; emitter.vertices[i + 1] = emitter.vertices[i + 7]; emitter.vertices[i + 2] = emitter.vertices[i + 8]; emitter.vertices[i + 3] = emitter.vertices[i + 9]; emitter.vertices[i + 4] = emitter.vertices[i + 10]; emitter.vertices[i + 5] = emitter.vertices[i + 11]; } } } // still exists if (emitter.creationTimes.length) { this.updateEmitterTexCoords(emitter, now); } } private appendVertices (emitter: RibbonEmitterWrapper): void { const first: vec3 = vec3.clone(emitter.props.PivotPoint as vec3); const second: vec3 = vec3.clone(emitter.props.PivotPoint as vec3); first[1] -= this.interp.animVectorVal(emitter.props.HeightBelow, 0); second[1] += this.interp.animVectorVal(emitter.props.HeightAbove, 0); const emitterMatrix: mat4 = this.rendererData.nodes[emitter.props.ObjectId].matrix; vec3.transformMat4(first, first, emitterMatrix); vec3.transformMat4(second, second, emitterMatrix); const currentSize = emitter.creationTimes.length; emitter.vertices[currentSize * 6] = first[0]; emitter.vertices[currentSize * 6 + 1] = first[1]; emitter.vertices[currentSize * 6 + 2] = first[2]; emitter.vertices[currentSize * 6 + 3] = second[0]; emitter.vertices[currentSize * 6 + 4] = second[1]; emitter.vertices[currentSize * 6 + 5] = second[2]; } private updateEmitterTexCoords (emitter: RibbonEmitterWrapper, now: number): void { for (let i = 0; i < emitter.creationTimes.length; ++i) { let relativePos = (now - emitter.creationTimes[i]) / (emitter.props.LifeSpan * 1000); const textureSlot = this.interp.animVectorVal(emitter.props.TextureSlot, 0); const texCoordX = textureSlot % emitter.props.Columns; const texCoordY = Math.floor(textureSlot / emitter.props.Rows); const cellWidth = 1 / emitter.props.Columns; const cellHeight = 1 / emitter.props.Rows; relativePos = texCoordX * cellWidth + relativePos * cellWidth; emitter.texCoords[i * 2 * 2] = relativePos; emitter.texCoords[i * 2 * 2 + 1] = texCoordY * cellHeight; emitter.texCoords[i * 2 * 2 + 2] = relativePos; emitter.texCoords[i * 2 * 2 + 3] = (1 + texCoordY) * cellHeight; } } private setLayerProps (layer: Layer, textureID: number): void { const texture = this.rendererData.model.Textures[textureID]; if (layer.Shading & LayerShading.TwoSided) { gl.disable(gl.CULL_FACE); } else { gl.enable(gl.CULL_FACE); } if (layer.FilterMode === FilterMode.Transparent) { gl.uniform1f(shaderProgramLocations.discardAlphaLevelUniform, 0.75); } else { gl.uniform1f(shaderProgramLocations.discardAlphaLevelUniform, 0.); } if (layer.FilterMode === FilterMode.None) { gl.disable(gl.BLEND); gl.enable(gl.DEPTH_TEST); // gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.depthMask(true); } else if (layer.FilterMode === FilterMode.Transparent) { gl.enable(gl.BLEND); gl.enable(gl.DEPTH_TEST); gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.depthMask(true); } else if (layer.FilterMode === FilterMode.Blend) { gl.enable(gl.BLEND); gl.enable(gl.DEPTH_TEST); gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.depthMask(false); } else if (layer.FilterMode === FilterMode.Additive) { gl.enable(gl.BLEND); gl.enable(gl.DEPTH_TEST); gl.blendFunc(gl.SRC_COLOR, gl.ONE); gl.depthMask(false); } else if (layer.FilterMode === FilterMode.AddAlpha) { gl.enable(gl.BLEND); gl.enable(gl.DEPTH_TEST); gl.blendFunc(gl.SRC_ALPHA, gl.ONE); gl.depthMask(false); } else if (layer.FilterMode === FilterMode.Modulate) { gl.enable(gl.BLEND); gl.enable(gl.DEPTH_TEST); gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.ONE); gl.depthMask(false); } else if (layer.FilterMode === FilterMode.Modulate2x) { gl.enable(gl.BLEND); gl.enable(gl.DEPTH_TEST); gl.blendFuncSeparate(gl.DST_COLOR, gl.SRC_COLOR, gl.ZERO, gl.ONE); gl.depthMask(false); } if (texture.Image) { gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, this.rendererData.textures[texture.Image]); gl.uniform1i(shaderProgramLocations.samplerUniform, 0); gl.uniform1f(shaderProgramLocations.replaceableTypeUniform, 0); } else if (texture.ReplaceableId === 1 || texture.ReplaceableId === 2) { gl.uniform3fv(shaderProgramLocations.replaceableColorUniform, this.rendererData.teamColor); gl.uniform1f(shaderProgramLocations.replaceableTypeUniform, texture.ReplaceableId); } if (layer.Shading & LayerShading.NoDepthTest) { gl.disable(gl.DEPTH_TEST); } if (layer.Shading & LayerShading.NoDepthSet) { gl.depthMask(false); } /*if (typeof layer.TVertexAnimId === 'number') { let anim: TVertexAnim = this.rendererData.model.TextureAnims[layer.TVertexAnimId]; let translationRes = this.interp.vec3(translation, anim.Translation); let rotationRes = this.interp.quat(rotation, anim.Rotation); let scalingRes = this.interp.vec3(scaling, anim.Scaling); mat4.fromRotationTranslationScale( texCoordMat4, rotationRes || defaultRotation, translationRes || defaultTranslation, scalingRes || defaultScaling ); mat3.set( texCoordMat3, texCoordMat4[0], texCoordMat4[1], 0, texCoordMat4[4], texCoordMat4[5], 0, texCoordMat4[12], texCoordMat4[13], 0 ); gl.uniformMatrix3fv(shaderProgramLocations.tVertexAnimUniform, false, texCoordMat3); } else { gl.uniformMatrix3fv(shaderProgramLocations.tVertexAnimUniform, false, identifyMat3); }*/ } private setGeneralBuffers (emitter: RibbonEmitterWrapper): void { gl.bindBuffer(gl.ARRAY_BUFFER, emitter.texCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, emitter.texCoords, gl.DYNAMIC_DRAW); gl.vertexAttribPointer(shaderProgramLocations.textureCoordAttribute, 2, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, emitter.vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, emitter.vertices, gl.DYNAMIC_DRAW); gl.vertexAttribPointer(shaderProgramLocations.vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0); } private renderEmitter (emitter: RibbonEmitterWrapper): void { gl.drawArrays(gl.TRIANGLE_STRIP, 0, emitter.creationTimes.length * 2); } }
the_stack
import { ByteArrayArray } from "../../../ComplexProperties/ByteArrayArray"; import { CompleteName } from "../../../ComplexProperties/CompleteName"; import { ContactSource } from "../../../Enumerations/ContactSource"; import { DateTime } from "../../../DateTime"; import { EmailAddress } from "../../../ComplexProperties/EmailAddress"; import { EmailAddressCollection } from "../../../ComplexProperties/EmailAddressCollection"; import { EmailAddressDictionary } from "../../../ComplexProperties/EmailAddressDictionary"; import { EwsUtilities } from "../../EwsUtilities"; import { ExchangeService } from "../../ExchangeService"; import { ExchangeVersion } from "../../../Enumerations/ExchangeVersion"; import { FileAsMapping } from "../../../Enumerations/FileAsMapping"; import { FileAttachment } from "../../../ComplexProperties/FileAttachment"; import { IOutParam } from "../../../Interfaces/IOutParam"; import { ImAddressDictionary } from "../../../ComplexProperties/ImAddressDictionary"; import { ItemAttachment } from "../../../ComplexProperties/ItemAttachment"; import { ItemId } from "../../../ComplexProperties/ItemId"; import { PhoneNumberDictionary } from "../../../ComplexProperties/PhoneNumberDictionary"; import { PhysicalAddressDictionary } from "../../../ComplexProperties/PhysicalAddressDictionary"; import { PhysicalAddressIndex } from "../../../Enumerations/PhysicalAddressIndex"; import { Promise } from "../../../Promise"; import { PropertyException } from "../../../Exceptions/PropertyException"; import { PropertySet } from "../../PropertySet"; import { Schemas } from "../Schemas/Schemas"; import { ServiceObjectSchema } from "../Schemas/ServiceObjectSchema"; import { StringList } from "../../../ComplexProperties/StringList"; import { Strings } from "../../../Strings"; import { XmlElementNames } from "../../XmlElementNames"; import { Item } from "./Item"; /** * Represents a **contact**. Properties available on contacts are defined in the *ContactSchema* class. * */ export class Contact extends Item { /** required to check [Attachable] attribute, AttachmentCollection.AddItemAttachment<TItem>() checks for non inherited [Attachable] attribute. */ public static get Attachable(): boolean { return (<any>this).name === "Contact"; }; private static ContactPictureName: string = "ContactPicture.jpg"; /** * Gets or set the name under which this contact is filed as. FileAs can be manually set or can be automatically calculated based on the value of the FileAsMapping property. * */ get FileAs(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.FileAs); } set FileAs(value: string) { this.PropertyBag._setItem(Schemas.ContactSchema.FileAs, value); } /** * Gets or sets a value indicating how the FileAs property should be automatically calculated. * */ get FileAsMapping(): FileAsMapping { return <FileAsMapping>this.PropertyBag._getItem(Schemas.ContactSchema.FileAsMapping); } set FileAsMapping(value: FileAsMapping) { this.PropertyBag._setItem(Schemas.ContactSchema.FileAsMapping, value); } /** * Gets or sets the display name of the contact. * */ get DisplayName(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.DisplayName); } set DisplayName(value: string) { this.PropertyBag._setItem(Schemas.ContactSchema.DisplayName, value); } /** * Gets or sets the given name of the contact. * */ get GivenName(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.GivenName); } set GivenName(value: string) { this.PropertyBag._setItem(Schemas.ContactSchema.GivenName, value); } /** * Gets or sets the initials of the contact. * */ get Initials(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.Initials); } set Initials(value: string) { this.PropertyBag._setItem(Schemas.ContactSchema.Initials, value); } /** * Gets or sets the middle mame of the contact. * */ get MiddleName(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.MiddleName); } set MiddleName(value: string) { this.PropertyBag._setItem(Schemas.ContactSchema.MiddleName, value); } /** * Gets or sets the nick name of the contact. * */ get NickName(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.NickName); } set NickName(value: string) { this.PropertyBag._setItem(Schemas.ContactSchema.NickName, value); } /** * Gets the complete name of the contact. * */ get CompleteName(): CompleteName { return <CompleteName>this.PropertyBag._getItem(Schemas.ContactSchema.CompleteName); } /** * Gets or sets the compnay name of the contact. * */ get CompanyName(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.CompanyName); } set CompanyName(value: string) { this.PropertyBag._setItem(Schemas.ContactSchema.CompanyName, value); } /** * Gets an indexed list of e-mail addresses for the contact. For example, to set the first e-mail address, * use the following syntax: EmailAddresses[EmailAddressKey.EmailAddress1] = "john.doe@contoso.com" * */ get EmailAddresses(): EmailAddressDictionary { return <EmailAddressDictionary>this.PropertyBag._getItem(Schemas.ContactSchema.EmailAddresses); } /** * Gets an indexed list of physical addresses for the contact. For example, to set the business address, * use the following syntax: PhysicalAddresses[PhysicalAddressKey.Business] = new PhysicalAddressEntry() * */ get PhysicalAddresses(): PhysicalAddressDictionary { return <PhysicalAddressDictionary>this.PropertyBag._getItem(Schemas.ContactSchema.PhysicalAddresses); } /** * Gets an indexed list of phone numbers for the contact. For example, to set the home phone number, * use the following syntax: PhoneNumbers[PhoneNumberKey.HomePhone] = "phone number" * */ get PhoneNumbers(): PhoneNumberDictionary { return <PhoneNumberDictionary>this.PropertyBag._getItem(Schemas.ContactSchema.PhoneNumbers); } /** * Gets or sets the contact's assistant name. * */ get AssistantName(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.AssistantName); } set AssistantName(value: string) { this.PropertyBag._setItem(Schemas.ContactSchema.AssistantName, value); } /** * Gets or sets the birthday of the contact. * */ get Birthday(): DateTime { return <DateTime>this.PropertyBag._getItem(Schemas.ContactSchema.Birthday); } set Birthday(value: DateTime) { this.PropertyBag._setItem(Schemas.ContactSchema.Birthday, value); } /** * Gets or sets the business home page of the contact. * */ get BusinessHomePage(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.BusinessHomePage); } set BusinessHomePage(value: string) { this.PropertyBag._setItem(Schemas.ContactSchema.BusinessHomePage, value); } /** * Gets or sets a list of children for the contact. * */ get Children(): StringList { return <StringList>this.PropertyBag._getItem(Schemas.ContactSchema.Children); } set Children(value: StringList) { this.PropertyBag._setItem(Schemas.ContactSchema.Children, value); } /** * Gets or sets a list of companies for the contact. * */ get Companies(): StringList { return <StringList>this.PropertyBag._getItem(Schemas.ContactSchema.Companies); } set Companies(value: StringList) { this.PropertyBag._setItem(Schemas.ContactSchema.Companies, value); } /** * Gets the source of the contact. * */ get ContactSource(): ContactSource { return <ContactSource>this.PropertyBag._getItem(Schemas.ContactSchema.ContactSource); } /** * Gets or sets the department of the contact. * */ get Department(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.Department); } set Department(value: string) { this.PropertyBag._setItem(Schemas.ContactSchema.Department, value); } /** * Gets or sets the generation of the contact. * */ get Generation(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.Generation); } set Generation(value: string) { this.PropertyBag._setItem(Schemas.ContactSchema.Generation, value); } /** * Gets an indexed list of Instant Messaging addresses for the contact. * For example, to set the first IM address, use the following syntax: ImAddresses[ImAddressKey.ImAddress1] = "john.doe@contoso.com" * */ get ImAddresses(): ImAddressDictionary { return <ImAddressDictionary>this.PropertyBag._getItem(Schemas.ContactSchema.ImAddresses); } /** * Gets or sets the contact's job title. * */ get JobTitle(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.JobTitle); } set JobTitle(value: string) { this.PropertyBag._setItem(Schemas.ContactSchema.JobTitle, value); } /** * Gets or sets the name of the contact's manager. * */ get Manager(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.Manager); } set Manager(value: string) { this.PropertyBag._setItem(Schemas.ContactSchema.Manager, value); } /** * Gets or sets the mileage for the contact. * */ get Mileage(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.Mileage); } set Mileage(value: string) { this.PropertyBag._setItem(Schemas.ContactSchema.Mileage, value); } /** * Gets or sets the location of the contact's office. * */ get OfficeLocation(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.OfficeLocation); } set OfficeLocation(value: string) { this.PropertyBag._setItem(Schemas.ContactSchema.OfficeLocation, value); } /** * Gets or sets the index of the contact's postal address. When set, PostalAddressIndex refers to an entry in the PhysicalAddresses indexed list. * */ get PostalAddressIndex(): PhysicalAddressIndex { return <PhysicalAddressIndex>this.PropertyBag._getItem(Schemas.ContactSchema.PostalAddressIndex); } set PostalAddressIndex(value: PhysicalAddressIndex) { this.PropertyBag._setItem(Schemas.ContactSchema.PostalAddressIndex, value); } /** * Gets or sets the contact's profession. * */ get Profession(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.Profession); } set Profession(value: string) { this.PropertyBag._setItem(Schemas.ContactSchema.Profession, value); } /** * Gets or sets the name of the contact's spouse. * */ get SpouseName(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.SpouseName); } set SpouseName(value: string) { this.PropertyBag._setItem(Schemas.ContactSchema.SpouseName, value); } /** * Gets or sets the surname of the contact. * */ get Surname(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.Surname); } set Surname(value: string) { this.PropertyBag._setItem(Schemas.ContactSchema.Surname, value); } /** * Gets or sets the date of the contact's wedding anniversary. * */ get WeddingAnniversary(): DateTime { return <DateTime>this.PropertyBag._getItem(Schemas.ContactSchema.WeddingAnniversary); } set WeddingAnniversary(value: DateTime) { this.PropertyBag._setItem(Schemas.ContactSchema.WeddingAnniversary, value); } /** * Gets a value indicating whether this contact has a picture associated with it. * */ get HasPicture(): boolean { return <boolean>this.PropertyBag._getItem(Schemas.ContactSchema.HasPicture); } /** * Gets the full phonetic name from the directory * */ get PhoneticFullName(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.PhoneticFullName); } /** * Gets the phonetic first name from the directory * */ get PhoneticFirstName(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.PhoneticFirstName); } /** * Gets the phonetic last name from the directory * */ get PhoneticLastName(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.PhoneticLastName); } /** * Gets the Alias from the directory * */ get Alias(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.Alias); } /** * Get the Notes from the directory * */ get Notes(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.Notes); } /** * Gets the Photo from the directory **Unstable: needs testing** * */ get DirectoryPhoto(): number[] { return <number[]>this.PropertyBag._getItem(Schemas.ContactSchema.Photo); } /** * Gets the User SMIME certificate from the directory **Unstable: needs testing** * //ref: cant use bytearray, using base64 decoded string instead - number[][] * */ get UserSMIMECertificate(): string[] { var byteArrayArray: ByteArrayArray = <ByteArrayArray>this.PropertyBag._getItem(Schemas.ContactSchema.UserSMIMECertificate); return byteArrayArray.Content; } /** * Gets the MSExchange certificate from the directory **Unstable: needs testing** * //ref: cant use bytearray, using base64 decoded string instead - number[][] * */ get MSExchangeCertificate(): string[] { var byteArrayArray: ByteArrayArray = <ByteArrayArray>this.PropertyBag._getItem(Schemas.ContactSchema.MSExchangeCertificate); return byteArrayArray.Content; } /** * Gets the DirectoryID as Guid or DN string * */ get DirectoryId(): string { return <string>this.PropertyBag._getItem(Schemas.ContactSchema.DirectoryId); } /** * Gets the manager mailbox information * */ get ManagerMailbox(): EmailAddress { return <EmailAddress>this.PropertyBag._getItem(Schemas.ContactSchema.ManagerMailbox); } /** * Get the direct reports mailbox information * */ get DirectReports(): EmailAddressCollection { return <EmailAddressCollection>this.PropertyBag._getItem(Schemas.ContactSchema.DirectReports); } /** * Initializes an unsaved local instance of . To bind to an existing contact, use Contact.Bind() instead. * * @param {ExchangeService} service The ExchangeService object to which the contact will be bound. */ constructor(service: ExchangeService); /** * @internal Initializes a new instance of the **Contact** class. * * @param {ItemAttachment} parentAttachment The parent attachment. */ constructor(parentAttachment: ItemAttachment); constructor(serviceOrParentAttachment: ExchangeService | ItemAttachment) { super(serviceOrParentAttachment instanceof ItemAttachment ? serviceOrParentAttachment.Service : <ExchangeService>serviceOrParentAttachment);//todo:fix -can not user instanceof with exchangeservice, creates circular loop with ewsutility } /** * Binds to an existing contact and loads the specified set of properties. * Calling this method results in a call to EWS. * * @param {ExchangeService} service The service to use to bind to the contact. * @param {ItemId} id The Id of the contact to bind to. * @return {Promise<Contact>} A Contact instance representing the contact corresponding to the specified Id :Promise. */ static Bind(service: ExchangeService, id: ItemId): Promise<Contact>; /** * Binds to an existing contact and loads the specified set of properties. * Calling this method results in a call to EWS. * * @param {ExchangeService} service The service to use to bind to the contact. * @param {ItemId} id The Id of the contact to bind to. * @param {PropertySet} propertySet The set of properties to load. * @return {Promise<Contact>} A Contact instance representing the contact corresponding to the specified Id :Promise. */ static Bind(service: ExchangeService, id: ItemId, propertySet: PropertySet): Promise<Contact>; // Bind(service: ExchangeService, id: ItemId, propertySet: PropertySet = PropertySet.FirstClassProperties): Promise<Contact> { //removed // return Contact.Bind(service, id, propertySet); // } static Bind(service: ExchangeService, id: ItemId, propertySet: PropertySet = PropertySet.FirstClassProperties): Promise<Contact> { return service.BindToItem<Contact>(id, propertySet, Contact); } /** * Retrieves the file attachment that holds the contact's picture. **Unstable: needs testing** * * @return {FileAttachment} The file attachment that holds the contact's picture. */ GetContactPictureAttachment(): FileAttachment { EwsUtilities.ValidateMethodVersion(this.Service, ExchangeVersion.Exchange2010, "GetContactPictureAttachment"); if (!this.PropertyBag.IsPropertyLoaded(Schemas.ContactSchema.Attachments)) { throw new PropertyException(Strings.AttachmentCollectionNotLoaded); } for (var attachment of this.Attachments.Items) { //todo: implement typecasting var fileAttachment = <FileAttachment>attachment; if (fileAttachment.IsContactPhoto) { return fileAttachment; } } return null; } /** * @internal Gets the minimum required server version. * * @return {ExchangeVersion} Earliest Exchange version in which this service object type is supported. */ GetMinimumRequiredServerVersion(): ExchangeVersion { return ExchangeVersion.Exchange2007_SP1; } /** * @internal Internal method to return the schema associated with this type of object. * * @return {ServiceObjectSchema} The schema associated with this type of object. */ GetSchema(): ServiceObjectSchema { return Schemas.ContactSchema.Instance; } /** * @internal Gets the element name of item in XML * * @return {string} name of elelment */ GetXmlElementName(): string { return XmlElementNames.Contact; } /** * Removes the picture from local attachment collection. * */ private InternalRemoveContactPicture(): void { // Iterates in reverse order to remove file attachments that have IsContactPhoto set to true. for (var index = this.Attachments.Count - 1; index >= 0; index--) { //todo: implement safe typecasting var fileAttachment: FileAttachment = <FileAttachment>this.Attachments._getItem(index); if (fileAttachment != null) { if (fileAttachment.IsContactPhoto) { this.Attachments.Remove(fileAttachment); } } } } /** * Removes the contact's picture. * */ RemoveContactPicture(): void { EwsUtilities.ValidateMethodVersion(this.Service, ExchangeVersion.Exchange2010, "RemoveContactPicture"); if (!this.PropertyBag.IsPropertyLoaded(Schemas.ContactSchema.Attachments)) { throw new PropertyException(Strings.AttachmentCollectionNotLoaded); } this.InternalRemoveContactPicture(); } //ref: //todo: Not Implemented //SetContactPicture(contentStream: any /*System.IO.Stream*/): any { throw new Error("Contact.ts - SetContactPicture : Not implemented."); } //SetContactPicture(content: number[] /*System.Byte[]*/): any { throw new Error("Contact.ts - SetContactPicture : Not implemented."); } //SetContactPicture(fileName: string): any { throw new Error("Contact.ts - SetContactPicture : Not implemented."); } /** * Sets the contact's picture using the base64 content of file. * * @param {string} base64Content base64 content of picture attachment. * @param {string} attachmentName name of the picture attachment. * */ SetContactPicture(base64Content: string, attachmentName: string): void { EwsUtilities.ValidateMethodVersion(this.Service, ExchangeVersion.Exchange2010, "SetContactPicture"); this.InternalRemoveContactPicture(); let fileAttachment: FileAttachment = this.Attachments.AddFileAttachment(attachmentName, base64Content); fileAttachment.IsContactPhoto = true; } /** * @internal Validates this instance. * */ Validate(): void { super.Validate(); var fileAsMapping: IOutParam<any> = { outValue: null }; if (this.TryGetProperty(Schemas.ContactSchema.FileAsMapping, fileAsMapping)) { // FileAsMapping is extended by 5 new values in 2010 mode. Validate that they are used according the version. EwsUtilities.ValidateEnumVersionValue(FileAsMapping, fileAsMapping.outValue, this.Service.RequestedServerVersion, "FileAsMapping"); } } }
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as stream from 'stream'; import * as models from '../models'; /** * @class * ImageModeration * __NOTE__: An instance of this class is automatically created for an * instance of the ContentModeratorClient. */ export interface ImageModeration { /** * Returns the list of faces found. * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<FoundFaces>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ findFacesWithHttpOperationResponse(options?: { cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FoundFaces>>; /** * Returns the list of faces found. * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {FoundFaces} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {FoundFaces} [result] - The deserialized result object if an error did not occur. * See {@link FoundFaces} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ findFaces(options?: { cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.FoundFaces>; findFaces(callback: ServiceCallback<models.FoundFaces>): void; findFaces(options: { cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FoundFaces>): void; /** * Returns any text found in the image for the language specified. If no * language is specified in input then the detection defaults to English. * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {boolean} [options.enhanced] When set to True, the image goes through * additional processing to come with additional candidates. * * image/tiff is not supported when enhanced is set to true * * Note: This impacts the response time. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OCR>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ oCRMethodWithHttpOperationResponse(language: string, options?: { cacheImage? : boolean, enhanced? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OCR>>; /** * Returns any text found in the image for the language specified. If no * language is specified in input then the detection defaults to English. * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {boolean} [options.enhanced] When set to True, the image goes through * additional processing to come with additional candidates. * * image/tiff is not supported when enhanced is set to true * * Note: This impacts the response time. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OCR} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OCR} [result] - The deserialized result object if an error did not occur. * See {@link OCR} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ oCRMethod(language: string, options?: { cacheImage? : boolean, enhanced? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.OCR>; oCRMethod(language: string, callback: ServiceCallback<models.OCR>): void; oCRMethod(language: string, options: { cacheImage? : boolean, enhanced? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OCR>): void; /** * Returns probabilities of the image containing racy or adult content. * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Evaluate>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ evaluateMethodWithHttpOperationResponse(options?: { cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Evaluate>>; /** * Returns probabilities of the image containing racy or adult content. * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Evaluate} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Evaluate} [result] - The deserialized result object if an error did not occur. * See {@link Evaluate} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ evaluateMethod(options?: { cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.Evaluate>; evaluateMethod(callback: ServiceCallback<models.Evaluate>): void; evaluateMethod(options: { cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Evaluate>): void; /** * Fuzzily match an image against one of your custom Image Lists. You can * create and manage your custom image lists using <a * href="/docs/services/578ff44d2703741568569ab9/operations/578ff7b12703741568569abe">this</a> * API. * * Returns ID and tags of matching image.<br/> * <br/> * Note: Refresh Index must be run on the corresponding Image List before * additions and removals are reflected in the response. * * @param {object} [options] Optional Parameters. * * @param {string} [options.listId] The list Id. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MatchResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ matchMethodWithHttpOperationResponse(options?: { listId? : string, cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MatchResponse>>; /** * Fuzzily match an image against one of your custom Image Lists. You can * create and manage your custom image lists using <a * href="/docs/services/578ff44d2703741568569ab9/operations/578ff7b12703741568569abe">this</a> * API. * * Returns ID and tags of matching image.<br/> * <br/> * Note: Refresh Index must be run on the corresponding Image List before * additions and removals are reflected in the response. * * @param {object} [options] Optional Parameters. * * @param {string} [options.listId] The list Id. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MatchResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MatchResponse} [result] - The deserialized result object if an error did not occur. * See {@link MatchResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ matchMethod(options?: { listId? : string, cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.MatchResponse>; matchMethod(callback: ServiceCallback<models.MatchResponse>): void; matchMethod(options: { listId? : string, cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MatchResponse>): void; /** * Returns the list of faces found. * * @param {object} imageStream The image file. * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<FoundFaces>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ findFacesFileInputWithHttpOperationResponse(imageStream: stream.Readable, options?: { cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FoundFaces>>; /** * Returns the list of faces found. * * @param {object} imageStream The image file. * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {FoundFaces} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {FoundFaces} [result] - The deserialized result object if an error did not occur. * See {@link FoundFaces} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ findFacesFileInput(imageStream: stream.Readable, options?: { cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.FoundFaces>; findFacesFileInput(imageStream: stream.Readable, callback: ServiceCallback<models.FoundFaces>): void; findFacesFileInput(imageStream: stream.Readable, options: { cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FoundFaces>): void; /** * Returns the list of faces found. * * @param {string} contentType The content type. * * @param {object} imageUrl The image url. * * @param {string} [imageUrl.dataRepresentation] * * @param {string} [imageUrl.value] * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<FoundFaces>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ findFacesUrlInputWithHttpOperationResponse(contentType: string, imageUrl: models.BodyModel, options?: { cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.FoundFaces>>; /** * Returns the list of faces found. * * @param {string} contentType The content type. * * @param {object} imageUrl The image url. * * @param {string} [imageUrl.dataRepresentation] * * @param {string} [imageUrl.value] * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {FoundFaces} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {FoundFaces} [result] - The deserialized result object if an error did not occur. * See {@link FoundFaces} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ findFacesUrlInput(contentType: string, imageUrl: models.BodyModel, options?: { cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.FoundFaces>; findFacesUrlInput(contentType: string, imageUrl: models.BodyModel, callback: ServiceCallback<models.FoundFaces>): void; findFacesUrlInput(contentType: string, imageUrl: models.BodyModel, options: { cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.FoundFaces>): void; /** * Returns any text found in the image for the language specified. If no * language is specified in input then the detection defaults to English. * * @param {string} language Language of the terms. * * @param {string} contentType The content type. * * @param {object} imageUrl The image url. * * @param {string} [imageUrl.dataRepresentation] * * @param {string} [imageUrl.value] * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {boolean} [options.enhanced] When set to True, the image goes through * additional processing to come with additional candidates. * * image/tiff is not supported when enhanced is set to true * * Note: This impacts the response time. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OCR>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ oCRUrlInputWithHttpOperationResponse(language: string, contentType: string, imageUrl: models.BodyModel, options?: { cacheImage? : boolean, enhanced? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OCR>>; /** * Returns any text found in the image for the language specified. If no * language is specified in input then the detection defaults to English. * * @param {string} language Language of the terms. * * @param {string} contentType The content type. * * @param {object} imageUrl The image url. * * @param {string} [imageUrl.dataRepresentation] * * @param {string} [imageUrl.value] * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {boolean} [options.enhanced] When set to True, the image goes through * additional processing to come with additional candidates. * * image/tiff is not supported when enhanced is set to true * * Note: This impacts the response time. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OCR} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OCR} [result] - The deserialized result object if an error did not occur. * See {@link OCR} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ oCRUrlInput(language: string, contentType: string, imageUrl: models.BodyModel, options?: { cacheImage? : boolean, enhanced? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.OCR>; oCRUrlInput(language: string, contentType: string, imageUrl: models.BodyModel, callback: ServiceCallback<models.OCR>): void; oCRUrlInput(language: string, contentType: string, imageUrl: models.BodyModel, options: { cacheImage? : boolean, enhanced? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OCR>): void; /** * Returns any text found in the image for the language specified. If no * language is specified in input then the detection defaults to English. * * @param {string} language Language of the terms. * * @param {object} imageStream The image file. * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {boolean} [options.enhanced] When set to True, the image goes through * additional processing to come with additional candidates. * * image/tiff is not supported when enhanced is set to true * * Note: This impacts the response time. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OCR>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ oCRFileInputWithHttpOperationResponse(language: string, imageStream: stream.Readable, options?: { cacheImage? : boolean, enhanced? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OCR>>; /** * Returns any text found in the image for the language specified. If no * language is specified in input then the detection defaults to English. * * @param {string} language Language of the terms. * * @param {object} imageStream The image file. * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {boolean} [options.enhanced] When set to True, the image goes through * additional processing to come with additional candidates. * * image/tiff is not supported when enhanced is set to true * * Note: This impacts the response time. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OCR} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OCR} [result] - The deserialized result object if an error did not occur. * See {@link OCR} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ oCRFileInput(language: string, imageStream: stream.Readable, options?: { cacheImage? : boolean, enhanced? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.OCR>; oCRFileInput(language: string, imageStream: stream.Readable, callback: ServiceCallback<models.OCR>): void; oCRFileInput(language: string, imageStream: stream.Readable, options: { cacheImage? : boolean, enhanced? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OCR>): void; /** * Returns probabilities of the image containing racy or adult content. * * @param {object} imageStream The image file. * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Evaluate>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ evaluateFileInputWithHttpOperationResponse(imageStream: stream.Readable, options?: { cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Evaluate>>; /** * Returns probabilities of the image containing racy or adult content. * * @param {object} imageStream The image file. * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Evaluate} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Evaluate} [result] - The deserialized result object if an error did not occur. * See {@link Evaluate} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ evaluateFileInput(imageStream: stream.Readable, options?: { cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.Evaluate>; evaluateFileInput(imageStream: stream.Readable, callback: ServiceCallback<models.Evaluate>): void; evaluateFileInput(imageStream: stream.Readable, options: { cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Evaluate>): void; /** * Returns probabilities of the image containing racy or adult content. * * @param {string} contentType The content type. * * @param {object} imageUrl The image url. * * @param {string} [imageUrl.dataRepresentation] * * @param {string} [imageUrl.value] * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Evaluate>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ evaluateUrlInputWithHttpOperationResponse(contentType: string, imageUrl: models.BodyModel, options?: { cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Evaluate>>; /** * Returns probabilities of the image containing racy or adult content. * * @param {string} contentType The content type. * * @param {object} imageUrl The image url. * * @param {string} [imageUrl.dataRepresentation] * * @param {string} [imageUrl.value] * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Evaluate} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Evaluate} [result] - The deserialized result object if an error did not occur. * See {@link Evaluate} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ evaluateUrlInput(contentType: string, imageUrl: models.BodyModel, options?: { cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.Evaluate>; evaluateUrlInput(contentType: string, imageUrl: models.BodyModel, callback: ServiceCallback<models.Evaluate>): void; evaluateUrlInput(contentType: string, imageUrl: models.BodyModel, options: { cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Evaluate>): void; /** * Fuzzily match an image against one of your custom Image Lists. You can * create and manage your custom image lists using <a * href="/docs/services/578ff44d2703741568569ab9/operations/578ff7b12703741568569abe">this</a> * API. * * Returns ID and tags of matching image.<br/> * <br/> * Note: Refresh Index must be run on the corresponding Image List before * additions and removals are reflected in the response. * * @param {string} contentType The content type. * * @param {object} imageUrl The image url. * * @param {string} [imageUrl.dataRepresentation] * * @param {string} [imageUrl.value] * * @param {object} [options] Optional Parameters. * * @param {string} [options.listId] The list Id. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MatchResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ matchUrlInputWithHttpOperationResponse(contentType: string, imageUrl: models.BodyModel, options?: { listId? : string, cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MatchResponse>>; /** * Fuzzily match an image against one of your custom Image Lists. You can * create and manage your custom image lists using <a * href="/docs/services/578ff44d2703741568569ab9/operations/578ff7b12703741568569abe">this</a> * API. * * Returns ID and tags of matching image.<br/> * <br/> * Note: Refresh Index must be run on the corresponding Image List before * additions and removals are reflected in the response. * * @param {string} contentType The content type. * * @param {object} imageUrl The image url. * * @param {string} [imageUrl.dataRepresentation] * * @param {string} [imageUrl.value] * * @param {object} [options] Optional Parameters. * * @param {string} [options.listId] The list Id. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MatchResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MatchResponse} [result] - The deserialized result object if an error did not occur. * See {@link MatchResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ matchUrlInput(contentType: string, imageUrl: models.BodyModel, options?: { listId? : string, cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.MatchResponse>; matchUrlInput(contentType: string, imageUrl: models.BodyModel, callback: ServiceCallback<models.MatchResponse>): void; matchUrlInput(contentType: string, imageUrl: models.BodyModel, options: { listId? : string, cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MatchResponse>): void; /** * Fuzzily match an image against one of your custom Image Lists. You can * create and manage your custom image lists using <a * href="/docs/services/578ff44d2703741568569ab9/operations/578ff7b12703741568569abe">this</a> * API. * * Returns ID and tags of matching image.<br/> * <br/> * Note: Refresh Index must be run on the corresponding Image List before * additions and removals are reflected in the response. * * @param {object} imageStream The image file. * * @param {object} [options] Optional Parameters. * * @param {string} [options.listId] The list Id. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MatchResponse>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ matchFileInputWithHttpOperationResponse(imageStream: stream.Readable, options?: { listId? : string, cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MatchResponse>>; /** * Fuzzily match an image against one of your custom Image Lists. You can * create and manage your custom image lists using <a * href="/docs/services/578ff44d2703741568569ab9/operations/578ff7b12703741568569abe">this</a> * API. * * Returns ID and tags of matching image.<br/> * <br/> * Note: Refresh Index must be run on the corresponding Image List before * additions and removals are reflected in the response. * * @param {object} imageStream The image file. * * @param {object} [options] Optional Parameters. * * @param {string} [options.listId] The list Id. * * @param {boolean} [options.cacheImage] Whether to retain the submitted image * for future use; defaults to false if omitted. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MatchResponse} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MatchResponse} [result] - The deserialized result object if an error did not occur. * See {@link MatchResponse} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ matchFileInput(imageStream: stream.Readable, options?: { listId? : string, cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.MatchResponse>; matchFileInput(imageStream: stream.Readable, callback: ServiceCallback<models.MatchResponse>): void; matchFileInput(imageStream: stream.Readable, options: { listId? : string, cacheImage? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MatchResponse>): void; } /** * @class * TextModeration * __NOTE__: An instance of this class is automatically created for an * instance of the ContentModeratorClient. */ export interface TextModeration { /** * @summary Detect profanity and match against custom and shared blacklists * * Detects profanity in more than 100 languages and match against custom and * shared blacklists. * * @param {string} textContentType The content type. Possible values include: * 'text/plain', 'text/html', 'text/xml', 'text/markdown' * * @param {object} textContent Content to screen. * * @param {object} [options] Optional Parameters. * * @param {string} [options.language] Language of the text. * * @param {boolean} [options.autocorrect] Autocorrect text. * * @param {boolean} [options.pII] Detect personal identifiable information. * * @param {string} [options.listId] The list Id. * * @param {boolean} [options.classify] Classify input. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Screen>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ screenTextWithHttpOperationResponse(textContentType: string, textContent: stream.Readable, options?: { language? : string, autocorrect? : boolean, pII? : boolean, listId? : string, classify? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Screen>>; /** * @summary Detect profanity and match against custom and shared blacklists * * Detects profanity in more than 100 languages and match against custom and * shared blacklists. * * @param {string} textContentType The content type. Possible values include: * 'text/plain', 'text/html', 'text/xml', 'text/markdown' * * @param {object} textContent Content to screen. * * @param {object} [options] Optional Parameters. * * @param {string} [options.language] Language of the text. * * @param {boolean} [options.autocorrect] Autocorrect text. * * @param {boolean} [options.pII] Detect personal identifiable information. * * @param {string} [options.listId] The list Id. * * @param {boolean} [options.classify] Classify input. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Screen} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Screen} [result] - The deserialized result object if an error did not occur. * See {@link Screen} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ screenText(textContentType: string, textContent: stream.Readable, options?: { language? : string, autocorrect? : boolean, pII? : boolean, listId? : string, classify? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.Screen>; screenText(textContentType: string, textContent: stream.Readable, callback: ServiceCallback<models.Screen>): void; screenText(textContentType: string, textContent: stream.Readable, options: { language? : string, autocorrect? : boolean, pII? : boolean, listId? : string, classify? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Screen>): void; /** * This operation will detect the language of given input content. Returns the * <a href="http://www-01.sil.org/iso639-3/codes.asp">ISO 639-3 code</a> for * the predominant language comprising the submitted text. Over 110 languages * supported. * * @param {string} textContentType The content type. Possible values include: * 'text/plain', 'text/html', 'text/xml', 'text/markdown' * * @param {object} textContent Content to screen. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DetectedLanguage>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ detectLanguageWithHttpOperationResponse(textContentType: string, textContent: stream.Readable, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DetectedLanguage>>; /** * This operation will detect the language of given input content. Returns the * <a href="http://www-01.sil.org/iso639-3/codes.asp">ISO 639-3 code</a> for * the predominant language comprising the submitted text. Over 110 languages * supported. * * @param {string} textContentType The content type. Possible values include: * 'text/plain', 'text/html', 'text/xml', 'text/markdown' * * @param {object} textContent Content to screen. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DetectedLanguage} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DetectedLanguage} [result] - The deserialized result object if an error did not occur. * See {@link DetectedLanguage} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ detectLanguage(textContentType: string, textContent: stream.Readable, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DetectedLanguage>; detectLanguage(textContentType: string, textContent: stream.Readable, callback: ServiceCallback<models.DetectedLanguage>): void; detectLanguage(textContentType: string, textContent: stream.Readable, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DetectedLanguage>): void; } /** * @class * ListManagementImageLists * __NOTE__: An instance of this class is automatically created for an * instance of the ContentModeratorClient. */ export interface ListManagementImageLists { /** * Returns the details of the image list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ImageList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getDetailsWithHttpOperationResponse(listId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ImageList>>; /** * Returns the details of the image list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ImageList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ImageList} [result] - The deserialized result object if an error did not occur. * See {@link ImageList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getDetails(listId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ImageList>; getDetails(listId: string, callback: ServiceCallback<models.ImageList>): void; getDetails(listId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ImageList>): void; /** * Deletes image list with the list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<String>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(listId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<string>>; /** * Deletes image list with the list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {String} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {String} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(listId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<string>; deleteMethod(listId: string, callback: ServiceCallback<string>): void; deleteMethod(listId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<string>): void; /** * Updates an image list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} contentType The content type. * * @param {object} body Schema of the body. * * @param {string} [body.name] Name of the list. * * @param {string} [body.description] Description of the list. * * @param {object} [body.metadata] Metadata of the list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ImageList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(listId: string, contentType: string, body: models.Body, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ImageList>>; /** * Updates an image list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} contentType The content type. * * @param {object} body Schema of the body. * * @param {string} [body.name] Name of the list. * * @param {string} [body.description] Description of the list. * * @param {object} [body.metadata] Metadata of the list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ImageList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ImageList} [result] - The deserialized result object if an error did not occur. * See {@link ImageList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(listId: string, contentType: string, body: models.Body, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ImageList>; update(listId: string, contentType: string, body: models.Body, callback: ServiceCallback<models.ImageList>): void; update(listId: string, contentType: string, body: models.Body, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ImageList>): void; /** * Creates an image list. * * @param {string} contentType The content type. * * @param {object} body Schema of the body. * * @param {string} [body.name] Name of the list. * * @param {string} [body.description] Description of the list. * * @param {object} [body.metadata] Metadata of the list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ImageList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(contentType: string, body: models.Body, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ImageList>>; /** * Creates an image list. * * @param {string} contentType The content type. * * @param {object} body Schema of the body. * * @param {string} [body.name] Name of the list. * * @param {string} [body.description] Description of the list. * * @param {object} [body.metadata] Metadata of the list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ImageList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ImageList} [result] - The deserialized result object if an error did not occur. * See {@link ImageList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ create(contentType: string, body: models.Body, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ImageList>; create(contentType: string, body: models.Body, callback: ServiceCallback<models.ImageList>): void; create(contentType: string, body: models.Body, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ImageList>): void; /** * Gets all the Image Lists. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Array>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getAllImageListsWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ImageList[]>>; /** * Gets all the Image Lists. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Array} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Array} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getAllImageLists(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ImageList[]>; getAllImageLists(callback: ServiceCallback<models.ImageList[]>): void; getAllImageLists(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ImageList[]>): void; /** * Refreshes the index of the list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RefreshIndex>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ refreshIndexMethodWithHttpOperationResponse(listId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RefreshIndex>>; /** * Refreshes the index of the list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RefreshIndex} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RefreshIndex} [result] - The deserialized result object if an error did not occur. * See {@link RefreshIndex} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ refreshIndexMethod(listId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RefreshIndex>; refreshIndexMethod(listId: string, callback: ServiceCallback<models.RefreshIndex>): void; refreshIndexMethod(listId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RefreshIndex>): void; } /** * @class * ListManagementTermLists * __NOTE__: An instance of this class is automatically created for an * instance of the ContentModeratorClient. */ export interface ListManagementTermLists { /** * Returns list Id details of the term list with list Id equal to list Id * passed. * * @param {string} listId List Id of the image list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<TermList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getDetailsWithHttpOperationResponse(listId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TermList>>; /** * Returns list Id details of the term list with list Id equal to list Id * passed. * * @param {string} listId List Id of the image list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {TermList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {TermList} [result] - The deserialized result object if an error did not occur. * See {@link TermList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getDetails(listId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TermList>; getDetails(listId: string, callback: ServiceCallback<models.TermList>): void; getDetails(listId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TermList>): void; /** * Deletes term list with the list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<String>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(listId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<string>>; /** * Deletes term list with the list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {String} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {String} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(listId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<string>; deleteMethod(listId: string, callback: ServiceCallback<string>): void; deleteMethod(listId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<string>): void; /** * Updates an Term List. * * @param {string} listId List Id of the image list. * * @param {string} contentType The content type. * * @param {object} body Schema of the body. * * @param {string} [body.name] Name of the list. * * @param {string} [body.description] Description of the list. * * @param {object} [body.metadata] Metadata of the list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<TermList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(listId: string, contentType: string, body: models.Body, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TermList>>; /** * Updates an Term List. * * @param {string} listId List Id of the image list. * * @param {string} contentType The content type. * * @param {object} body Schema of the body. * * @param {string} [body.name] Name of the list. * * @param {string} [body.description] Description of the list. * * @param {object} [body.metadata] Metadata of the list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {TermList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {TermList} [result] - The deserialized result object if an error did not occur. * See {@link TermList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(listId: string, contentType: string, body: models.Body, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TermList>; update(listId: string, contentType: string, body: models.Body, callback: ServiceCallback<models.TermList>): void; update(listId: string, contentType: string, body: models.Body, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TermList>): void; /** * Creates a Term List * * @param {string} contentType The content type. * * @param {object} body Schema of the body. * * @param {string} [body.name] Name of the list. * * @param {string} [body.description] Description of the list. * * @param {object} [body.metadata] Metadata of the list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<TermList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(contentType: string, body: models.Body, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TermList>>; /** * Creates a Term List * * @param {string} contentType The content type. * * @param {object} body Schema of the body. * * @param {string} [body.name] Name of the list. * * @param {string} [body.description] Description of the list. * * @param {object} [body.metadata] Metadata of the list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {TermList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {TermList} [result] - The deserialized result object if an error did not occur. * See {@link TermList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ create(contentType: string, body: models.Body, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TermList>; create(contentType: string, body: models.Body, callback: ServiceCallback<models.TermList>): void; create(contentType: string, body: models.Body, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TermList>): void; /** * gets all the Term Lists * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Array>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getAllTermListsWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TermList[]>>; /** * gets all the Term Lists * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Array} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Array} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getAllTermLists(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TermList[]>; getAllTermLists(callback: ServiceCallback<models.TermList[]>): void; getAllTermLists(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TermList[]>): void; /** * Refreshes the index of the list with list Id equal to list ID passed. * * @param {string} listId List Id of the image list. * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RefreshIndex>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ refreshIndexMethodWithHttpOperationResponse(listId: string, language: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RefreshIndex>>; /** * Refreshes the index of the list with list Id equal to list ID passed. * * @param {string} listId List Id of the image list. * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RefreshIndex} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RefreshIndex} [result] - The deserialized result object if an error did not occur. * See {@link RefreshIndex} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ refreshIndexMethod(listId: string, language: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RefreshIndex>; refreshIndexMethod(listId: string, language: string, callback: ServiceCallback<models.RefreshIndex>): void; refreshIndexMethod(listId: string, language: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RefreshIndex>): void; } /** * @class * ListManagementImage * __NOTE__: An instance of this class is automatically created for an * instance of the ContentModeratorClient. */ export interface ListManagementImage { /** * Add an image to the list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {object} [options] Optional Parameters. * * @param {number} [options.tag] Tag for the image. * * @param {string} [options.label] The image label. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Image>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ addImageWithHttpOperationResponse(listId: string, options?: { tag? : number, label? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Image>>; /** * Add an image to the list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {object} [options] Optional Parameters. * * @param {number} [options.tag] Tag for the image. * * @param {string} [options.label] The image label. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Image} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Image} [result] - The deserialized result object if an error did not occur. * See {@link Image} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ addImage(listId: string, options?: { tag? : number, label? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.Image>; addImage(listId: string, callback: ServiceCallback<models.Image>): void; addImage(listId: string, options: { tag? : number, label? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Image>): void; /** * Deletes all images from the list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<String>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteAllImagesWithHttpOperationResponse(listId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<string>>; /** * Deletes all images from the list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {String} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {String} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteAllImages(listId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<string>; deleteAllImages(listId: string, callback: ServiceCallback<string>): void; deleteAllImages(listId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<string>): void; /** * Gets all image Ids from the list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ImageIds>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getAllImageIdsWithHttpOperationResponse(listId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ImageIds>>; /** * Gets all image Ids from the list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ImageIds} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ImageIds} [result] - The deserialized result object if an error did not occur. * See {@link ImageIds} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getAllImageIds(listId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ImageIds>; getAllImageIds(listId: string, callback: ServiceCallback<models.ImageIds>): void; getAllImageIds(listId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ImageIds>): void; /** * Deletes an image from the list with list Id and image Id passed. * * @param {string} listId List Id of the image list. * * @param {string} imageId Id of the image. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<String>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteImageWithHttpOperationResponse(listId: string, imageId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<string>>; /** * Deletes an image from the list with list Id and image Id passed. * * @param {string} listId List Id of the image list. * * @param {string} imageId Id of the image. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {String} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {String} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteImage(listId: string, imageId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<string>; deleteImage(listId: string, imageId: string, callback: ServiceCallback<string>): void; deleteImage(listId: string, imageId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<string>): void; /** * Add an image to the list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} contentType The content type. * * @param {object} imageUrl The image url. * * @param {string} [imageUrl.dataRepresentation] * * @param {string} [imageUrl.value] * * @param {object} [options] Optional Parameters. * * @param {number} [options.tag] Tag for the image. * * @param {string} [options.label] The image label. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Image>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ addImageUrlInputWithHttpOperationResponse(listId: string, contentType: string, imageUrl: models.BodyModel, options?: { tag? : number, label? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Image>>; /** * Add an image to the list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} contentType The content type. * * @param {object} imageUrl The image url. * * @param {string} [imageUrl.dataRepresentation] * * @param {string} [imageUrl.value] * * @param {object} [options] Optional Parameters. * * @param {number} [options.tag] Tag for the image. * * @param {string} [options.label] The image label. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Image} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Image} [result] - The deserialized result object if an error did not occur. * See {@link Image} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ addImageUrlInput(listId: string, contentType: string, imageUrl: models.BodyModel, options?: { tag? : number, label? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.Image>; addImageUrlInput(listId: string, contentType: string, imageUrl: models.BodyModel, callback: ServiceCallback<models.Image>): void; addImageUrlInput(listId: string, contentType: string, imageUrl: models.BodyModel, options: { tag? : number, label? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Image>): void; /** * Add an image to the list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {object} imageStream The image file. * * @param {object} [options] Optional Parameters. * * @param {number} [options.tag] Tag for the image. * * @param {string} [options.label] The image label. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Image>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ addImageFileInputWithHttpOperationResponse(listId: string, imageStream: stream.Readable, options?: { tag? : number, label? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Image>>; /** * Add an image to the list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {object} imageStream The image file. * * @param {object} [options] Optional Parameters. * * @param {number} [options.tag] Tag for the image. * * @param {string} [options.label] The image label. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Image} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Image} [result] - The deserialized result object if an error did not occur. * See {@link Image} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ addImageFileInput(listId: string, imageStream: stream.Readable, options?: { tag? : number, label? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.Image>; addImageFileInput(listId: string, imageStream: stream.Readable, callback: ServiceCallback<models.Image>): void; addImageFileInput(listId: string, imageStream: stream.Readable, options: { tag? : number, label? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Image>): void; } /** * @class * ListManagementTerm * __NOTE__: An instance of this class is automatically created for an * instance of the ContentModeratorClient. */ export interface ListManagementTerm { /** * Add a term to the term list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} term Term to be deleted * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Object>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ addTermWithHttpOperationResponse(listId: string, term: string, language: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<any>>; /** * Add a term to the term list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} term Term to be deleted * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Object} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Object} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ addTerm(listId: string, term: string, language: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<any>; addTerm(listId: string, term: string, language: string, callback: ServiceCallback<any>): void; addTerm(listId: string, term: string, language: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<any>): void; /** * Deletes a term from the list with list Id equal to the list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} term Term to be deleted * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<String>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteTermWithHttpOperationResponse(listId: string, term: string, language: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<string>>; /** * Deletes a term from the list with list Id equal to the list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} term Term to be deleted * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {String} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {String} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteTerm(listId: string, term: string, language: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<string>; deleteTerm(listId: string, term: string, language: string, callback: ServiceCallback<string>): void; deleteTerm(listId: string, term: string, language: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<string>): void; /** * Gets all terms from the list with list Id equal to the list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {number} [options.offset] The pagination start index. * * @param {number} [options.limit] The max limit. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Terms>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getAllTermsWithHttpOperationResponse(listId: string, language: string, options?: { offset? : number, limit? : number, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Terms>>; /** * Gets all terms from the list with list Id equal to the list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {number} [options.offset] The pagination start index. * * @param {number} [options.limit] The max limit. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Terms} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Terms} [result] - The deserialized result object if an error did not occur. * See {@link Terms} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getAllTerms(listId: string, language: string, options?: { offset? : number, limit? : number, customHeaders? : { [headerName: string]: string; } }): Promise<models.Terms>; getAllTerms(listId: string, language: string, callback: ServiceCallback<models.Terms>): void; getAllTerms(listId: string, language: string, options: { offset? : number, limit? : number, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Terms>): void; /** * Deletes all terms from the list with list Id equal to the list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<String>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteAllTermsWithHttpOperationResponse(listId: string, language: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<string>>; /** * Deletes all terms from the list with list Id equal to the list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {String} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {String} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteAllTerms(listId: string, language: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<string>; deleteAllTerms(listId: string, language: string, callback: ServiceCallback<string>): void; deleteAllTerms(listId: string, language: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<string>): void; } /** * @class * Reviews * __NOTE__: An instance of this class is automatically created for an * instance of the ContentModeratorClient. */ export interface Reviews { /** * Returns review details for the review Id passed. * * @param {string} teamName Your Team Name. * * @param {string} reviewId Id of the review. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Review>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getReviewWithHttpOperationResponse(teamName: string, reviewId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Review>>; /** * Returns review details for the review Id passed. * * @param {string} teamName Your Team Name. * * @param {string} reviewId Id of the review. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Review} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Review} [result] - The deserialized result object if an error did not occur. * See {@link Review} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getReview(teamName: string, reviewId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Review>; getReview(teamName: string, reviewId: string, callback: ServiceCallback<models.Review>): void; getReview(teamName: string, reviewId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Review>): void; /** * Get the Job Details for a Job Id. * * @param {string} teamName Your Team Name. * * @param {string} jobId Id of the job. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Job>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getJobDetailsWithHttpOperationResponse(teamName: string, jobId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Job>>; /** * Get the Job Details for a Job Id. * * @param {string} teamName Your Team Name. * * @param {string} jobId Id of the job. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Job} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Job} [result] - The deserialized result object if an error did not occur. * See {@link Job} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getJobDetails(teamName: string, jobId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Job>; getJobDetails(teamName: string, jobId: string, callback: ServiceCallback<models.Job>): void; getJobDetails(teamName: string, jobId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Job>): void; /** * The reviews created would show up for Reviewers on your team. As Reviewers * complete reviewing, results of the Review would be POSTED (i.e. HTTP POST) * on the specified CallBackEndpoint. * * <h3>CallBack Schemas </h3> * <h4>Review Completion CallBack Sample</h4> * <p> * {<br/> * "ReviewId": "<Review Id>",<br/> * "ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/> * "ModifiedBy": "<Name of the Reviewer>",<br/> * "CallBackType": "Review",<br/> * "ContentId": "<The ContentId that was specified input>",<br/> * "Metadata": {<br/> * "adultscore": "0.xxx",<br/> * "a": "False",<br/> * "racyscore": "0.xxx",<br/> * "r": "True"<br/> * },<br/> * "ReviewerResultTags": {<br/> * "a": "False",<br/> * "r": "True"<br/> * }<br/> * }<br/> * * </p>. * * @param {string} urlContentType The content type. * * @param {string} teamName Your team name. * * @param {array} createReviewBody Body for create reviews API * * @param {object} [options] Optional Parameters. * * @param {string} [options.subTeam] SubTeam of your team, you want to assign * the created review to. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Array>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createReviewsWithHttpOperationResponse(urlContentType: string, teamName: string, createReviewBody: models.CreateReviewBodyItem[], options?: { subTeam? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<string[]>>; /** * The reviews created would show up for Reviewers on your team. As Reviewers * complete reviewing, results of the Review would be POSTED (i.e. HTTP POST) * on the specified CallBackEndpoint. * * <h3>CallBack Schemas </h3> * <h4>Review Completion CallBack Sample</h4> * <p> * {<br/> * "ReviewId": "<Review Id>",<br/> * "ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/> * "ModifiedBy": "<Name of the Reviewer>",<br/> * "CallBackType": "Review",<br/> * "ContentId": "<The ContentId that was specified input>",<br/> * "Metadata": {<br/> * "adultscore": "0.xxx",<br/> * "a": "False",<br/> * "racyscore": "0.xxx",<br/> * "r": "True"<br/> * },<br/> * "ReviewerResultTags": {<br/> * "a": "False",<br/> * "r": "True"<br/> * }<br/> * }<br/> * * </p>. * * @param {string} urlContentType The content type. * * @param {string} teamName Your team name. * * @param {array} createReviewBody Body for create reviews API * * @param {object} [options] Optional Parameters. * * @param {string} [options.subTeam] SubTeam of your team, you want to assign * the created review to. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Array} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Array} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createReviews(urlContentType: string, teamName: string, createReviewBody: models.CreateReviewBodyItem[], options?: { subTeam? : string, customHeaders? : { [headerName: string]: string; } }): Promise<string[]>; createReviews(urlContentType: string, teamName: string, createReviewBody: models.CreateReviewBodyItem[], callback: ServiceCallback<string[]>): void; createReviews(urlContentType: string, teamName: string, createReviewBody: models.CreateReviewBodyItem[], options: { subTeam? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<string[]>): void; /** * A job Id will be returned for the content posted on this endpoint. * * Once the content is evaluated against the Workflow provided the review will * be created or ignored based on the workflow expression. * * <h3>CallBack Schemas </h3> * * <p> * <h4>Job Completion CallBack Sample</h4><br/> * * {<br/> * "JobId": "<Job Id>,<br/> * "ReviewId": "<Review Id, if the Job resulted in a Review to be * created>",<br/> * "WorkFlowId": "default",<br/> * "Status": "<This will be one of Complete, InProgress, Error>",<br/> * "ContentType": "Image",<br/> * "ContentId": "<This is the ContentId that was specified on input>",<br/> * "CallBackType": "Job",<br/> * "Metadata": {<br/> * "adultscore": "0.xxx",<br/> * "a": "False",<br/> * "racyscore": "0.xxx",<br/> * "r": "True"<br/> * }<br/> * }<br/> * * </p> * <p> * <h4>Review Completion CallBack Sample</h4><br/> * * { * "ReviewId": "<Review Id>",<br/> * "ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/> * "ModifiedBy": "<Name of the Reviewer>",<br/> * "CallBackType": "Review",<br/> * "ContentId": "<The ContentId that was specified input>",<br/> * "Metadata": {<br/> * "adultscore": "0.xxx", * "a": "False",<br/> * "racyscore": "0.xxx",<br/> * "r": "True"<br/> * },<br/> * "ReviewerResultTags": {<br/> * "a": "False",<br/> * "r": "True"<br/> * }<br/> * }<br/> * * </p>. * * @param {string} teamName Your team name. * * @param {string} contentType Image, Text or Video. Possible values include: * 'Image', 'Text', 'Video' * * @param {string} contentId Id/Name to identify the content submitted. * * @param {string} workflowName Workflow Name that you want to invoke. * * @param {string} jobContentType The content type. Possible values include: * 'application/json', 'image/jpeg' * * @param {object} content Content to evaluate. * * @param {string} content.contentValue Content to evaluate for a job. * * @param {object} [options] Optional Parameters. * * @param {string} [options.callBackEndpoint] Callback endpoint for posting the * create job result. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<JobId>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createJobWithHttpOperationResponse(teamName: string, contentType: string, contentId: string, workflowName: string, jobContentType: string, content: models.Content, options?: { callBackEndpoint? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.JobId>>; /** * A job Id will be returned for the content posted on this endpoint. * * Once the content is evaluated against the Workflow provided the review will * be created or ignored based on the workflow expression. * * <h3>CallBack Schemas </h3> * * <p> * <h4>Job Completion CallBack Sample</h4><br/> * * {<br/> * "JobId": "<Job Id>,<br/> * "ReviewId": "<Review Id, if the Job resulted in a Review to be * created>",<br/> * "WorkFlowId": "default",<br/> * "Status": "<This will be one of Complete, InProgress, Error>",<br/> * "ContentType": "Image",<br/> * "ContentId": "<This is the ContentId that was specified on input>",<br/> * "CallBackType": "Job",<br/> * "Metadata": {<br/> * "adultscore": "0.xxx",<br/> * "a": "False",<br/> * "racyscore": "0.xxx",<br/> * "r": "True"<br/> * }<br/> * }<br/> * * </p> * <p> * <h4>Review Completion CallBack Sample</h4><br/> * * { * "ReviewId": "<Review Id>",<br/> * "ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/> * "ModifiedBy": "<Name of the Reviewer>",<br/> * "CallBackType": "Review",<br/> * "ContentId": "<The ContentId that was specified input>",<br/> * "Metadata": {<br/> * "adultscore": "0.xxx", * "a": "False",<br/> * "racyscore": "0.xxx",<br/> * "r": "True"<br/> * },<br/> * "ReviewerResultTags": {<br/> * "a": "False",<br/> * "r": "True"<br/> * }<br/> * }<br/> * * </p>. * * @param {string} teamName Your team name. * * @param {string} contentType Image, Text or Video. Possible values include: * 'Image', 'Text', 'Video' * * @param {string} contentId Id/Name to identify the content submitted. * * @param {string} workflowName Workflow Name that you want to invoke. * * @param {string} jobContentType The content type. Possible values include: * 'application/json', 'image/jpeg' * * @param {object} content Content to evaluate. * * @param {string} content.contentValue Content to evaluate for a job. * * @param {object} [options] Optional Parameters. * * @param {string} [options.callBackEndpoint] Callback endpoint for posting the * create job result. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {JobId} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {JobId} [result] - The deserialized result object if an error did not occur. * See {@link JobId} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createJob(teamName: string, contentType: string, contentId: string, workflowName: string, jobContentType: string, content: models.Content, options?: { callBackEndpoint? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.JobId>; createJob(teamName: string, contentType: string, contentId: string, workflowName: string, jobContentType: string, content: models.Content, callback: ServiceCallback<models.JobId>): void; createJob(teamName: string, contentType: string, contentId: string, workflowName: string, jobContentType: string, content: models.Content, options: { callBackEndpoint? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.JobId>): void; /** * The reviews created would show up for Reviewers on your team. As Reviewers * complete reviewing, results of the Review would be POSTED (i.e. HTTP POST) * on the specified CallBackEndpoint. * * <h3>CallBack Schemas </h3> * <h4>Review Completion CallBack Sample</h4> * <p> * {<br/> * "ReviewId": "<Review Id>",<br/> * "ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/> * "ModifiedBy": "<Name of the Reviewer>",<br/> * "CallBackType": "Review",<br/> * "ContentId": "<The ContentId that was specified input>",<br/> * "Metadata": {<br/> * "adultscore": "0.xxx",<br/> * "a": "False",<br/> * "racyscore": "0.xxx",<br/> * "r": "True"<br/> * },<br/> * "ReviewerResultTags": {<br/> * "a": "False",<br/> * "r": "True"<br/> * }<br/> * }<br/> * * </p>. * * @param {string} teamName Your team name. * * @param {string} reviewId Id of the review. * * @param {object} [options] Optional Parameters. * * @param {number} [options.timescale] Timescale of the video you are adding * frames to. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ addVideoFrameWithHttpOperationResponse(teamName: string, reviewId: string, options?: { timescale? : number, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * The reviews created would show up for Reviewers on your team. As Reviewers * complete reviewing, results of the Review would be POSTED (i.e. HTTP POST) * on the specified CallBackEndpoint. * * <h3>CallBack Schemas </h3> * <h4>Review Completion CallBack Sample</h4> * <p> * {<br/> * "ReviewId": "<Review Id>",<br/> * "ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/> * "ModifiedBy": "<Name of the Reviewer>",<br/> * "CallBackType": "Review",<br/> * "ContentId": "<The ContentId that was specified input>",<br/> * "Metadata": {<br/> * "adultscore": "0.xxx",<br/> * "a": "False",<br/> * "racyscore": "0.xxx",<br/> * "r": "True"<br/> * },<br/> * "ReviewerResultTags": {<br/> * "a": "False",<br/> * "r": "True"<br/> * }<br/> * }<br/> * * </p>. * * @param {string} teamName Your team name. * * @param {string} reviewId Id of the review. * * @param {object} [options] Optional Parameters. * * @param {number} [options.timescale] Timescale of the video you are adding * frames to. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ addVideoFrame(teamName: string, reviewId: string, options?: { timescale? : number, customHeaders? : { [headerName: string]: string; } }): Promise<void>; addVideoFrame(teamName: string, reviewId: string, callback: ServiceCallback<void>): void; addVideoFrame(teamName: string, reviewId: string, options: { timescale? : number, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * The reviews created would show up for Reviewers on your team. As Reviewers * complete reviewing, results of the Review would be POSTED (i.e. HTTP POST) * on the specified CallBackEndpoint. * * <h3>CallBack Schemas </h3> * <h4>Review Completion CallBack Sample</h4> * <p> * {<br/> * "ReviewId": "<Review Id>",<br/> * "ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/> * "ModifiedBy": "<Name of the Reviewer>",<br/> * "CallBackType": "Review",<br/> * "ContentId": "<The ContentId that was specified input>",<br/> * "Metadata": {<br/> * "adultscore": "0.xxx",<br/> * "a": "False",<br/> * "racyscore": "0.xxx",<br/> * "r": "True"<br/> * },<br/> * "ReviewerResultTags": {<br/> * "a": "False",<br/> * "r": "True"<br/> * }<br/> * }<br/> * * </p>. * * @param {string} teamName Your team name. * * @param {string} reviewId Id of the review. * * @param {object} [options] Optional Parameters. * * @param {number} [options.startSeed] Time stamp of the frame from where you * want to start fetching the frames. * * @param {number} [options.noOfRecords] Number of frames to fetch. * * @param {string} [options.filter] Get frames filtered by tags. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Frames>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getVideoFramesWithHttpOperationResponse(teamName: string, reviewId: string, options?: { startSeed? : number, noOfRecords? : number, filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Frames>>; /** * The reviews created would show up for Reviewers on your team. As Reviewers * complete reviewing, results of the Review would be POSTED (i.e. HTTP POST) * on the specified CallBackEndpoint. * * <h3>CallBack Schemas </h3> * <h4>Review Completion CallBack Sample</h4> * <p> * {<br/> * "ReviewId": "<Review Id>",<br/> * "ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/> * "ModifiedBy": "<Name of the Reviewer>",<br/> * "CallBackType": "Review",<br/> * "ContentId": "<The ContentId that was specified input>",<br/> * "Metadata": {<br/> * "adultscore": "0.xxx",<br/> * "a": "False",<br/> * "racyscore": "0.xxx",<br/> * "r": "True"<br/> * },<br/> * "ReviewerResultTags": {<br/> * "a": "False",<br/> * "r": "True"<br/> * }<br/> * }<br/> * * </p>. * * @param {string} teamName Your team name. * * @param {string} reviewId Id of the review. * * @param {object} [options] Optional Parameters. * * @param {number} [options.startSeed] Time stamp of the frame from where you * want to start fetching the frames. * * @param {number} [options.noOfRecords] Number of frames to fetch. * * @param {string} [options.filter] Get frames filtered by tags. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Frames} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Frames} [result] - The deserialized result object if an error did not occur. * See {@link Frames} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getVideoFrames(teamName: string, reviewId: string, options?: { startSeed? : number, noOfRecords? : number, filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.Frames>; getVideoFrames(teamName: string, reviewId: string, callback: ServiceCallback<models.Frames>): void; getVideoFrames(teamName: string, reviewId: string, options: { startSeed? : number, noOfRecords? : number, filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Frames>): void; /** * Publish video review to make it available for review. * * @param {string} teamName Your team name. * * @param {string} reviewId Id of the review. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ publishVideoReviewWithHttpOperationResponse(teamName: string, reviewId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Publish video review to make it available for review. * * @param {string} teamName Your team name. * * @param {string} reviewId Id of the review. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ publishVideoReview(teamName: string, reviewId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; publishVideoReview(teamName: string, reviewId: string, callback: ServiceCallback<void>): void; publishVideoReview(teamName: string, reviewId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * This API adds a transcript screen text result file for a video review. * Transcript screen text result file is a result of Screen Text API . In order * to generate transcript screen text result file , a transcript file has to be * screened for profanity using Screen Text API. * * @param {string} contentType The content type. * * @param {string} teamName Your team name. * * @param {string} reviewId Id of the review. * * @param {array} transcriptModerationBody Body for add video transcript * moderation result API * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ addVideoTranscriptModerationResultWithHttpOperationResponse(contentType: string, teamName: string, reviewId: string, transcriptModerationBody: models.TranscriptModerationBodyItem[], options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * This API adds a transcript screen text result file for a video review. * Transcript screen text result file is a result of Screen Text API . In order * to generate transcript screen text result file , a transcript file has to be * screened for profanity using Screen Text API. * * @param {string} contentType The content type. * * @param {string} teamName Your team name. * * @param {string} reviewId Id of the review. * * @param {array} transcriptModerationBody Body for add video transcript * moderation result API * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ addVideoTranscriptModerationResult(contentType: string, teamName: string, reviewId: string, transcriptModerationBody: models.TranscriptModerationBodyItem[], options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; addVideoTranscriptModerationResult(contentType: string, teamName: string, reviewId: string, transcriptModerationBody: models.TranscriptModerationBodyItem[], callback: ServiceCallback<void>): void; addVideoTranscriptModerationResult(contentType: string, teamName: string, reviewId: string, transcriptModerationBody: models.TranscriptModerationBodyItem[], options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * This API adds a transcript file (text version of all the words spoken in a * video) to a video review. The file should be a valid WebVTT format. * * @param {string} teamName Your team name. * * @param {string} reviewId Id of the review. * * @param {object} vTTfile Transcript file of the video. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ addVideoTranscriptWithHttpOperationResponse(teamName: string, reviewId: string, vTTfile: stream.Readable, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * This API adds a transcript file (text version of all the words spoken in a * video) to a video review. The file should be a valid WebVTT format. * * @param {string} teamName Your team name. * * @param {string} reviewId Id of the review. * * @param {object} vTTfile Transcript file of the video. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ addVideoTranscript(teamName: string, reviewId: string, vTTfile: stream.Readable, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; addVideoTranscript(teamName: string, reviewId: string, vTTfile: stream.Readable, callback: ServiceCallback<void>): void; addVideoTranscript(teamName: string, reviewId: string, vTTfile: stream.Readable, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * The reviews created would show up for Reviewers on your team. As Reviewers * complete reviewing, results of the Review would be POSTED (i.e. HTTP POST) * on the specified CallBackEndpoint. * * <h3>CallBack Schemas </h3> * <h4>Review Completion CallBack Sample</h4> * <p> * {<br/> * "ReviewId": "<Review Id>",<br/> * "ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/> * "ModifiedBy": "<Name of the Reviewer>",<br/> * "CallBackType": "Review",<br/> * "ContentId": "<The ContentId that was specified input>",<br/> * "Metadata": {<br/> * "adultscore": "0.xxx",<br/> * "a": "False",<br/> * "racyscore": "0.xxx",<br/> * "r": "True"<br/> * },<br/> * "ReviewerResultTags": {<br/> * "a": "False",<br/> * "r": "True"<br/> * }<br/> * }<br/> * * </p>. * * @param {string} contentType The content type. * * @param {string} teamName Your team name. * * @param {array} createVideoReviewsBody Body for create reviews API * * @param {object} [options] Optional Parameters. * * @param {string} [options.subTeam] SubTeam of your team, you want to assign * the created review to. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Array>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createVideoReviewsWithHttpOperationResponse(contentType: string, teamName: string, createVideoReviewsBody: models.CreateVideoReviewsBodyItem[], options?: { subTeam? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<string[]>>; /** * The reviews created would show up for Reviewers on your team. As Reviewers * complete reviewing, results of the Review would be POSTED (i.e. HTTP POST) * on the specified CallBackEndpoint. * * <h3>CallBack Schemas </h3> * <h4>Review Completion CallBack Sample</h4> * <p> * {<br/> * "ReviewId": "<Review Id>",<br/> * "ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/> * "ModifiedBy": "<Name of the Reviewer>",<br/> * "CallBackType": "Review",<br/> * "ContentId": "<The ContentId that was specified input>",<br/> * "Metadata": {<br/> * "adultscore": "0.xxx",<br/> * "a": "False",<br/> * "racyscore": "0.xxx",<br/> * "r": "True"<br/> * },<br/> * "ReviewerResultTags": {<br/> * "a": "False",<br/> * "r": "True"<br/> * }<br/> * }<br/> * * </p>. * * @param {string} contentType The content type. * * @param {string} teamName Your team name. * * @param {array} createVideoReviewsBody Body for create reviews API * * @param {object} [options] Optional Parameters. * * @param {string} [options.subTeam] SubTeam of your team, you want to assign * the created review to. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Array} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Array} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createVideoReviews(contentType: string, teamName: string, createVideoReviewsBody: models.CreateVideoReviewsBodyItem[], options?: { subTeam? : string, customHeaders? : { [headerName: string]: string; } }): Promise<string[]>; createVideoReviews(contentType: string, teamName: string, createVideoReviewsBody: models.CreateVideoReviewsBodyItem[], callback: ServiceCallback<string[]>): void; createVideoReviews(contentType: string, teamName: string, createVideoReviewsBody: models.CreateVideoReviewsBodyItem[], options: { subTeam? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<string[]>): void; /** * Use this method to add frames for a video review.Timescale: This parameter * is a factor which is used to convert the timestamp on a frame into * milliseconds. Timescale is provided in the output of the Content Moderator * video media processor on the Azure Media Services platform.Timescale in the * Video Moderation output is Ticks/Second. * * @param {string} contentType The content type. * * @param {string} teamName Your team name. * * @param {string} reviewId Id of the review. * * @param {array} videoFrameBody Body for add video frames API * * @param {object} [options] Optional Parameters. * * @param {number} [options.timescale] Timescale of the video. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ addVideoFrameUrlWithHttpOperationResponse(contentType: string, teamName: string, reviewId: string, videoFrameBody: models.VideoFrameBodyItem[], options?: { timescale? : number, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Use this method to add frames for a video review.Timescale: This parameter * is a factor which is used to convert the timestamp on a frame into * milliseconds. Timescale is provided in the output of the Content Moderator * video media processor on the Azure Media Services platform.Timescale in the * Video Moderation output is Ticks/Second. * * @param {string} contentType The content type. * * @param {string} teamName Your team name. * * @param {string} reviewId Id of the review. * * @param {array} videoFrameBody Body for add video frames API * * @param {object} [options] Optional Parameters. * * @param {number} [options.timescale] Timescale of the video. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ addVideoFrameUrl(contentType: string, teamName: string, reviewId: string, videoFrameBody: models.VideoFrameBodyItem[], options?: { timescale? : number, customHeaders? : { [headerName: string]: string; } }): Promise<void>; addVideoFrameUrl(contentType: string, teamName: string, reviewId: string, videoFrameBody: models.VideoFrameBodyItem[], callback: ServiceCallback<void>): void; addVideoFrameUrl(contentType: string, teamName: string, reviewId: string, videoFrameBody: models.VideoFrameBodyItem[], options: { timescale? : number, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Use this method to add frames for a video review.Timescale: This parameter * is a factor which is used to convert the timestamp on a frame into * milliseconds. Timescale is provided in the output of the Content Moderator * video media processor on the Azure Media Services platform.Timescale in the * Video Moderation output is Ticks/Second. * * @param {string} contentType The content type. * * @param {string} teamName Your team name. * * @param {string} reviewId Id of the review. * * @param {object} frameImageZip Zip file containing frame images. * * @param {string} frameMetadata Metadata of the frame. * * @param {object} [options] Optional Parameters. * * @param {number} [options.timescale] Timescale of the video . * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ addVideoFrameStreamWithHttpOperationResponse(contentType: string, teamName: string, reviewId: string, frameImageZip: stream.Readable, frameMetadata: string, options?: { timescale? : number, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Use this method to add frames for a video review.Timescale: This parameter * is a factor which is used to convert the timestamp on a frame into * milliseconds. Timescale is provided in the output of the Content Moderator * video media processor on the Azure Media Services platform.Timescale in the * Video Moderation output is Ticks/Second. * * @param {string} contentType The content type. * * @param {string} teamName Your team name. * * @param {string} reviewId Id of the review. * * @param {object} frameImageZip Zip file containing frame images. * * @param {string} frameMetadata Metadata of the frame. * * @param {object} [options] Optional Parameters. * * @param {number} [options.timescale] Timescale of the video . * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ addVideoFrameStream(contentType: string, teamName: string, reviewId: string, frameImageZip: stream.Readable, frameMetadata: string, options?: { timescale? : number, customHeaders? : { [headerName: string]: string; } }): Promise<void>; addVideoFrameStream(contentType: string, teamName: string, reviewId: string, frameImageZip: stream.Readable, frameMetadata: string, callback: ServiceCallback<void>): void; addVideoFrameStream(contentType: string, teamName: string, reviewId: string, frameImageZip: stream.Readable, frameMetadata: string, options: { timescale? : number, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; }
the_stack
import Taro, { Component, Config } from '@tarojs/taro' import { View, RichText, ScrollView } from '@tarojs/components' import { AtDrawer, AtActionSheet, AtIcon } from 'taro-ui' import request from '../../utils/request' import * as api from '../../configs/api' import './index.scss' interface Page { id: string; start: number; end: number; desc: string; } interface Chapter { uuid: string; name: string; url: string; } export default class ReadPage extends Component { config: Config = { } state = { novelId: '', bookName: '', title: '', content: '', prevUrl: '', nextUrl: '', scrollTop: 0, // 点击"下一章"时,文章滚动条能回到页面顶部 all: [], // 所有列表信息 page: [], // 大分页 1-100、101-200、201-300 list: [], // 小分页展示的数据 isShowPage: false, // 是否显示大分页 chapterVisible: false, // 左侧章节抽屉是否可见 menuVisible: false, // 菜单抽屉是否可见。'目录' | '设置' | '白天/黑夜' isDark: false, // 白天还是黑夜 settingVisible: false, // 设置抽屉是否可见。字体大小、背景颜色、亮度 bgColor: '#fff', font: 15, } componentWillMount() { const { bookName = '', chapterUrl = '', novelId } = this.$router.params const novelUrl = chapterUrl.split('/').slice(0, 4).join('/') // 用于查询目录 this.handleGetChapterList(novelUrl) this.setState({ bookName, novelId }, () => { this.handleGetNovelContent(chapterUrl) }) } /** * 查询目录 */ async handleGetChapterList(url) { const result = await request({ url: api.NOVEL_CHAPTER_GET, data: { url }, }) // 拼接分页数据 288 => 2、88,,,,2880 => 28、80 const integer = Math.floor(result.data.length / 100) // 整数部分 const remainder = result.data.length % 100 // 小数部分 const page: Array<Page> = [] /** * start、end 下标从 0 开始 * page 0-99、100-199、200-299 */ for (let i = 0; i <= integer; i++) { const obj = Object.create(null) obj.id = String(i) obj.start = i * 100 if (integer === 0) { // 只有一页,0 - 88 obj.end = remainder - 1 } else if (i === integer) { // 最后一页 obj.end = i * 100 + remainder - 1 } else { obj.end = (i + 1) * 100 - 1 } obj.desc = `${obj.start + 1} - ${obj.end + 1}` page.push(obj) } this.setState({ all: result.data, page, list: result.data.slice(0, 100), }) } /** * 查询小说内容 */ async handleGetNovelContent(url) { const { novelId } = this.state const result = await request({ url: api.NOVEL_CONTENT_GET, data: { url, shelfId: novelId }, }) const { title, content, prevUrl, nextUrl } = result.data this.setState({ title, content, prevUrl, nextUrl, settingVisible: false, menuVisible: false, chapterVisible: false, scrollTop: Math.random(), // scrollTop 值不变时滚动条位置不会变 }) } /** * 更改状态 */ handleUpdateState(variable: any, value?: any) { if (typeof variable === 'string') { this.setState({ [variable]: value }) } else { this.setState(variable) } } /** * 返回书架页面 */ handleBack() { Taro.navigateBack() } /** * 显示目录 * 根据当前阅读章节显示对应的目录 */ handleShowChapter () { const { title, all = [], page = [] } = this.state try { const index = all.findIndex((item:Chapter) => item.name.indexOf(title.trim()) !== -1) || 0 const currentPage = page.find((item:Page) => item.start <= index && item.end >= index) const list = all.slice(currentPage.start, currentPage.end + 1) this.setState({ menuVisible: false, chapterVisible: true, list, }) } catch (e) { Taro.showToast({ title: '页面打小差了,再试一下吧~', icon: 'none', }) this.setState({ menuVisible: false, }) } } /** * 渲染设置抽屉 */ renderMenu() { const { isDark, menuVisible } = this.state return ( <AtActionSheet isOpened={menuVisible} onClose={() => this.handleUpdateState({ menuVisible: false })}> <View className='at-row read_menu'> <View className='at-col' onClick={() => this.handleShowChapter()}> <View className='at-icon at-icon-bullet-list'></View> <View>目录</View> </View> <View className='at-col' onClick={() => this.handleUpdateState({ menuVisible: false, settingVisible: true })}> <View className='at-icon at-icon-settings'></View> <View>设置</View> </View> { isDark ? ( <View className='at-col' onClick={() => this.handleUpdateState({ isDark: !isDark, bgColor: '#fff' })}> <View className='at-icon at-icon-loading-2'></View> <View>白天</View> </View> ) : ( <View className='at-col' onClick={() => this.handleUpdateState({ isDark: !isDark, bgColor: 'rgb(0, 0, 0)' })}> <View className='at-icon at-icon-star'></View> <View>黑夜</View> </View> ) } </View> </AtActionSheet> ) } /** * 章节 > 点击章节 */ handleClickChapter(url) { this.setState({ chapterVisible: false }) this.handleGetNovelContent(url) } /** * 章节 > 章节排序 */ handleOrderChapter() { const list = this.state.list list.reverse() this.setState({ list, scrollTop: Math.random() }) } /** * 渲染章节抽屉 */ renderChapter() { const { chapterVisible, bookName, title, all = [], list = [], page = [], isShowPage, scrollTop } = this.state return ( <AtDrawer show={chapterVisible} onClose={() => this.handleUpdateState({ chapterVisible: false })} mask > <View className="read_chapter"> <View className="read_chapter-header"> {bookName}(共 {all.length} 章) </View> <View className="at-row read_chapter-menus"> <View className="at-col read_align-center">目录</View> <View className="at-col read_align-center" onClick={() => this.handleUpdateState({ isShowPage: !isShowPage })}>切换翻页</View> { !isShowPage && <View className="at-col read_align-center" onClick={() => this.handleOrderChapter()}>排序</View> } </View> <ScrollView scrollY={true} className="read_chapter-list" scrollTop={scrollTop}> { isShowPage ? ( page.map((item: Page) => ( <View className="read_chapter-item" key={item.id} onClick={() => this.handleUpdateState({ isShowPage: !isShowPage, list: all.slice(item.start, item.end + 1) })} >{item.desc}</View> )) ) : ( list.map((item: Chapter) => ( <View className={`read_chapter-item ${item.name === title.trim() ? 'read_chapter-active' : ''}`} key={item.uuid} onClick={() => this.handleClickChapter(item.url)}>{item.name}</View> )) ) } </ScrollView> </View> </AtDrawer> ) } /** * 渲染设置 */ renderSetting() { const { settingVisible, font } = this.state const bgs = [ '#fff', 'rgb(158, 151, 167)', 'rgb(177, 160, 132)', 'rgb(165, 168, 185)', 'rgb(187, 157, 171)', ] return ( <AtActionSheet isOpened={settingVisible} onClose={() => this.handleUpdateState({ settingVisible: false })}> <View className="read_setting"> <View className="read_font"> <View className="read_label">字体</View> <AtIcon value="reload" color="rgb(107, 115, 117)" size={30} onClick={() => this.handleUpdateState({ font: 14 })}></AtIcon> <AtIcon value="subtract-circle" color="rgb(107, 115, 117)" size={30} onClick={() => this.handleUpdateState({ font: font - 2 })}></AtIcon> <AtIcon value="add-circle" color="rgb(107, 115, 117)" size={30} onClick={() => this.handleUpdateState({ font: font + 2 })}></AtIcon> </View> <ScrollView scrollX={true} className="read_bg"> { bgs.map(bg => ( <View key={bg} style={{ backgroundColor: bg }} className="read_bg-box" onClick={() => this.handleUpdateState({ bgColor: bg })}></View> )) } </ScrollView> </View> </AtActionSheet> ) } /** * 主页面:上一页 | 下一页 */ handleTurnPage(url, info) { if (url.indexOf('.html') === -1) { if (info === 'prev') { Taro.showToast({ title: '已经是第一章了', icon: 'none', }) } else if (info === 'next') { Taro.showToast({ title: '已经是最新章节了', icon: 'none', }) } return } this.handleGetNovelContent(url) } render() { const { content, title, prevUrl, nextUrl, bgColor, font, isDark, scrollTop = 0 } = this.state return ( <View className="read_container" style={{ backgroundColor: bgColor }}> <View className="navbar" style={{ backgroundColor: bgColor, color: isDark ? '#666' : '#333' }}> <AtIcon value="chevron-left" onClick={() => this.handleBack()}></AtIcon> <View className="at-article__p read_title">{title}</View> </View> <ScrollView className="read_content" scrollTop={scrollTop} scrollY> <RichText style={{ fontSize: font + 'px', lineHeight: font * 1.5 + 'px' }} className="at-article__p" nodes={content} onClick={() => this.handleUpdateState({ menuVisible: true })}></RichText> </ScrollView> <View className="at-row read_footer"> <View className='at-col at-col-3 at-col__offset-6' onClick={() => this.handleTurnPage(prevUrl, 'prev')}> 上一章 </View> <View className='at-col at-col-3' onClick={() => this.handleTurnPage(nextUrl, 'next')}> 下一章 </View> </View> {this.renderMenu()} {this.renderChapter()} {this.renderSetting()} </View> ) } }
the_stack
import { Euler, EulerOrder } from "./Euler"; import { Matrix4 } from "./Matrix4"; import { Quaternion } from "./Quaternion"; import { makeQuaternionFromRotationMatrix4 } from "./Quaternion.Functions"; import { Vector2 } from "./Vector2"; import { Vector3 } from "./Vector3"; export function makeMatrix4Concatenation(a: Matrix4, b: Matrix4, result = new Matrix4()): Matrix4 { const ae = a.elements; const be = b.elements; const te = result.elements; const a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12]; const a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13]; const a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14]; const a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15]; const b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12]; const b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13]; const b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14]; const b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15]; // TODO: Replace with set(...) te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; return result; } export function matrix4Determinant(m: Matrix4): number { // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm const me = m.elements, n11 = me[0], n21 = me[1], n31 = me[2], n41 = me[3], n12 = me[4], n22 = me[5], n32 = me[6], n42 = me[7], n13 = me[8], n23 = me[9], n33 = me[10], n43 = me[11], n14 = me[12], n24 = me[13], n34 = me[14], n44 = me[15], t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; return n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; } export function makeMatrix4Transpose(m: Matrix4, result = new Matrix4()): Matrix4 { const re = result.copy(m).elements; let tmp; // TODO: replace this with just reading from me and setting re, no need for a temporary tmp = re[1]; re[1] = re[4]; re[4] = tmp; tmp = re[2]; re[2] = re[8]; re[8] = tmp; tmp = re[6]; re[6] = re[9]; re[9] = tmp; tmp = re[3]; re[3] = re[12]; re[12] = tmp; tmp = re[7]; re[7] = re[13]; re[13] = tmp; tmp = re[11]; re[11] = re[14]; re[14] = tmp; return result; } export function makeMatrix4Inverse(m: Matrix4, result = new Matrix4()): Matrix4 { // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm const me = m.elements, n11 = me[0], n21 = me[1], n31 = me[2], n41 = me[3], n12 = me[4], n22 = me[5], n32 = me[6], n42 = me[7], n13 = me[8], n23 = me[9], n33 = me[10], n43 = me[11], n14 = me[12], n24 = me[13], n34 = me[14], n44 = me[15], t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; if (det === 0) { throw new Error("can not invert degenerate matrix"); } const detInv = 1 / det; // TODO: replace with a set const re = result.elements; re[0] = t11 * detInv; re[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv; re[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv; re[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv; re[4] = t12 * detInv; re[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv; re[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv; re[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv; re[8] = t13 * detInv; re[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv; re[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv; re[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv; re[12] = t14 * detInv; re[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv; re[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv; re[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv; return result; } export function makeMatrix4Translation(t: Vector3, result = new Matrix4()): Matrix4 { return result.set(1, 0, 0, t.x, 0, 1, 0, t.y, 0, 0, 1, t.z, 0, 0, 0, 1); } export function makeMatrix4RotationFromAngleAxis(axis: Vector3, angle: number, result = new Matrix4()): Matrix4 { // Based on http://www.gamedev.net/reference/articles/article1199.asp const c = Math.cos(angle); const s = Math.sin(angle); const t = 1 - c; const x = axis.x, y = axis.y, z = axis.z; const tx = t * x, ty = t * y; return result.set( tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1, ); } export function makeMatrix4LookAt(eye: Vector3, target: Vector3, up: Vector3, result = new Matrix4()): Matrix4 { const te = result.elements; const look = eye.clone().sub(target); const lookLength = look.length(); if (lookLength === 0) { look.z = 1.0; } else { look.multiplyByScalar(1.0 / lookLength); } const right = up.clone().cross(look); const rightLength = right.length(); if (rightLength === 0) { // up and z are parallel if (Math.abs(up.z) === 1) { up.x += 0.0001; } else { up.z += 0.0001; } up.normalize(); right.cross(up); } else { right.multiplyByScalar(1.0 / rightLength); } const up2 = look.clone().cross(right); te[0] = right.x; te[4] = up2.x; te[8] = look.x; te[1] = right.y; te[5] = up2.y; te[9] = look.y; te[2] = right.z; te[6] = up2.z; te[10] = look.z; return result; } export function makeMatrix4RotationFromEuler(euler: Euler, result = new Matrix4()): Matrix4 { const te = result.elements; const x = euler.x, y = euler.y, z = euler.z; const a = Math.cos(x), b = Math.sin(x); const c = Math.cos(y), d = Math.sin(y); const e = Math.cos(z), f = Math.sin(z); // TODO: Replace smart code that compacts all of these orders into one if (euler.order === EulerOrder.XYZ) { const ae = a * e, af = a * f, be = b * e, bf = b * f; te[0] = c * e; te[4] = -c * f; te[8] = d; te[1] = af + be * d; te[5] = ae - bf * d; te[9] = -b * c; te[2] = bf - ae * d; te[6] = be + af * d; te[10] = a * c; } else if (euler.order === EulerOrder.YXZ) { const ce = c * e, cf = c * f, de = d * e, df = d * f; te[0] = ce + df * b; te[4] = de * b - cf; te[8] = a * d; te[1] = a * f; te[5] = a * e; te[9] = -b; te[2] = cf * b - de; te[6] = df + ce * b; te[10] = a * c; } else if (euler.order === EulerOrder.ZXY) { const ce = c * e, cf = c * f, de = d * e, df = d * f; te[0] = ce - df * b; te[4] = -a * f; te[8] = de + cf * b; te[1] = cf + de * b; te[5] = a * e; te[9] = df - ce * b; te[2] = -a * d; te[6] = b; te[10] = a * c; } else if (euler.order === EulerOrder.ZYX) { const ae = a * e, af = a * f, be = b * e, bf = b * f; te[0] = c * e; te[4] = be * d - af; te[8] = ae * d + bf; te[1] = c * f; te[5] = bf * d + ae; te[9] = af * d - be; te[2] = -d; te[6] = b * c; te[10] = a * c; } else if (euler.order === EulerOrder.YZX) { const ac = a * c, ad = a * d, bc = b * c, bd = b * d; te[0] = c * e; te[4] = bd - ac * f; te[8] = bc * f + ad; te[1] = f; te[5] = a * e; te[9] = -b * e; te[2] = -d * e; te[6] = ad * f + bc; te[10] = ac - bd * f; } else if (euler.order === EulerOrder.XZY) { const ac = a * c, ad = a * d, bc = b * c, bd = b * d; te[0] = c * e; te[4] = -f; te[8] = d * e; te[1] = ac * f + bd; te[5] = a * e; te[9] = ad * f - bc; te[2] = bc * f - ad; te[6] = b * e; te[10] = bd * f + ac; } // bottom row te[3] = 0; te[7] = 0; te[11] = 0; // last column te[12] = 0; te[13] = 0; te[14] = 0; te[15] = 1; return result; } export function makeMatrix4RotationFromQuaternion(q: Quaternion, result = new Matrix4()): Matrix4 { return composeMatrix4(new Vector3(), q, new Vector3(1, 1, 1), result); } export function makeMatrix4Scale(s: Vector3, result = new Matrix4()): Matrix4 { return result.set(s.x, 0, 0, 0, 0, s.y, 0, 0, 0, 0, s.z, 0, 0, 0, 0, 1); } export function makeMatrix4Shear(x: number, y: number, z: number, result = new Matrix4()): Matrix4 { return result.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1); } export function getMaxScaleOnAxis(m: Matrix4): number { const te = m.elements; const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2]; const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6]; const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10]; return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq)); } export function composeMatrix4( position: Vector3, rotation: Quaternion, scale: Vector3, result = new Matrix4(), ): Matrix4 { const x = rotation.x, y = rotation.y, z = rotation.z, w = rotation.w; const x2 = x + x, y2 = y + y, z2 = z + z; const xx = x * x2, xy = x * y2, xz = x * z2; const yy = y * y2, yz = y * z2, zz = z * z2; const wx = w * x2, wy = w * y2, wz = w * z2; const sx = scale.x, sy = scale.y, sz = scale.z; return result.set( // TODO: Replace with set (1 - (yy + zz)) * sx, (xy - wz) * sy, (xz + wy) * sz, position.x, (xy + wz) * sx, (1 - (xx + zz)) * sy, (yz - wx) * sz, position.y, (xz - wy) * sx, (yz + wx) * sy, (1 - (xx + yy)) * sz, position.z, 0, 0, 0, 1, ); } export function decomposeMatrix4(m: Matrix4, position: Vector3, rotation: Quaternion, scale: Vector3): Matrix4 { const te = m.elements; let sx = new Vector3(te[0], te[1], te[2]).length(); const sy = new Vector3(te[4], te[5], te[6]).length(); const sz = new Vector3(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale if (matrix4Determinant(m) < 0) { sx = -sx; } position.x = te[12]; position.y = te[13]; position.z = te[14]; // scale the rotation part const m2 = new Matrix4().copy(m); const invSX = 1 / sx; const invSY = 1 / sy; const invSZ = 1 / sz; // TODO: replace with me m2.elements[0] *= invSX; m2.elements[1] *= invSX; m2.elements[2] *= invSX; m2.elements[4] *= invSY; m2.elements[5] *= invSY; m2.elements[6] *= invSY; m2.elements[8] *= invSZ; m2.elements[9] *= invSZ; m2.elements[10] *= invSZ; makeQuaternionFromRotationMatrix4(m2, rotation); scale.x = sx; scale.y = sy; scale.z = sz; return m; } // TODO: Replace with a Box2 export function makeMatrix4Perspective( left: number, right: number, top: number, bottom: number, near: number, far: number, result = new Matrix4(), ): Matrix4 { const x = (2 * near) / (right - left); const y = (2 * near) / (top - bottom); const a = (right + left) / (right - left); const b = (top + bottom) / (top - bottom); const c = -(far + near) / (far - near); const d = (-2 * far * near) / (far - near); return result.set(x, 0, a, 0, 0, y, b, 0, 0, 0, c, d, 0, 0, -1, 0); } export function makeMatrix4PerspectiveFov( verticalFov: number, near: number, far: number, zoom: number, aspectRatio: number, result = new Matrix4(), ): Matrix4 { const height = (2.0 * near * Math.tan((verticalFov * Math.PI) / 180.0)) / zoom; const width = height * aspectRatio; // NOTE: OpenGL screen coordinates are -bottomt to +top, -left to +right. const right = width * 0.5; const left = right - width; const top = height * 0.5; const bottom = top - height; return makeMatrix4Perspective(left, right, top, bottom, near, far, result); } // TODO: Replace with a Box3? export function makeMatrix4Orthographic( left: number, right: number, top: number, bottom: number, near: number, far: number, result = new Matrix4(), ): Matrix4 { const w = 1.0 / (right - left); const h = 1.0 / (top - bottom); const p = 1.0 / (far - near); const x = (right + left) * w; const y = (top + bottom) * h; const z = (far + near) * p; return result.set(2 * w, 0, 0, -x, 0, 2 * h, 0, -y, 0, 0, -2 * p, -z, 0, 0, 0, 1); } export function makeMatrix4OrthographicSimple( height: number, center: Vector2, near: number, far: number, zoom: number, aspectRatio = 1.0, result = new Matrix4(), ): Matrix4 { height /= zoom; const width = height * aspectRatio; const left = -width * 0.5 + center.x; const right = left + width; const top = -height * 0.5 + center.y; const bottom = top + height; return makeMatrix4Orthographic(left, right, top, bottom, near, far, result); }
the_stack
import { ethers, network, upgrades, waffle } from "hardhat"; import { Signer, BigNumberish, utils, Wallet } from "ethers"; import chai from "chai"; import { solidity } from "ethereum-waffle"; import "@openzeppelin/test-helpers"; import { MdexFactory, MdexFactory__factory, MdexPair, MdexPair__factory, MdexRestrictedStrategyLiquidate, MdexRestrictedStrategyLiquidate__factory, MdexRouter, MdexRouter__factory, MdxToken, MdxToken__factory, MockERC20, MockERC20__factory, MockMdexWorker, MockMdexWorker__factory, Oracle, Oracle__factory, PancakePair, PancakePair__factory, StrategyAddBaseTokenOnly, SwapMining, SwapMining__factory, WETH, WETH__factory, } from "../../../../../typechain"; import * as TimeHelpers from "../../../../helpers/time"; import { deploy } from "@openzeppelin/hardhat-upgrades/dist/utils"; chai.use(solidity); const { expect } = chai; const FOREVER = "2000000000"; const MDX_PER_BLOCK = "51600000000000000000"; describe("MdexRestricted_StrategyLiquidate", () => { let factory: MdexFactory; let router: MdexRouter; let lp: MdexPair; let wbnb: WETH; let baseToken: MockERC20; let farmingToken: MockERC20; let mdxToken: MdxToken; let swapMining: SwapMining; let oracle: Oracle; let mockMdexWorker: MockMdexWorker; let mockMdexEvilWorker: MockMdexWorker; let strat: MdexRestrictedStrategyLiquidate; // initial Contract Signer part let deployer: Signer; let alice: Signer; let bob: Signer; let baseTokenAsAlice: MockERC20; let baseTokenAsBob: MockERC20; let farmingTokenAsAlice: MockERC20; let farmingTokenAsBob: MockERC20; let wbnbTokenAsAlice: WETH; let routerAsAlice: MdexRouter; let routerAsBob: MdexRouter; let lpAsAlice: PancakePair; let lpAsBob: PancakePair; let stratAsAlice: MdexRestrictedStrategyLiquidate; let stratAsBob: MdexRestrictedStrategyLiquidate; let mockMdexWorkerAsBob: MockMdexWorker; let mockMdexEvilWorkerAsBob: MockMdexWorker; async function fixture() { [deployer, alice, bob] = await ethers.getSigners(); const MdexFactory = (await ethers.getContractFactory("MdexFactory", deployer)) as MdexFactory__factory; factory = await MdexFactory.deploy(await deployer.getAddress()); await factory.deployed(); const WBNB = (await ethers.getContractFactory("WETH", deployer)) as WETH__factory; wbnb = await WBNB.deploy(); await wbnb.deployed(); const MdexRouter = (await ethers.getContractFactory("MdexRouter", deployer)) as MdexRouter__factory; router = await MdexRouter.deploy(factory.address, wbnb.address); await router.deployed(); const MockERC20 = (await ethers.getContractFactory("MockERC20", deployer)) as MockERC20__factory; baseToken = (await upgrades.deployProxy(MockERC20, ["BTOKEN", "BTOKEN", 18])) as MockERC20; await baseToken.deployed(); farmingToken = (await upgrades.deployProxy(MockERC20, ["FTOKEN", "FTOKEN", 18])) as MockERC20; await farmingToken.deployed(); const MDexToken = (await ethers.getContractFactory("MdxToken", deployer)) as MdxToken__factory; mdxToken = await MDexToken.deploy(); await mdxToken.deployed(); const Oracle = (await ethers.getContractFactory("Oracle", deployer)) as Oracle__factory; oracle = await Oracle.deploy(factory.address); await oracle.deployed(); // mint to alice and bob 100 BToken await baseToken.mint(await alice.getAddress(), ethers.utils.parseEther("100")); await baseToken.mint(await bob.getAddress(), ethers.utils.parseEther("100")); //farming token 10 token await farmingToken.mint(await alice.getAddress(), ethers.utils.parseEther("10")); await farmingToken.mint(await bob.getAddress(), ethers.utils.parseEther("10")); await mdxToken.addMinter(await deployer.getAddress()); //create pair await factory.createPair(baseToken.address, farmingToken.address); // create LP for using at worker lp = MdexPair__factory.connect(await factory.getPair(baseToken.address, farmingToken.address), deployer); await factory.addPair(lp.address); const MockMdexWorker = (await ethers.getContractFactory("MockMdexWorker", deployer)) as MockMdexWorker__factory; mockMdexWorker = (await MockMdexWorker.deploy( lp.address, baseToken.address, farmingToken.address )) as MockMdexWorker; await mockMdexWorker.deployed(); // MDEX REWARD SETTING const blockNumber = await TimeHelpers.latestBlockNumber(); const SwapMining = (await ethers.getContractFactory("SwapMining", deployer)) as SwapMining__factory; swapMining = await SwapMining.deploy( mdxToken.address, factory.address, oracle.address, router.address, farmingToken.address, MDX_PER_BLOCK, blockNumber ); await swapMining.deployed(); // swapMining router.setSwapMining(swapMining.address); await swapMining.addPair(100, lp.address, false); await swapMining.addWhitelist(baseToken.address); await swapMining.addWhitelist(farmingToken.address); await mdxToken.addMinter(swapMining.address); mockMdexEvilWorker = (await MockMdexWorker.deploy( lp.address, baseToken.address, farmingToken.address )) as MockMdexWorker; await mockMdexEvilWorker.deployed(); const MdexRestrictedStrategyLiquidate = (await ethers.getContractFactory( "MdexRestrictedStrategyLiquidate", deployer )) as MdexRestrictedStrategyLiquidate__factory; strat = (await upgrades.deployProxy(MdexRestrictedStrategyLiquidate, [ router.address, mdxToken.address, ])) as MdexRestrictedStrategyLiquidate; await strat.deployed(); await strat.setWorkersOk([mockMdexWorker.address], true); // Signer part lpAsAlice = PancakePair__factory.connect(lp.address, alice); lpAsBob = PancakePair__factory.connect(lp.address, bob); stratAsAlice = MdexRestrictedStrategyLiquidate__factory.connect(strat.address, alice); stratAsBob = MdexRestrictedStrategyLiquidate__factory.connect(strat.address, bob); baseTokenAsAlice = MockERC20__factory.connect(baseToken.address, alice); baseTokenAsBob = MockERC20__factory.connect(baseToken.address, bob); farmingTokenAsAlice = MockERC20__factory.connect(farmingToken.address, alice); farmingTokenAsBob = MockERC20__factory.connect(farmingToken.address, bob); routerAsAlice = MdexRouter__factory.connect(router.address, alice); routerAsBob = MdexRouter__factory.connect(router.address, bob); mockMdexWorkerAsBob = MockMdexWorker__factory.connect(mockMdexWorker.address, bob); mockMdexEvilWorkerAsBob = MockMdexWorker__factory.connect(mockMdexEvilWorker.address, bob); // Set block base fee per gas to 0 await network.provider.send("hardhat_setNextBlockBaseFeePerGas", ["0x0"]); } beforeEach(async () => { await waffle.loadFixture(fixture); }); context("When bad calldata", async () => { it("should revert", async () => { await expect(stratAsBob.execute(await bob.getAddress(), "0", "0x1234")).to.be.reverted; }); }); context("When the setOkWorkers caller is not an owner", async () => { it("should be reverted", async () => { await expect(stratAsBob.setWorkersOk([mockMdexEvilWorkerAsBob.address], true)).to.reverted; }); }); context("When non-workers call strat", async () => { it("should revert", async () => { await expect( stratAsBob.execute(await bob.getAddress(), "0", ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])) ).to.be.reverted; }); }); context("When caller worker hasn't been whitelisted", async () => { it("should revert as bad worker", async () => { // transfer to evil contract and use evilContract to work await baseTokenAsBob.transfer(mockMdexEvilWorkerAsBob.address, ethers.utils.parseEther("0.05")); await expect( mockMdexEvilWorkerAsBob.work( 0, await bob.getAddress(), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [strat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0.05")])] ) ) ).to.be.revertedWith("MdexRestrictedStrategyLiquidate::onlyWhitelistedWorkers:: bad worker"); }); }); context("When revoke whitelist worker", async () => { it("should revertas bad worker", async () => { await strat.setWorkersOk([mockMdexWorker.address], false); await expect( mockMdexWorkerAsBob.work( 0, await bob.getAddress(), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [strat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0.05")])] ) ) ).to.be.revertedWith("MdexRestrictedStrategyLiquidate::onlyWhitelistedWorkers:: bad worker"); }); }); context("When apply liquite strategy", async () => { it("should convert all LP token back to ", async () => { await factory.setPairFees(lp.address, 25); // approve for add liquidity as alice await baseTokenAsAlice.approve(router.address, ethers.utils.parseEther("1")); await farmingTokenAsAlice.approve(router.address, ethers.utils.parseEther("0.1")); await routerAsAlice.addLiquidity( baseToken.address, farmingToken.address, ethers.utils.parseEther("1"), ethers.utils.parseEther("0.1"), "0", "0", await alice.getAddress(), FOREVER ); // approve for add liquidity as bob await baseTokenAsBob.approve(router.address, ethers.utils.parseEther("1")); await farmingTokenAsBob.approve(router.address, ethers.utils.parseEther("0.1")); await routerAsBob.addLiquidity( baseToken.address, farmingToken.address, ethers.utils.parseEther("1"), ethers.utils.parseEther("0.1"), "0", "0", await bob.getAddress(), FOREVER ); expect(await baseToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("99")); expect(await baseToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("99")); expect(await farmingToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("9.9")); expect(await farmingToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("9.9")); expect(await lp.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("0.316227766016837933")); // Bob's position: 0.316227766016837933 LP // The following conditions must be satisfied if strategy executed successfully // - LPs in Strategy contract must be 0 // - Worker should have 0 LP left as all LP is liquidated // - Bob should have: // bobBtokenBefore + 1 BTOKEN + [((0.1*9975)*1)/(0.1*10000+(0.1*9975))] = 0.499374217772215269 BTOKEN] (from swap 0.1 FTOKEN to BTOKEN) in his account // - BTOKEN in reserve should be 1-0.499374217772215269 = 0.500625782227784731 BTOKEN // - FTOKEN in reserve should be 0.1+0.1 = 0.2 FTOKEN // - minBaseToken >= 1.499374217772215269 1 (debt) = 0.499374217772215269 BTOKEN must pass slippage check // Bob uses liquidate strategy to turn all LPs back to BTOKEN but with an unreasonable expectation await lpAsBob.transfer(strat.address, ethers.utils.parseEther("0.316227766016837933")); await expect( mockMdexWorkerAsBob.work( 0, await bob.getAddress(), ethers.utils.parseEther("1"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ strat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0.499374217772215270")]), ] ) ) ).to.be.revertedWith("insufficient baseToken received"); const mdexTokenBefore = await mdxToken.balanceOf(await deployer.getAddress()); const bobBTokenBefore = await baseToken.balanceOf(await bob.getAddress()); await mockMdexWorkerAsBob.work( 0, await bob.getAddress(), ethers.utils.parseEther("1"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ strat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0.499374217772215269")]), ] ) ); const prevBlockRewardMining = await strat.getMiningRewards([0]); const withdrawTx = await strat.withdrawTradingRewards(await deployer.getAddress()); const currentBlockRewardMining = await swapMining["reward()"]({ blockTag: withdrawTx.blockNumber }); const totalMiningRewards = prevBlockRewardMining.add(currentBlockRewardMining); const mdexTokenAfter = await mdxToken.balanceOf(await deployer.getAddress()); const bobBTokenAfter = await baseToken.balanceOf(await bob.getAddress()); expect( bobBTokenAfter.sub(bobBTokenBefore), "Bob's balance should increase by 1.499374217772215269 BTOKEN" ).to.be.eq(ethers.utils.parseEther("1").add(ethers.utils.parseEther("0.499374217772215269"))); expect(await lp.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0")); expect(await lp.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("0")); expect(await baseToken.balanceOf(lp.address)).to.be.eq(ethers.utils.parseEther("0.500625782227784731")); expect(await farmingToken.balanceOf(lp.address)).to.be.eq(ethers.utils.parseEther("0.2")); // formula is blockReward*poolAlloc/totalAlloc = (825600000000000000000 *100/100 )+ (51600000000000000000 *100/100) = 877200000000000000000 expect(prevBlockRewardMining).to.be.eq("825600000000000000000"); expect(totalMiningRewards).to.be.eq("877200000000000000000"); expect(mdexTokenAfter.sub(mdexTokenBefore)).to.be.eq(totalMiningRewards); }); }); context("When the withdrawTradingRewards caller is not an owner", async () => { it("should be reverted", async () => { await expect(stratAsBob.withdrawTradingRewards(await bob.getAddress())).to.reverted; }); }); });
the_stack
import config from "./config"; import { Frame, Brk, FunctionDescr, Module, Scope, ScopeInfo, VarInfo, StateMap, States, normalizeDrive, toGlobal, native, Flag, BrkFlag, defaultErrHandler, defaultFinHandler, undef, signalThread, trace } from "./state"; import * as State from "./state"; import * as TT from "./timeTravel/frame"; import { parse as babelParse } from "@babel/parser"; import babelGenerate from "@babel/generator"; import * as T from "./transform"; import * as path from "path"; import { setObjectDescriptor } from "@effectful/serialization"; import { regOpaqueObject, regFun, ModuleDescriptor, defaultBind, FunctionDescriptor } from "./persist"; import { isValidIdentifier } from "@babel/types"; const globalNS = config.globalNS; const { journal, context, token, closures, functions, thunks, CLOSURE_PARENT, CLOSURE_VARS, CLOSURE_META, CLOSURE_FUNC } = State; const nativeFunction = native.Function; const nativeObject = native.Object; const __effectful__nativeApply = native.FunctionMethods.apply; const __effectful__nativeCall = native.FunctionMethods.call; const defineProperty = nativeObject.defineProperty; const nativeToString = Function.prototype.toString; const weakMapSet = native.WeakMap.set; const weakMapDelete = native.WeakMap.delete; const setPrototypeOf = nativeObject.setPrototypeOf; const __effectful__reflectApply = native.Reflect.apply; let curModule: Module = undefined as any; // this is always used in context where this is inited let moduleChanged = false; const recordFrame = config.timeTravel ? function recordFrame(top: Frame | null) { if (top && journal.enabled) TT.recordFrame(top); } : function recordFrame() {}; class ArgsTraps { func: Frame; $: any[]; constructor(func: Frame) { this.func = func; this.$ = func.$; } set(target: any[], prop: any, value: any) { if (typeof prop === "symbol" || isNaN(prop)) return Reflect.set(target, prop, value); const { func } = this; func.$[func.meta.shift + +prop] = value; return Reflect.set(target, prop, value); } get(target: any[], prop: any): any { if (typeof prop === "symbol" || isNaN(prop)) return Reflect.get(target, prop); const meta = this.func.meta; const index = +prop; if (meta.params.length > index) return this.$[meta.shift + index]; return Reflect.get(target, prop); } } const objectValues = Object.values; export function compileModule(): Module | null { if (!moduleChanged) { if (curModule.exports) curModule.cjs.exports = curModule.exports; return null; } if (curModule.version === void 0) curModule.version = 0; else curModule.version++; if (!curModule.topLevel || curModule.topLevel.blackbox) return curModule; const funcs = objectValues(curModule.functions).reverse(); const lines = (curModule.lines = new Array(curModule.topLevel.endLine)); for (let meta of funcs) { const states = meta.states; for (const state of states) { if (state.flags | State.BrkFlag.STMT && state.line) { (lines[state.line] || (lines[state.line] = [])).push(state); } } for (let x = states.length; --x; ) { const state = states[x]; if (state.flags | State.BrkFlag.STMT && state.line) { for (let j = state.line + 1, end = state.endLine; j <= end; ++j) (lines[j] || (lines[j] = [])).push(state); } } } let cur = null; for (let i = lines.length; i--; ) { const line = lines[i]; if (!line) lines[i] = cur; else cur = lines[i]; } return curModule; } export function getCurModule(): Module { return curModule; } export function argsWrap<T>(frame: Frame, value: Iterable<T>): T[] { const arr = native.Array.from(value); defineProperty(arr, "callee", { writable: true, enumerable: false, value: frame.func }); return new native.Proxy(arr, new ArgsTraps(frame)); } interface CjsModule { id: string; hot?: { accept(): void; }; } export function module( this: any, modName: string | number, evalContext: { [name: string]: VarInfo } | undefined, cjs: CjsModule | undefined, require: any, safePrefix: string, closSyms: { [name: string]: any }, params: { [name: string]: any } | null ) { let fullPath: string | undefined; let name: string; let id: number | undefined; curModule = <any>null; if (typeof modName === "number") { id = modName; name = `#eval_${id}.js`; } else { name = modName; fullPath = normalizeDrive(path.join(config.srcRoot, name)); } let prevVersion = config.hot === false ? null : context.modules[<any>(fullPath || id)]; if (config.hot === true) curModule = <any>prevVersion; if (!require) require = <any>closSyms["__webpack_require__"]; if (cjs) { if (config.hot === true && cjs.hot) { cjs.hot.accept(); } // something is loaded with node and webpack for example if (prevVersion && (!prevVersion.cjs || prevVersion.cjs.id !== cjs.id)) prevVersion = curModule = <any>null; } regOpaqueObject(cjs, `cjs#${name}`); moduleChanged = !curModule; if (!curModule) { curModule = <any>{ functions: {}, prevVersion }; if (prevVersion) prevVersion.prevVersion = null; } (<any>curModule).topLevel = null; regOpaqueObject(cjs, name + "$mod"); context.modules[<any>(fullPath || id)] = curModule; setObjectDescriptor(curModule, ModuleDescriptor); if (cjs) { context.modulesById[cjs.id] = curModule; regOpaqueObject(cjs, `${cjs.id}$mod`); } curModule.name = name; curModule.require = require; curModule.fullPath = fullPath; curModule.id = id; context.moduleId = (cjs && cjs.id) || null; curModule.cjs = cjs; curModule.evalContext = evalContext; curModule.safePrefix = safePrefix; curModule.api = this; curModule.closSyms = closSyms; curModule.params = params; curModule.onReload = null; return curModule; } let metaCount = 0; export const parentTag = { _parentTag: true }; export function fun( name: string, origName: string | null, calleeName: number | null, parentConstr: ((this: any, ...args: any[]) => any) | null, params: string[], localsNum: number, varsNum: number, loc: string | null, flags: number, handler: (this: any, p: any) => any | string, errHandler: StateMap, finHandler: StateMap, scopeDepth: number, states: States ): (this: any, ...args: any[]) => any { const top = !curModule.topLevel; let meta = curModule.functions[name]; if (meta) { if (nativeToString.call(handler) === nativeToString.call(meta.handler)) { if (top) curModule.topLevel = meta; meta.handler = handler; return meta.func; } moduleChanged = true; } else if (!meta) meta = curModule.functions[name] = <FunctionDescr>{}; if (top) curModule.topLevel = meta; if (!errHandler) errHandler = defaultErrHandler; if (!finHandler) finHandler = defaultFinHandler; const names = [origName || "*"]; let parent: FunctionDescr | null = null; if (parentConstr) parent = <FunctionDescr>functions.get(parentConstr); for (let p = parent; p; p = p.parent) names.unshift(p.name); const uniqName = `${curModule.name}#${names.join(".")}`; const fullName = `${uniqName}@${loc || "?"}`; let persistName = parent ? parent.persistName : curModule.name; if (!top) persistName += "#" + (origName || "*"); const memo: Brk[] = []; const evalContext = curModule.evalContext || {}; if (loc) { meta.location = loc; [meta.line, meta.column, meta.endLine, meta.endColumn] = location(loc); } for (const [flags, loc, scope] of states) { const [line, column, endLine, endColumn] = location(loc); let id = memo.length; const brk: Brk = { flags, id, meta, line, column, endLine, endColumn, scope: scope ? buildScope(scope, evalContext) : evalContext, scopeDepth: scope[2], location: strLoc(line, column, endLine, endColumn), breakpoint: null, logPoint: null }; regOpaqueObject(brk, `s#${persistName}#${id}`); memo.push(brk); } meta.varsNum = varsNum; meta.shift = calleeName ? 2 : 1; meta.exitBreakpoint = memo[memo.length - 1]; meta.blackbox = (flags & Flag.BLACKBOX) !== 0; meta.origName = origName || "(anonymous)"; meta.calleeName = calleeName; meta.module = curModule; meta.flags = flags || 0; meta.handler = handler; meta.errHandler = errHandler; meta.finHandler = finHandler; meta.name = name; meta.fullName = fullName; meta.parent = parent; meta.uniqName = uniqName; meta.persistName = persistName; meta.params = params; meta.localsNum = localsNum; meta.errState = states.length - 2; meta.finState = states.length - 1; if (meta.id == null) meta.id = metaCount++; meta.states = memo; meta.statesByLine = memo.filter(hasLine).sort(byLine); meta.deps = []; meta.scopeDepth = scopeDepth; meta.onReload = null; if (parent) parent.deps.push(meta); const headLines: string[] = []; const ctx = curModule.safePrefix; let funcName = meta.origName; if (funcName) { if (!isValidIdentifier(funcName) || meta.params.indexOf(funcName) !== -1) funcName = ctx + funcName.replace(/\W/g, "_"); } else { funcName = ctx + meta.name; } let varsInit = [`${ctx}.$`]; if (meta.calleeName) varsInit.push(funcName); varsInit.push(...meta.params); varsInit.fill("void 0", varsInit.length, (varsInit.length = meta.varsNum)); headLines.push(`${ctx}.$ = [${varsInit.join()}]`); const isArrow = flags & Flag.ARROW_FUNCTION; const isAsync = flags & Flag.ASYNC_FUNCTION; const isGenerator = flags & Flag.GENERATOR_FUNCTION; if (flags & Flag.HAS_THIS) headLines.push(`${ctx}.self = ${isArrow ? ctx + "$.self" : "this"}`); if (flags & Flag.HAS_ARGUMENTS) headLines.push( `${ctx}.args = ${ isArrow ? ctx + "$.args" : `${ctx}args(${ctx},arguments)` }` ); const api = curModule.api; let headCode; if (isGenerator) { headCode = `return ${ctx}.iter /* regenerator */`; } else { headCode = ` try { ${ctx}pushFrame(${ctx},${funcName}); return ${ctx}.meta.handler(${ctx}, ${ctx}.$, null); } catch(e) { return ${ctx}M.handle(${ctx}, e); }`; } const constrParams = [ "module", "exports", `${ctx}args`, `${ctx}context`, `${ctx}m`, `${ctx}M`, `${ctx}clos`, `${ctx}frame`, `${ctx}pushFrame` ]; const cjs = curModule.cjs; const args = [ cjs, cjs && cjs.exports, argsWrap, context, meta, api, isAsync || !isGenerator ? api.clos : api.closG, isAsync ? isGenerator ? api.frameAG : api.frameA : isGenerator ? api.frameG : api.frame, api.pushFrame ]; constrParams.push(`return (function(${ctx}$){ var ${ctx}x = [${ctx}$,${ctx}$ && ${ctx}$.$,${ctx}m,function ${funcName}(${meta.params.join()}) { ${flags & Flag.SLOPPY ? "" : '"use strict";'} var ${ctx} = ${ctx}frame(${ctx}x,new.target); ${headLines.join("\n")} ${headCode} }] return ${ctx}clos(${ctx}x); })`); const constr: any = __effectful__reflectApply( native.Reflect.construct(nativeFunction, constrParams), null, args ); meta.func = constr; weakMapSet.call(functions, constr, meta); if (config.expFunctionConstr) constr.constructor = FunctionConstr; if (config.persistState) regFun(meta); return meta.func; } function hasLine(b: Brk): boolean { return (b.flags & State.BrkFlag.STMT) !== 0 && b.line > 0; } function byLine(a: Brk, b: Brk): number { return a.line - b.line; } function strLoc( line?: number, column?: number, endLine?: number, endColumn?: number ) { return `${line || "?"}:${column == null ? "?" : column}-${endLine || "?"}:${ endColumn == null ? "?" : endColumn }`; } function buildScope( scope: Scope, parent: { [name: string]: VarInfo } ): ScopeInfo { if (scope == null) return parent; if (scope.length === 4) return scope[3]; const [vars, par, depth] = scope; const scopeInfo: ScopeInfo = {}; scope.push(scopeInfo); const parScope = par ? buildScope(par, parent) : parent; if (parScope) Object.assign(scopeInfo, parScope); // tslint:disable-next-line:forin for (const i in vars) { const info = vars[i]; if (!info) continue; const [declDepth, declLoc] = info; scopeInfo[i] = [declDepth, depth, declLoc]; } return scopeInfo; } export const clos: any = config.persistState ? function clos(closure: State.Closure) { const func = closure[CLOSURE_FUNC]; weakMapSet.call(closures, func, closure); setObjectDescriptor(func, FunctionDescriptor /*(<any>meta).descriptor*/); return func; } : function clos(closure: State.Closure) { const func = closure[CLOSURE_FUNC]; setPrototypeOf(func, FunctionConstr.prototype); weakMapSet.call(closures, func, closure); return func; }; function __effectful__apply(this: any) { if (context.call === __effectful__apply) context.call = this; return __effectful__reflectApply( <any>__effectful__nativeApply, this, <any>arguments ); } function __effectful__call(this: any) { if (context.call === __effectful__call) context.call = this; return __effectful__reflectApply( <any>__effectful__nativeCall, this, <any>arguments ); } export function pushScope(varsNum: number) { const top = <Frame>context.top; const cur = Array(varsNum); cur[0] = top.$; return (top.$ = cur); } export function copyScope() { const top = <Frame>context.top; return (top.$ = top.$.slice()); } export function popScope() { const top = <Frame>context.top; return (top.$ = top.$[0]); } export function __effectful_mcall(prop: string, ...args: [any, ...any[]]) { const func = args[0][prop]; if (!func) throw new TypeError(`${prop} isn't a function`); return __effectful__reflectApply( <any>__effectful__nativeCall, (context.call = func), args ); } /** * runs a computation until it encounters some breakpoint (returns `token) * or finishes the whole computation (returns the resulting value or throws an exception) */ export function step() { try { context.running = true; const value = context.value; const top = context.top; const error = context.error; context.value = void 0; context.error = false; if (!top) return value; if (error) top.meta.errHandler(top, top.$); if (top.brk && top.brk.flags & BrkFlag.EXIT) { if (!context.enabled) { const restoreDebug = top.restoreEnabled; if (restoreDebug !== undef) { context.enabled = true; context.call = restoreDebug; } } popFrame(top); } return loop(value); } finally { context.running = false; } } export function loop(value: any): any { let top: Frame | null = context.top; while (top) { try { recordFrame(top); value = top.meta.handler(top, top.$, value); top = context.top; } catch (e) { if (e === token) { context.onStop(); return e; } (<Frame>top).error = e; if ( !(<Frame>top).meta.blackbox && context.exception !== e && checkErrBrk(<Frame>top, e) ) { context.value = e; context.error = true; context.top = top; context.onStop(); return token; } top = context.top; if (!top) { if (config.verbose) { // tslint:disable-next-line:no-console console.error( `Uncaught exception: ${e}(on any:${!!context.brkOnAnyException},on uncaught:${!!context.brkOnUncaughtException})` ); if (config.debuggerDebug && (<any>e).stack) { // tslint:disable-next-line:no-console console.error("Real stack:", (<any>e).stack); // tslint:disable-next-line:no-console console.error("Original stack:", (<any>e)._deb_stack); } } throw e; } top.error = value = e; top.meta.errHandler(top, top.$); } } return value; } /** resumes execution of the current stack */ export function resume(frame: Frame, e: any) { try { frame.next = context.top; context.top = frame; recordFrame(frame); return frame.meta.handler(frame, frame.$, e); } catch (e) { return handle(frame, e); } } /** like `resume` but appends the frame to the current stack */ export function resumeLocal(frame: Frame, e: any) { try { frame.caller = frame.next = context.top; context.top = frame; recordFrame(frame); return frame.meta.handler(frame, frame.$, e); } catch (e) { return handle(frame, e); } } /** checks if the current frame's state has an exception handler */ function hasEH(frame: Frame): boolean { return (frame.meta.states[frame.state].flags & BrkFlag.HAS_EH) !== 0; } export function checkErrBrk(frame: Frame, e: any): boolean { if (!context.enabled) return false; context.exception = e; if (e && e.stack) { const stack = [String(e)]; for (let i: Frame | null = frame; i; i = i.next) { if (i.brk) stack.push( ` at ${i.meta.origName} (${i.meta.module.name}:${i.brk.line}:${i.brk.column})` ); } if (config.debuggerDebug) { try { defineProperty(e, "_deb_stack", { value: stack.join("\n") }); } catch (e) {} } else e.stack = stack.join("\n"); } let needsStop = false; if (context.brkOnAnyException) { needsStop = true; } else if (context.brkOnUncaughtException) { // avoiding running finally blocks needsStop = true; for (let i: Frame | null = frame; i; i = i.next) { if (hasEH(i)) { needsStop = (i.meta.flags & Flag.EXCEPTION_BOUNDARY) !== 0; break; } } } if (needsStop) frame.stopReason = "exception"; return needsStop; } export function handle(frame: Frame, e: any) { for (;;) { if (e === token) { if (context.running || frame.next) throw e; context.onStop(); return e; } if (frame !== context.top) throw e; // tslint:disable-next-line:no-console const meta = frame.meta; frame.error = e; if (!meta.blackbox && e !== context.exception && checkErrBrk(frame, e)) { context.value = e; context.error = true; context.top = frame; if (frame.next) throw token; context.onStop(); return token; } meta.errHandler(frame, frame.$); try { recordFrame(frame); return frame.meta.handler(frame, frame.$, null); } catch (ex) { e = ex; } } } export function evalAt(src: string) { const top = <Frame>context.top; const meta = top.meta; const state = top.meta.states[top.state]; const memo = meta.evalMemo || (meta.evalMemo = new native.Map()); const key = `${src}@${meta.module.name}@${meta.uniqName}@${ state ? state.id : "*" }/${context.enabled}}`; let resMeta = memo.get(key); if (!resMeta) { resMeta = compileEval( src, meta.module, state.scope, state.scopeDepth + 1, !context.enabled, null ); memo.set(key, resMeta); } const func = resMeta.func(top); context.call = func; return __effectful__nativeCall.call(func, top.self); } const locationRE = /^(\d+):(\d+)-(\d+):(\d+)$/; const undefLoc = [0, 0, 0, 0]; /** parses location string into a tuple with a line, a column, a last last and a last column */ export function location(str: string): number[] { if (!str) return undefLoc; const res: number[] = []; const re = locationRE.exec(str); if (!re || re.length < 5) return res; for (let i = 1; i < 5; i++) res.push(+re[i]); return res; } let evalCnt = 0; const indirMemo = new native.Map<string, string>(); /** * Like `compileEval` but returns a self-sufficient string, which can be * passed to, say, "vm". However, it doesn't memoize meta-data construction * (like `compileEval` does) though. */ export function compileEvalToString( code: string, params: string[] | null ): string { const savedEnabled = journal.enabled; try { journal.enabled = false; const top = context.top; const meta = top && top.meta; const blackbox = !meta || meta.blackbox; const key = code + "@" + blackbox; let tgt = indirMemo.get(key); if (tgt) return tgt; const id = toGlobal(++evalCnt); if (!blackbox) context.onNewSource(id, code); const ast = babelParse(code, { allowReturnOutsideFunction: true }); if (params == null) { const body = <any>ast.program.body; if (body.length === 1 && body[0].type === "ExpressionStatement") body[0] = { type: "ReturnStatement", argument: body[0].expression }; } tgt = babelGenerate( T.run(ast, { preInstrumentedLibs: true, blackbox, pureModule: true, evalContext: null, evalParams: params, rt: false, ns: globalNS, relativeName: id, filename: `VM${id}.js`, iifeWrap: true, moduleExports: params == null ? "execModule" : "retModule", constrParams: { code }, timeTravel: config.timeTravel, implicitCalls: config.implicitCalls }), { compact: true } ).code; indirMemo.set(key, tgt); return `/*!EDBG!*/(function() { ${tgt}; })()`; } finally { journal.enabled = savedEnabled; } } /** * executes a top level function for a current module * this is an API required for `compileEvalToString` */ export function execModule() { compileModule(); return (context.call = curModule.topLevel.func(null))(); } /** * returns a top level function for a current module * this is an API required for `compileEvalToString` */ export function retModule() { compileModule(); return curModule.topLevel.func(null); } const functionConstrMemo = new native.Map<string, FunctionDescr>(); const savedEval = eval; export const FunctionConstr = function Function(...args: any[]) { let res: any; if (context.enabled && context.call === Function) { const code = args.pop(); const key = `${code}@Fn@/${context.enabled}/${args.join()}`; let meta = functionConstrMemo.get(key); if (!meta) { meta = compileEval( code, (context.top && context.top.meta && context.top.meta.module) || null, null, 0, !context.enabled, args ); functionConstrMemo.set(key, meta); } res = meta.func(null); } else res = native.Reflect.construct(nativeFunction, args); res.constructor = Function; return res; }; if (config.patchRT) { FunctionConstr.prototype = Function.prototype; defineProperty(FunctionConstr.prototype, "call", { configurable: true, writable: true, value: __effectful__call }); defineProperty(FunctionConstr.prototype, "apply", { configurable: true, writable: true, value: __effectful__apply }); defineProperty(FunctionConstr.prototype, "bind", { configurable: true, writable: true, value: defaultBind }); defineProperty(FunctionConstr.prototype, "toString", { configurable: true, writable: true, value() { // nothing to see here (lodash refuses to work with not native functions) let params: string = ""; let name = this.name; const data = closures.get(this); if ( (data && data[CLOSURE_META] && !data[CLOSURE_META].blackbox) || !State.nativeFuncs.has(this) ) return nativeToString.call(this); return `function ${name || ""}(${params}) { [native code] }`; } }); } regOpaqueObject(FunctionConstr, "@effectful/debugger/Function"); regOpaqueObject(__effectful__call, "@effectful/debugger/call"); regOpaqueObject(__effectful__apply, "@effectful/debugger/apply"); regOpaqueObject(defaultBind, "@effectful/debugger/bind"); export function indirEval(code: string): any { if (!context.enabled || context.call !== indirEval) return savedEval(code); const meta = compileEval( code, context.top ? context.top.meta.module : null, null, 0, !context.enabled, null ); const func = meta.func(null); context.call = func; return __effectful__nativeCall.call(func, void 0); } function trim(n: string) { return n.trim(); } function splitParams(param: string): string[] { return param.split(",").map(trim); } export function compileEval( code: string, mod: Module | null, evalContext: { [name: string]: VarInfo } | null, scopeDepth: number | null, blackbox: boolean, params: string[] | null, id?: number ): FunctionDescr { const savedEnabled = journal.enabled; blackbox = blackbox || !context.top || context.top.meta.blackbox; try { journal.enabled = false; if (id == null) id = toGlobal(++evalCnt); if (!blackbox) context.onNewSource(id, code); const ast = babelParse(code, { allowReturnOutsideFunction: true }); if (params == null) { const body = <any>ast.program.body; if (body.length === 1 && body[0].type === "ExpressionStatement") body[0] = { type: "ReturnStatement", argument: body[0].expression }; } else { params = (<string[]>[]).concat(...params.map(splitParams)); } const tgt = babelGenerate( T.run(ast, { preInstrumentedLibs: true, blackbox, exclude: false, pureModule: true, evalContext, evalParams: params, rt: false, ns: globalNS, relativeName: id, filename: `VM${id}.js`, moduleExports: null, iifeWrap: false, scopeDepth, constrParams: null, timeTravel: config.timeTravel, implicitCalls: config.implicitCalls }), { compact: true } ).code; const cjs = mod && mod.cjs; new nativeFunction( "exports", "require", "module", "__filename", "__dirname", tgt )( // exports, mod && (<any>mod).exports, (mod && mod.require) || (cjs && cjs.require), mod, mod ? mod.fullPath : ".", mod && mod.fullPath ? path.dirname(mod.fullPath) : "" ); curModule.params = { code, parent: mod && (mod.fullPath || mod.id), evalContext, scopeDepth, id, params, blackbox }; compileModule(); const res = curModule.topLevel; return res; } finally { journal.enabled = savedEnabled; } } export function isDelayedResult(value: any): boolean { return value === token; } export function makeFrame(closure: State.Closure, newTarget: any): Frame { let $g = global; const frame: Frame = { $: <any>closure[CLOSURE_VARS], closure, func: closure[CLOSURE_FUNC], $g, meta: closure[CLOSURE_META], state: 0, goto: 0, done: false, running: false, parent: closure[CLOSURE_PARENT], newTarget, brk: null, next: null, caller: null, restoreEnabled: undef, awaiting: token, stopReason: null, onReturn: null, onError: null, promise: null, timestamp: journal.now, result: void 0, error: void 0, self: void 0, args: void 0 }; return frame; } let TOP_LINES_STACK_NUM = 2; const isStackFrameLine = State.isNode ? function isStackFrameLine(line: string) { line = line.trim(); if (line.length === 0) return false; let f = line; for (;;) { const m = /\((.+):\d+:\d+\)/g.exec(f); if (!m) break; f = m[1]; } if (!path.isAbsolute(f) && f[0] !== ".") return false; return !/__effectful__/g.test(line); } : function isStackFrameLine(line: string) { return ( line.trim().length > 0 && !/__effectful__|\(events\.js\:|\(net\.js\:|\bprocess\/browser\.js|\bdrainQueue\b/g.test( line ) ); }; function numFrames(e: any): number { let s = String(e.stack).split("\n").filter(isStackFrameLine); return s.length; } // maybe there is a better way, but we need to know if the function call is async // we just compare stack trace lines size here const nativeSetTimeout = native.setTimeout; nativeSetTimeout(function setupTopNumFrames() { TOP_LINES_STACK_NUM = numFrames(new Error("__effectful__stack")) + 1; }, 0); function scheduleCurrentThread() { context.queue.push({ top: context.top, debug: context.enabled, value: context.value }); if (config.verbose) trace(`DEBUGGER: schedule a thread: ${State.stackDescr().join(" ==> ")}`); context.top = null; signalThread(); throw token; } export function pushFrame(frame: Frame, redir: any): any { const next = context.top; frame.next = frame.caller = next; const res = (context.top = frame); if (next) { if (context.enabled) { if (!context.launched && !frame.meta.blackbox) { State.pauseEventQueue(); scheduleCurrentThread(); } if (context.call !== redir) { // maybe it is called via older version frame.restoreEnabled = context.call; context.enabled = false; } } } else { context.onFirstFrame(); if (!context.running && context.enabled) { // so suddenly some transpiled function is executed // we could use `caller === null` but it could be called from a strict mode // on FF this is one line, but on Chrome two // the condition probably not always works if (numFrames(new Error("__effectful__stack")) <= TOP_LINES_STACK_NUM) { // we don't want that code to run if something is stopped on a breakpoint already // this way order of async functions is preserved if (context.pausedTop || context.queue.length) scheduleCurrentThread(); } } } return res; } export function popFrame(top: Frame) { const next = top.next; if ((context.top = next) == null) signalThread(); else recordFrame(next); } export const frame: (closure: State.Closure, newTarget: any) => any = config.timeTravel ? function frame(closure: State.Closure, newTarget: any): any { const top = context.top; recordFrame(top); return makeFrame(closure, newTarget); } : makeFrame; export function checkExitBrk(top: Frame, value: any) { const meta = top.meta; if (meta.blackbox) return; const brk = (context.brk = top.brk = meta.exitBreakpoint); if (brk && context.needsBreak(brk, top, value)) { context.value = value; context.error = false; throw token; } } export function ret(value: any): any { const top = <Frame>context.top; if ( top.newTarget && (!value || (typeof value !== "object" && typeof value !== "function")) ) value = top.self; top.result = void 0; top.done = true; if (top.onReturn) { context.call = top.onReturn; top.onReturn(value); } if (context.enabled) { checkExitBrk(top, value); } else if (top.restoreEnabled !== undef) { context.enabled = true; context.call = top.restoreEnabled; } popFrame(top); return value; } export function unhandled(e: any) { const top = <Frame>context.top; // top.state = top.goto = 0; if (top.onError) { context.call = top.onError; top.onError(e); } top.error = void 0; top.done = true; if (!context.enabled) { const restoreDebug = top.restoreEnabled; if (restoreDebug !== undef) { context.enabled = true; context.call = restoreDebug; } } popFrame(top); throw e; } export function brk(): any { if (context.enabled === false) return; const { needsBreak, top } = context; let p: Brk; if ( top && (p = top.brk = context.brk = top.meta.states[top.state]) && needsBreak(p, top) && context.enabled ) { throw token; } } export function iterator<T>(v: Iterable<T>) { return (context.call = v[Symbol.iterator]), v[Symbol.iterator](); } export function iteratorM<T>(v: AsyncIterable<T>) { return v[Symbol.asyncIterator] ? ((context.call = v[Symbol.asyncIterator]), v[Symbol.asyncIterator]()) : ((context.call = (<any>v)[Symbol.iterator]), (<any>v)[Symbol.iterator]()); } export function then( p: Promise<any>, onResolve: (value: any) => any, onReject?: (reason: any) => any ) { context.call = <any>Promise.resolve; const res = <any>Promise.resolve(p); context.call = res.then; return res.then(onResolve, onReject); } export function raise(e: any) { context.exception = undef; throw e; } export { token, context }; /** resets module's states (for tests) */ export function reset() { metaCount = 0; indirMemo.clear(); functionConstrMemo.clear(); context.pausedTop = context.top = null; context.running = false; context.brk = null; context.queue.length = 0; context.launched = false; } export function iterErr(iter: any, reason: any) { if (!(context.call = iter.throw)) throw reason; return iter.throw(reason); } export function iterErrUndef() { return TypeError("The iterator does not provide a 'throw' method."); } export function iterFin(iter: any, value: any) { if (!(context.call = iter.return)) return { value, done: true }; return iter.return(value); } export function iterNext(iter: any, value: any) { return (context.call = iter.next), iter.next(value); } /** * if `value` is a lazy thunk it is executed and its result is returned * otherwise `value` is returned as is */ export function force(value: any): any { if (!value) return value; const thunk = thunks.get(value); if (thunk === void 0) { return value; } // defineProperty(value, thunkSymbol, { value: null, configurable: true }); weakMapDelete.call(thunks, value); return thunk(); } regOpaqueObject(__effectful__nativeCall, "@effectful/debugger/native/call"); regOpaqueObject(__effectful__nativeApply, "@effectful/debugger/native/apply"); export { config };
the_stack
import * as React from "react"; import { BlankMaskRenderer, ChildrenRenderer, MayersRenderer, NavbarRenderer, SidepanelRenderer, ViewsRenderer } from "./SceneRenderer/Items"; import { PureComponent, SyntheticEvent, ReactNode, RefObject } from "react"; import { Props as MayerProps } from "./Mayer"; import Sidepanel from "./Sidepanel"; import { AnimationType, NavbarMenu, SidepanelConfig } from "./Airr"; import { ViewsConfigItem } from "./Scene"; export type NavbarProp = 1 | true | -1 | 0 | false; export type ViewsArray = ViewsConfigItem<any>[]; export interface CoreSceneProps { /** * The name of the scene. Must be unique among others views in parent scene. Will be used as identification string */ name: string; /** * Name of the active view */ activeViewName?: string; /** * Boolean telling if GUI should be disabled meaning no user actions, events are allowed. * GUI is disabled via absolute positioned, not visible div that has the biggest z-Index */ GUIDisabled?: boolean; /** * React element to be placed in GUI disabling div */ GUIDisableCover?: ReactNode; /** * Type of animation to perform when switching views */ animation?: AnimationType; /** * Time of views changing animation in miliseconds */ animationTime?: number; /** * Specify if navbar is present (1,true) or not (0,false). Or maybe hidden (-1) */ navbar?: NavbarProp; /** * Height of the navbar in pixels */ navbarHeight?: number; /** * Navbar menu is placed on the right most side. Might contain "toggleSidepanel" button or any custom buttons list. */ navbarMenu?: NavbarMenu; /** * Extra, space separated, navbar's class list */ navbarClass?: string; /** * Boolean specifing if navbar renders BackButton. Placed by default on the left side of navbar. */ backButton?: boolean; /** * Do you need to still show backButton even if scene is rendering first view from stack? */ backButtonOnFirstView?: boolean; /** * Function that will handle back button click events */ handleBackButton?: (e: SyntheticEvent<HTMLElement>) => void; /** * Function that will handle back button clicks events on when first view in stack is active */ handleBackBehaviourOnFirstView?: () => void; /** * Is this view active in parent scene. Readonly. */ active?: boolean; /** * Sidepanels declaration. Must contain two properties: `type` and `props` **/ sidepanel?: SidepanelConfig<any>; /** * This function will be called when sidepanel changes it's visibility. * It's argument will be isShown bool. */ sidepanelVisibilityCallback?(isShown: boolean): void; /** * Array of `views`. Every view object declaration must contain two properties: `type` and `props`. */ views?: ViewsArray; /** * Array of `mayers` objects that will be render into this Scene. Must contain special Mayer class properties. * To check the possible values of properties go to Mayer declaration. */ mayers?: MayerProps[]; /** * Title that will be use in parent Scene navbar title section */ title?: ReactNode; /** * Extra, space separated classes names to use upon first div element. */ className?: string; /** * Children prop */ children?: ReactNode; /** * Inner, private prop for manipulating navbar title. Do not set manually. */ mockTitleName?: string; //inner props key?: string; ref?: React.LegacyRef<PureComponent>; } export interface Props extends CoreSceneProps { /** * React component's ref object */ refCOMPSidepanel: RefObject<Sidepanel>; /** * React ref to dom object */ refDOM: RefObject<HTMLDivElement>; /** * React ref to dom object */ refDOMNavbar: RefObject<HTMLDivElement>; /** * Object of React refs components specified under string keys */ refsCOMPViews: { [name: string]: RefObject<PureComponent> }; /** * React component's ref object */ refDOMContainer: RefObject<HTMLDivElement>; /** * Inner, private prop with containers height information */ containersHeight: number; } export const sceneDefaultProps: CoreSceneProps = { name: "", activeViewName: null, GUIDisabled: false, GUIDisableCover: null, animation: "slide", animationTime: 300, navbar: false, navbarHeight: 48, navbarMenu: null, navbarClass: "", backButton: false, backButtonOnFirstView: false, handleBackButton: null, handleBackBehaviourOnFirstView: null, active: false, sidepanel: null, views: [], mayers: [], title: "", className: "", sidepanelVisibilityCallback: null, children: null, mockTitleName: null }; export default class SceneRenderer extends PureComponent<Props> { static defaultProps: Props = { ...sceneDefaultProps, refCOMPSidepanel: null, refDOM: null, refDOMNavbar: null, refsCOMPViews: null, refDOMContainer: null, mockTitleName: "", containersHeight: null }; /** * Mayers Components refferencies */ mayersCompsRefs = {}; /** * Returns view index from this.props.views array * * @param {string} viewName * @returns {Number} */ getViewIndex(viewName: string): number { return this.props.views.findIndex((config): boolean => config.props.name === viewName); } /** * Handles navbar backbutton tap events * * @param {object} e Event object * @returns {void} */ handleBackButton = (e: SyntheticEvent<HTMLElement>): void => { const backBtn = e.currentTarget; backBtn.classList.add("clicked"); setTimeout((): void => { backBtn.classList.remove("clicked"); }, 300); if ( this.getViewIndex(this.props.activeViewName) === 0 && this.props.handleBackBehaviourOnFirstView ) { return this.props.handleBackBehaviourOnFirstView(); } if (this.props.handleBackButton) { this.props.handleBackButton(e); } else { console.warn("[] Back button handler was not specified."); } }; /** * Handles navbar menu button tap events * * @param {object} e Event object * @returns {void} */ handleMenuButtonToggleSidepanel = (e: SyntheticEvent<HTMLElement>): void => { if (this.props.refCOMPSidepanel && this.props.refCOMPSidepanel.current) { this.props.refCOMPSidepanel.current.isShown() ? this.props.refCOMPSidepanel.current.hide() : this.props.refCOMPSidepanel.current.show(); } }; checkValidActiveView = (): boolean => { const isAnyViewActive = this.props.views.some( (view): boolean => view.props.name === this.props.activeViewName ); if (!isAnyViewActive) { console.warn( "[] No view was set as active" + (this.props.name && " in Scene named `" + this.props.name + "`") + "." ); } return Boolean(isAnyViewActive); }; render(): ReactNode { let className = "airr-view airr-scene"; this.props.active && (className += " active"); this.props.className && (className += " " + this.props.className); this.checkValidActiveView(); const activeViewIndex = this.getViewIndex(this.props.activeViewName); let mockViewTitle; if (this.props.mockTitleName) { const mockViewIndex = this.getViewIndex(this.props.mockTitleName); if (mockViewIndex >= 0) { const mockView = this.props.views[mockViewIndex]; if (mockView.props.title) { mockViewTitle = mockView.props.title; } } } return ( <div className={className} ref={this.props.refDOM}> <div className="airr-content-wrap"> <NavbarRenderer navbar={this.props.navbar} activeViewIndex={activeViewIndex} backButtonOnFirstView={this.props.backButtonOnFirstView} backButton={this.props.backButton} handleBackButton={this.handleBackButton} navbarMenu={this.props.navbarMenu} hasSidepanel={Boolean(this.props.sidepanel)} handleMenuButtonToggleSidepanel={this.handleMenuButtonToggleSidepanel} navbarClass={this.props.navbarClass} mockViewTitle={mockViewTitle} activeViewTitle={ this.props.views[activeViewIndex] && this.props.views[activeViewIndex].props.title } refDOMNavbar={this.props.refDOMNavbar} navbarHeight={this.props.navbarHeight} /> <ViewsRenderer className={this.props.animation ? this.props.animation + "-animation" : ""} refsCOMPViews={this.props.refsCOMPViews} activeViewName={this.props.activeViewName} views={this.props.views} refDOMContainer={this.props.refDOMContainer} containersHeight={this.props.containersHeight} /> </div> <ChildrenRenderer {...this.props}>{this.props.children}</ChildrenRenderer> {this.props.sidepanel && ( <SidepanelRenderer type={this.props.sidepanel.type} refCOMPSidepanel={this.props.refCOMPSidepanel} visibilityCallback={this.props.sidepanelVisibilityCallback} sceneHasMayers={Boolean(this.props.mayers.length)} props={this.props.sidepanel.props} /> )} <MayersRenderer mayers={this.props.mayers} /> <BlankMaskRenderer GUIDisabled={this.props.GUIDisabled} GUIDisableCover={this.props.GUIDisableCover} /> </div> ); } }
the_stack
function sign(number: number) { if(number < 0) return -1; if(number > 0) return 1; return 0; } class EasyPZLoader { static DEFAULT_MODES = ["SIMPLE_PAN", "HOLD_ZOOM_IN", "CLICK_HOLD_ZOOM_OUT", "WHEEL_ZOOM_EASE", "PINCH_ZOOM", "DBLCLICK_ZOOM_IN", "DBLRIGHTCLICK_ZOOM_OUT"]; private easyPzElements: { element: HTMLElement, settings: string, easypz: EasyPZ }[] = []; private static getSettingsFromString(settingsString) : { options: { minScale?: number, maxScale?: number, bounds?: { top: number, right: number, bottom: number, left: number } }, onPanned: () => void, onZoomed: () => void, onTransformed: () => void, onResetAbsoluteScale: () => void, modes: string[], applyTransformTo: string, replaceVariables: boolean, modeSettings: {[modeName: string]: {[settingName: string]: any}} } { let settings = { onPanned: () => {}, onZoomed: () => {}, onTransformed: () => {}, onResetAbsoluteScale: () => {}, options: {}, modes: EasyPZLoader.DEFAULT_MODES, applyTransformTo: '', replaceVariables: false, modeSettings: {} }; if(!!window['onPanned']) settings.onPanned = window['onPanned']; if(!!window['onZoomed']) settings.onZoomed = window['onZoomed']; if(!!window['onTransformed']) settings.onTransformed = window['onTransformed']; if(!!window['onResetAbsoluteScale']) settings.onResetAbsoluteScale = window['onResetAbsoluteScale']; let settingsObj = {}; try { if(settingsString && settingsString.length) { settingsObj = JSON.parse(settingsString); } else { settingsObj = {applyTransformTo: "svg > *"}; } } catch(e) { console.error('Could not parse EasyPZ settings: "' + settingsString + '"'); console.log(e); } const possibleOverrides = ['options', 'modes', 'onPanned', 'onZoomed', 'onTransformed', 'onResetAbsoluteScale', 'applyTransformTo', 'modeSettings']; for(let possibleOverride of possibleOverrides) { if(settingsObj[possibleOverride]) { settings[possibleOverride] = settingsObj[possibleOverride]; if(possibleOverride.substr(0,2) === 'on') { settings[possibleOverride] = window[settings[possibleOverride]]; } } } if(settingsObj['replaceVariables']) settings['replaceVariables'] = !!settingsObj['replaceVariables']; return settings; } public checkElements() { let els = <HTMLElement[]> Array.from(document.querySelectorAll('[easypz]')).concat( Array.from(document.querySelectorAll('[data-easypz]'))); const prevEls = this.easyPzElements.map(obj => obj.element); for(let i = 0; i < els.length; i++) { let el = els[i]; let settingsString = el.getAttribute('easypz') || el.dataset.easypz; const prevIndex = prevEls.indexOf(el); const prevObj = prevEls.indexOf(el) === -1 ? null : this.easyPzElements[prevIndex]; if(prevObj) { if(prevObj.settings === settingsString) { // Same element, same settings: Do nothing. continue; } else { // Same element, different settings: Update settings. console.log('Modifying EasyPZ'); } } else { console.log('Adding EasyPZ'); } let modes: string[] = []; let onPanned = function() {}; let onZoomed = function() {}; let onTransformed = function() {}; let onResetAbsoluteScale = function() {}; let options = {}; let applyTransformTo = ''; let modeSettings = {}; try { let settingsObj = EasyPZLoader.getSettingsFromString(settingsString); modes = settingsObj.modes; onPanned = settingsObj.onPanned; onZoomed = settingsObj.onZoomed; onTransformed = settingsObj.onTransformed; onResetAbsoluteScale = settingsObj.onResetAbsoluteScale; applyTransformTo = settingsObj.applyTransformTo; options = settingsObj.options; modeSettings = settingsObj.modeSettings; } catch(e) { console.error(e); } if(!prevObj) { const easypz = new EasyPZ(el, onTransformed, options, modes, modeSettings, onPanned, onZoomed, onResetAbsoluteScale, applyTransformTo); this.easyPzElements.push({ element: el, settings: settingsString, easypz: easypz }); } else { prevObj.settings = settingsString; prevObj.easypz.setSettings(onTransformed, options, modes, modeSettings, onPanned, onZoomed, onResetAbsoluteScale, applyTransformTo); } } } } class EzEventEmitter<T> { subscribers : ((value: T) => void)[] = []; public emit(value: T) { this.subscribers.forEach(subscriber => { subscriber(value); }); } public subscribe(subscriber: (value: T) => void) { this.subscribers.push(subscriber); } } class EzPromise<T> { private onDone: (T) => void; public then(callback: (T) => void) { this.onDone = callback; } private resolve(data: T) { if(this.onDone) { this.onDone(data); } } constructor(mainPart: (resolve: (T) => void, reject) => void) { mainPart((data: T) => { this.resolve(data);} , (data: T) => { this.resolve(data);}); } } class EasyPzZoomData { x: number; y: number; scaleChange?: number; absoluteScaleChange?: number; targetX?: number; targetY?: number; } class EasyPzPanData { x: number; y: number; } class EasyPzCallbackData { event; modeName; } class EasyPzMode { ids: string[]; active?: boolean; data?: any; settings: any; onClickTouch?: (eventData: EasyPzCallbackData) => void; onMove?: (eventData: EasyPzCallbackData) => void; onClickTouchEnd?: (eventData: EasyPzCallbackData) => void; onMultiTouch?: (eventData: EasyPzCallbackData) => void; onWheel?: (eventData: EasyPzCallbackData) => void; onRightClick?: (eventData: EasyPzCallbackData) => void; } class EasyPZ { private static MOUSE_EVENT_TYPES = {'MOUSE_DOWN': 0, 'MOUSE_MOVE': 1, 'MOUSE_UP': 2}; public lastMouseDownTime = 0; public mouseDownTime = 0; public mouseMoveTime = 0; public mouseUpTime = 0; public lastMousePos = {x: 0, y: 0}; public numberOfPointers = 0; public mousePos = {x: 0, y: 0}; private afterMouseMovedCallbacks : (() => void)[] = []; public height = 0; public width = 0; // Mobile devices call both touchend as well as mouseup on release. // However, there is a delay - touchend is called about 250 ms before mouseup. // These variables are used to prevent those mouseup events to be called if a // touchend event was just called. The same is true for mousedown and touchstart. private lastTouchEvent = 0; private static TOUCH_TO_COMPUTER_SWITCH_TIME_MS = 500; static DIMENSIONS = ['x', 'y']; private enabledModes = ["SIMPLE_PAN", "HOLD_ZOOM_IN", "CLICK_HOLD_ZOOM_OUT", "WHEEL_ZOOM", "PINCH_ZOOM", "DBLCLICK_ZOOM_IN", "DBLRIGHTCLICK_ZOOM_OUT"]; public onPanned = new EzEventEmitter<EasyPzPanData>(); public onZoomed = new EzEventEmitter<EasyPzZoomData>(); public resetAbsoluteScale = new EzEventEmitter<void>(); private totalTransform = { scale: 1, translateX: 0, translateY: 0}; private totalTransformSnapshot = { scale: 1, translateX: 0, translateY: 0}; public el: HTMLElement; private options = { minScale: 0.25, maxScale: 12, bounds: { top: -150, right: 150, bottom: 150, left: -150 } }; private listeners = { 'mousedown': this.onMouseDown.bind(this), 'touchstart': this.onTouchStart.bind(this), 'mousemove': this.onMouseMove.bind(this), 'touchmove': this.onTouchMove.bind(this), 'mouseup': this.onMouseUp.bind(this), 'mouseout': this.onMouseOut.bind(this), 'touchend': this.onTouchEnd.bind(this), 'contextmenu': this.onContextMenu.bind(this), 'wheel': this.onWheel.bind(this) }; constructor(el: Node|{node: () => HTMLElement}, onTransform: (transform: { scale: number, translateX: number, translateY: number}) => void = () => {}, options?: { minScale?: number, maxScale?: number, bounds?: { top: number, right: number, bottom: number, left: number } }, enabledModes?: string[], modeSettings: {[modeName: string]: {[settingName: string]: any}} = {}, onPanned: (panData: EasyPzPanData, transform: { scale: number, translateX: number, translateY: number}) => void = () => {}, onZoomed: (zoomData: EasyPzZoomData, transform: { scale: number, translateX: number, translateY: number}) => void = () => {}, onResetAbsoluteScale: () => void = () => {}, private applyTransformTo: string = '') { this.el = el instanceof Node ? <HTMLElement> el : el.node(); this.setSettings(onTransform, options, enabledModes, modeSettings, onPanned, onZoomed, onResetAbsoluteScale, applyTransformTo); this.ngAfterViewInit(); this.setupHostListeners(); } public setSettings(onTransform: (transform: { scale: number, translateX: number, translateY: number}) => void = () => {}, options?: { minScale?: number, maxScale?: number, bounds?: { top: number, right: number, bottom: number, left: number } }, enabledModes?: string[], modeSettings: {[modeName: string]: {[settingName: string]: any}} = {}, onPanned: (panData: EasyPzPanData, transform: { scale: number, translateX: number, translateY: number}) => void = () => {}, onZoomed: (zoomData: EasyPzZoomData, transform: { scale: number, translateX: number, translateY: number}) => void = () => {}, onResetAbsoluteScale: () => void = () => {}, applyTransformTo: string = '') { if(enabledModes) { this.enabledModes = enabledModes; } // Update modes in case they are different. this.modes = EasyPZ.modes.map(unresolvedMode => { return unresolvedMode(this); }); // Reset listeners. this.onPanned = new EzEventEmitter<EasyPzPanData>(); this.onZoomed = new EzEventEmitter<EasyPzZoomData>(); this.resetAbsoluteScale = new EzEventEmitter<void>(); this.applyModeSettings(modeSettings); if(options) { if(typeof options.minScale !== 'undefined') { this.options.minScale = options.minScale; } if(typeof options.maxScale !== 'undefined') { this.options.maxScale = options.maxScale; } if(typeof options.bounds !== 'undefined') { this.options.bounds = options.bounds; } } let transformBeforeScale = !applyTransformTo; this.trackTotalTransformation(onTransform, onPanned, onZoomed, transformBeforeScale); this.resetAbsoluteScale.subscribe(() => this.saveCurrentTransformation(onResetAbsoluteScale)); this.onPanned.subscribe(() => this.applyTransformation()); this.onZoomed.subscribe(() => this.applyTransformation()); } private saveCurrentTransformation(onResetAbsoluteScale) { this.totalTransformSnapshot = { scale: this.totalTransform.scale, translateX: this.totalTransform.translateX, translateY: this.totalTransform.translateY }; onResetAbsoluteScale(); } private trackTotalTransformation(onTransform, onPanned, onZoomed, transformBeforeScale) { this.onPanned.subscribe((panData: EasyPzPanData) => { if(transformBeforeScale) { this.totalTransform.translateX += panData.x; this.totalTransform.translateY += panData.y; } else { this.totalTransform.translateX += panData.x / this.totalTransform.scale; this.totalTransform.translateY += panData.y / this.totalTransform.scale; } this.ensureTransformWithinBounds(transformBeforeScale); onPanned(panData, this.totalTransform); onTransform(this.totalTransform); }); this.onZoomed.subscribe((zoomData: EasyPzZoomData) => { // Zoom either relative to the current transformation, or to the saved snapshot. const zoomDataScaleChange = zoomData.scaleChange ? zoomData.scaleChange : 1; let relativeTransform = zoomData.absoluteScaleChange ? this.totalTransformSnapshot : this.totalTransform; let scaleChange = zoomData.absoluteScaleChange ? 1 / zoomData.absoluteScaleChange : 1 / zoomDataScaleChange; let scalePrev = zoomData.absoluteScaleChange ? this.totalTransformSnapshot.scale : this.totalTransform.scale; this.totalTransform.scale = this.getScaleWithinLimits(relativeTransform.scale * scaleChange); scaleChange = this.totalTransform.scale / scalePrev; if(transformBeforeScale) { this.totalTransform.translateX = (relativeTransform.translateX - zoomData.x) / scalePrev * this.totalTransform.scale + zoomData.x; this.totalTransform.translateY = (relativeTransform.translateY - zoomData.y) / scalePrev * this.totalTransform.scale + zoomData.y; if(zoomData.targetX && zoomData.targetY) { this.totalTransform.translateX += (zoomData.targetX - zoomData.x) / scalePrev * this.totalTransform.scale; this.totalTransform.translateY += (zoomData.targetY - zoomData.y) / scalePrev * this.totalTransform.scale; } } else { let posBefore = {x: zoomData.x , y: zoomData.y }; let posAfter = {x: posBefore.x * scaleChange, y: posBefore.y * scaleChange}; let relative = {x: posAfter.x - posBefore.x, y: posAfter.y - posBefore.y}; this.totalTransform.translateX = relativeTransform.translateX - relative.x / this.totalTransform.scale; this.totalTransform.translateY = relativeTransform.translateY - relative.y / this.totalTransform.scale; if(zoomData.targetX && zoomData.targetY) { this.totalTransform.translateX += (zoomData.targetX - zoomData.x) / this.totalTransform.scale; this.totalTransform.translateY += (zoomData.targetY - zoomData.y) / this.totalTransform.scale; } } this.ensureTransformWithinBounds(transformBeforeScale); onZoomed(zoomData, this.totalTransform); onTransform(this.totalTransform); }); } private getScaleWithinLimits(scale: number) : number { if(!isNaN(this.options.minScale) && this.options.minScale !== null) { scale = scale > this.options.minScale ? scale : this.options.minScale; } if(!isNaN(this.options.maxScale) && this.options.maxScale !== null) { scale = scale < this.options.maxScale ? scale : this.options.maxScale; } return scale; } private ensureTransformWithinBounds(transformBeforeScale) { if(this.options.bounds) { let scale = transformBeforeScale ? this.totalTransform.scale - 1 : 1 - 1 / this.totalTransform.scale; let scaleTopLeft = -1 * Math.max(scale, 0); let scaleBotRight = -1 * Math.min(scale, 0); if(this.totalTransform.translateX < scaleTopLeft * this.width + this.options.bounds.left) { this.totalTransform.translateX = scaleTopLeft * this.width + this.options.bounds.left; } if(this.totalTransform.translateX > scaleBotRight * this.width + this.options.bounds.right) { this.totalTransform.translateX = scaleBotRight * this.width + this.options.bounds.right; } if(this.totalTransform.translateY < scaleTopLeft * this.height + this.options.bounds.top) { this.totalTransform.translateY = scaleTopLeft * this.height + this.options.bounds.top; } if(this.totalTransform.translateY > scaleBotRight * this.height + this.options.bounds.bottom) { this.totalTransform.translateY = scaleBotRight * this.height + this.options.bounds.bottom; } } } private lastAppliedTransform = { translateX: 0, translateY: 0, scale: 1 }; private applyTransformation() { if(this.applyTransformTo) { let els = this.el.querySelectorAll(this.applyTransformTo); for(let i = 0; i < els.length; i++) { const element = els[i]; const transform = element.getAttribute('transform') || ''; let transformData = EasyPZ.parseTransform(transform); let translateX = this.totalTransform.translateX; let translateY = this.totalTransform.translateY; let scaleX = this.totalTransform.scale; let scaleY = this.totalTransform.scale; if(transformData) { const originalScaleX = transformData.scaleX / this.lastAppliedTransform.scale; const originalScaleY = transformData.scaleY / this.lastAppliedTransform.scale; const originalTranslate = { x: 0, y: 0 }; const translateBeforeScaleFactorX = transformData.translateBeforeScale ? 1 : originalScaleX; const translateBeforeScaleFactorY = transformData.translateBeforeScale ? 1 : originalScaleY; originalTranslate.x = (transformData.translateX - this.lastAppliedTransform.translateX / originalScaleX) * translateBeforeScaleFactorX; originalTranslate.y = (transformData.translateY - this.lastAppliedTransform.translateY / originalScaleY) * translateBeforeScaleFactorY; // console.log(originalTranslate.x, transformData.translateX , this.lastAppliedTransform.translateX, originalScale, this.lastAppliedTransform.scale, this.lastAppliedTransform.lastScale, transformData.translateBeforeScale); scaleX *= originalScaleX; scaleY *= originalScaleY; translateX = translateX / originalScaleX + originalTranslate.x / originalScaleX; translateY = translateY / originalScaleY + originalTranslate.y / originalScaleY; } else { console.log('what is wrong', transform); } let transformString = ''; if(transformData.rotate) { transformString += 'rotate(' + transformData.rotate + ')'; } if(transformData.skewX) { transformString += 'skewX(' + transformData.skewX + ')'; } if(transformData.skewY) { transformString += 'skewY(' + transformData.skewY + ')'; } transformString += 'scale(' + scaleX + ',' + scaleY + ')'; transformString += 'translate(' + translateX + ',' + translateY + ')'; element.setAttribute('transform', transformString); } this.lastAppliedTransform.translateX = this.totalTransform.translateX; this.lastAppliedTransform.translateY = this.totalTransform.translateY; this.lastAppliedTransform.scale = this.totalTransform.scale; } } private static parseTransform(transform: string) { const transformObject = { translateX: 0, translateY: 0, scaleX: 1, scaleY: 1, translateBeforeScale: false, rotate: '', skewX: '', skewY: ''}; if(transform) { transform = transform.replace(/(\r\n|\n|\r)/gm,''); let recognized = false; const translate = /\s*translate\(([-0-9.]+),\s*([-0-9.]+)\)/.exec(transform); if(translate) { transformObject.translateX = parseFloat(translate[1]); transformObject.translateY = parseFloat(translate[2]); recognized = true; } const scale = /\s*scale\(([-0-9.]+)(,\s*([-0-9.]+))?\)/.exec(transform); if(scale) { transformObject.scaleX = parseFloat(scale[1]); transformObject.scaleY = scale[3] ? parseFloat(scale[3]) : parseFloat(scale[1]); recognized = true; } const translateScale = /\s*translate\(([-0-9.]+),\s*([-0-9.]+)\)[ ]*scale\(([-0-9.]+(,\s*[-0-9.]+)?)\)/.exec(transform); if(translateScale) { transformObject.translateBeforeScale = true; } const rotate = /\s*rotate\(([-0-9., ]*)\)/.exec(transform); if(rotate) { transformObject.rotate = rotate[1]; recognized = true; } const skewX = /\s*skewX\(([-0-9., ]*)\)/.exec(transform); if(skewX) { transformObject.skewX = skewX[1]; recognized = true; } const skewY = /\s*skewY\(([-0-9., ]*)\)/.exec(transform); if(skewY) { transformObject.skewY = skewY[1]; recognized = true; } if(!recognized) { console.error('No transformation recognized in: ', transform); } } return transformObject; } private ngAfterViewInit() { this.setDimensions(); } private setDimensions() { let rect = this.el.getBoundingClientRect(); this.width = rect.width; this.height = rect.height; } private updateMousePosition(event: MouseEvent|TouchEvent) : void { let pos = this.getMousePosition(event); if(pos) { this.mousePos = pos; } } private getMousePosition(event: MouseEvent|TouchEvent) : {x: number, y: number}|null { let pos = {x: 0, y: 0}; //if(event instanceof MouseEvent && event.clientX) if(event.type.substr(0,5) === 'mouse' && event['clientX']) { pos = {x: event['clientX'], y: event['clientY']}; this.numberOfPointers = 1; } //else if(event instanceof TouchEvent) else if(event.type.substr(0,5) === 'touch') { const touches = event['touches'] ? event['touches'] : []; this.numberOfPointers = touches.length; if(touches.length < 1) return null; pos = {x: touches[0].clientX, y: touches[0].clientY}; } return this.getRelativePosition(pos.x, pos.y); } public getRelativePosition(x: number, y: number) : {x: number, y: number} { let boundingRect = this.el.getBoundingClientRect(); this.width = boundingRect.width; this.height = boundingRect.height; return { x: x - boundingRect.left, y: y - boundingRect.top }; } private onMouseTouchDown(mouseEvent: MouseEvent|null, touchEvent?: TouchEvent) { this.lastMouseDownTime = this.mouseDownTime; this.lastMousePos = {x: this.mousePos.x, y: this.mousePos.y}; this.mouseDownTime = Date.now(); let event = mouseEvent || touchEvent; if(!event) { return console.error('no event!'); } this.updateMousePosition(event); let eventType = EasyPZ.MOUSE_EVENT_TYPES.MOUSE_DOWN; this.onMouseTouchEvent(eventType, event); } private setupHostListeners() { for(const [listenerName, listenerFct] of Object.entries(this.listeners)) { this.el.addEventListener(listenerName, listenerFct); } } removeHostListeners() { for(const [listenerName, listenerFct] of Object.entries(this.listeners)) { this.el.removeEventListener(listenerName, listenerFct); } } private onMouseDown(event: MouseEvent) { if(Date.now() - this.lastTouchEvent > EasyPZ.TOUCH_TO_COMPUTER_SWITCH_TIME_MS) { this.onMouseTouchDown(event); } } private onTouchStart(event: TouchEvent) { this.lastTouchEvent = Date.now(); let eventType = EasyPZ.MOUSE_EVENT_TYPES.MOUSE_DOWN; if(event.touches.length == 1) { this.onMouseTouchDown(null, event); } else if(event.touches.length == 2) { this.updateMousePosition(event); this.onMultiTouchEvent(eventType, event); event.preventDefault(); } } private onMouseTouchMove(mouseEvent: MouseEvent|null, touchEvent?: TouchEvent) : boolean { this.mouseMoveTime = Date.now(); this.lastMousePos = {x: this.mousePos.x, y: this.mousePos.y}; let event = mouseEvent || touchEvent; if(!event) { console.error('no event'); return false; } this.updateMousePosition(event); let eventType = EasyPZ.MOUSE_EVENT_TYPES.MOUSE_MOVE; let eventWasUsed = this.onMouseTouchEvent(eventType, event); for(let cb of this.afterMouseMovedCallbacks) { cb(); } return eventWasUsed; } private onMouseMove(event: MouseEvent) { this.onMouseTouchMove(event); } private onTouchMove(event: TouchEvent) { if(event.touches.length == 1) { const eventWasUsed = this.onMouseTouchMove(null, event); if(eventWasUsed) { event.preventDefault(); } } else if(event.touches.length == 2) { this.updateMousePosition(event); let eventType = EasyPZ.MOUSE_EVENT_TYPES.MOUSE_MOVE; this.onMultiTouchEvent(eventType, event); event.preventDefault(); } } private static modes : ((easyPZ: EasyPZ) => EasyPzMode)[] = []; private modes : EasyPzMode[] = []; public static addMode(unresolvedMode: (easyPZ: EasyPZ) => EasyPzMode) { EasyPZ.modes.push(unresolvedMode); } private getEventData(event, modeName) : EasyPzCallbackData { return { event: event, modeName: modeName }; } private getActiveModes() { let modes : { mode: EasyPzMode, activeId: string}[] = []; this.modes.forEach(mode => { mode.ids.forEach(modeId => { if(this.enabledModes.indexOf(modeId) !== -1) { modes.push({ mode: mode, activeId: modeId }); } }); }); return modes; } private onMultiTouchEvent(eventType: number, event: TouchEvent) { this.getActiveModes().forEach(modeData => { if(eventType === EasyPZ.MOUSE_EVENT_TYPES.MOUSE_MOVE && modeData.mode.onMove) modeData.mode.onMove(this.getEventData(event, modeData.activeId)); else if(eventType === EasyPZ.MOUSE_EVENT_TYPES.MOUSE_DOWN && modeData.mode.onClickTouch) modeData.mode.onClickTouch(this.getEventData(event, modeData.activeId)); else if(eventType === EasyPZ.MOUSE_EVENT_TYPES.MOUSE_UP && modeData.mode.onClickTouchEnd) modeData.mode.onClickTouchEnd(this.getEventData(event, modeData.activeId)); }); } private onMouseTouchUp(mouseEvent: MouseEvent|null, touchEvent?: TouchEvent) { this.mouseUpTime = Date.now(); this.lastMousePos = {x: this.mousePos.x, y: this.mousePos.y}; let event = mouseEvent || touchEvent; if(!event) { return console.error('no event'); } this.updateMousePosition(event); let eventType = EasyPZ.MOUSE_EVENT_TYPES.MOUSE_UP; this.onMouseTouchEvent(eventType, event); } private onMouseTouchEvent(eventType: number, event: MouseEvent|TouchEvent) { let eventWasUsed = false; if(EasyPZ.isRightClick(event)) { if(eventType === EasyPZ.MOUSE_EVENT_TYPES.MOUSE_DOWN) { //TODO should check if it uses the event. this.onRightClick(eventType, event); } return eventWasUsed; } this.getActiveModes().forEach(modeData => { if(eventType === EasyPZ.MOUSE_EVENT_TYPES.MOUSE_MOVE && modeData.mode.onMove) modeData.mode.onMove(this.getEventData(event, modeData.activeId)); else if(eventType === EasyPZ.MOUSE_EVENT_TYPES.MOUSE_DOWN && modeData.mode.onClickTouch) modeData.mode.onClickTouch(this.getEventData(event, modeData.activeId)); else if(eventType === EasyPZ.MOUSE_EVENT_TYPES.MOUSE_UP && modeData.mode.onClickTouchEnd) modeData.mode.onClickTouchEnd(this.getEventData(event, modeData.activeId)); eventWasUsed = true; /*if(modeData.mode.active) { eventWasUsed = true; }*/ }); return eventWasUsed; } private onMouseUp(event: MouseEvent) { if(Date.now() - this.lastTouchEvent > EasyPZ.TOUCH_TO_COMPUTER_SWITCH_TIME_MS) { this.onMouseTouchUp(event); } } private onMouseOut(event: MouseEvent) { // The problem with this is that it detects mouseout events of elements within this element, // not only of mouseout events of the main element itself. This is why a pointer position check is done // to see if the user has actually left the visualization. let pos = this.getMousePosition(event); if(pos && (pos.x < 0 || pos.x > this.width || pos.y < 0 || pos.y > this.height)) { this.onMouseTouchUp(event); } } private onTouchEnd(event: TouchEvent) { // Touch End always has zero touch positions, so the pointer position can not be used here. this.lastTouchEvent = Date.now(); let eventType = EasyPZ.MOUSE_EVENT_TYPES.MOUSE_UP; this.onMouseTouchUp(null, event); this.onMultiTouchEvent(eventType, event); } private onContextMenu() { /*if(this.modeOn(EasyPZ.MODES.DBLRIGHTCLICK_ZOOM_IN) || this.modeOn(EasyPZ.MODES.DBLRIGHTCLICK_ZOOM_OUT)) { event.preventDefault(); return false; }*/ } private onWheel(event: WheelEvent) { let captured = false; this.getActiveModes().forEach(modeData => { if(modeData.mode.onWheel) { modeData.mode.onWheel(this.getEventData(event, modeData.activeId)); captured = true; } }); if(captured) { event.preventDefault(); } } private onRightClick(eventType: number, event: MouseEvent|TouchEvent) { this.getActiveModes().forEach(modeData => { if(modeData.mode.onRightClick) { modeData.mode.onRightClick(this.getEventData(event, modeData.activeId)); } }); } private applyModeSettings(modeSettings: {[modeName: string]: {[settingName: string]: any}} = {}) { const modeNames = Object.keys(modeSettings); if(modeNames && modeNames.length) { for(const modeName of modeNames) { const modes = this.modes.filter(m => m.ids.indexOf(modeName) !== -1); if (modes.length !== 1) { console.error('Trying to set a setting for an easypz mode that does not exist', modeName); } else { const mode = modes[0]; const newSettings = modeSettings[modeName]; for(const settingName in newSettings) { if(!mode.settings[settingName]) { console.error('Trying to set a setting for the easypz mode ', modeName, ', but this setting does not exist: ', settingName); } else { mode.settings[settingName] = newSettings[settingName]; } } } } } } public static easeInteraction(maxSpeed: number, duration: number, onStep: (data: {speed?: number, timePassed?: number, dist?: number}) => void) { return EasyPZ.momentumInteraction(onStep, (timePassed) => { return maxSpeed - Math.pow((timePassed - duration / 2), 2) / (Math.pow(duration, 2) / (4 * maxSpeed)); }, duration); } public static frictionInteraction(maxSpeed : number, friction : number, onStep: (data: {speed?: number, timePassed?: number, dist?: number}) => void) { return EasyPZ.momentumInteraction(onStep, (timePassed) => { return Math.max(0, maxSpeed - friction * timePassed); }, maxSpeed / friction); } public static momentumInteraction(onStep: (data: {speed?: number, timePassed?: number, dist?: number}) => void, speedFct: (timePassed: number) => number, duration: number) { let startTime = Date.now(); let lastMoveTime = Date.now(); let continueInteraction = () => { const timePassed = Date.now() - startTime; let speed = speedFct(timePassed); if(timePassed < duration) { const timePassed = Date.now() - lastMoveTime; const dist = timePassed * speed; onStep({speed, timePassed, dist}); lastMoveTime = Date.now(); requestAnimationFrame(continueInteraction); } }; return { start : function() { requestAnimationFrame(continueInteraction); }, stop : function() { startTime = 0; } } } public static momentumInteractionOld(onStep : (dist) => void, speedFct: (timePassed: number) => number, duration: number) { let startTime = Date.now(); let lastMoveTime = Date.now(); let continueInteraction = () => { const timePassed = Date.now() - startTime; let speed = speedFct(timePassed); if(timePassed < duration) { let dist = (Date.now() - lastMoveTime) * speed; onStep(dist); lastMoveTime = Date.now(); requestAnimationFrame(continueInteraction); } }; return { start : function() { requestAnimationFrame(continueInteraction); }, stop : function() { startTime = 0; } } } /* Useful functions */ static isRightClick(event: MouseEvent|TouchEvent): boolean { return event instanceof MouseEvent && (!!event.clientX) && (("which" in event && event.which === 3) || ("button" in event && event.button === 2)); } static getPositionDistance(pos1: {x: number, y: number}, pos2: {x: number, y: number}) { return Math.sqrt(Math.pow(pos2.x - pos1.x, 2) + Math.pow(pos2.y - pos1.y, 2)); } callbackAfterTimeoutOrMovement(timeout: number, movement: number) : EzPromise<number> { return new EzPromise<number>((resolve) => { let resolved = false; let currentPos = {x: this.mousePos.x, y: this.mousePos.y}; let index = this.afterMouseMovedCallbacks.length; this.afterMouseMovedCallbacks.push(() => { let dist = EasyPZ.getPositionDistance(currentPos, this.mousePos); if(dist > movement && !resolved) { //console.log('resolved after ', dist , ' px'); this.afterMouseMovedCallbacks.splice(index, 1); resolved = true; resolve(dist); } }); setTimeout(() => { if(!resolved) { let dist = EasyPZ.getPositionDistance(currentPos, this.mousePos); //console.log('resolved after ', timeout , ' ms'); this.afterMouseMovedCallbacks.splice(index, 1); resolved = true; resolve(dist); } }, timeout); }); } } /* Simple Pan*/ EasyPZ.addMode((easypz: EasyPZ) => { const mode = { ids: ['SIMPLE_PAN'], settings: { minDistance: 3, delay: 300 }, active: false, data: {lastPosition: {x: 0, y: 0}}, onClickTouch: () => { mode.active = false; mode.data.lastPosition = {x: easypz.mousePos.x, y: easypz.mousePos.y}; easypz.callbackAfterTimeoutOrMovement(mode.settings.delay, mode.settings.minDistance).then((dist) => { mode.active = easypz.mouseUpTime < easypz.mouseDownTime && dist >= mode.settings.minDistance; }); }, onMove: () => { if(mode.active) { let relativeX = easypz.mousePos.x - mode.data.lastPosition.x; let relativeY = easypz.mousePos.y - mode.data.lastPosition.y; easypz.onPanned.emit({x: relativeX, y: relativeY}); mode.data.lastPosition = {x: easypz.mousePos.x, y: easypz.mousePos.y}; } }, onClickTouchEnd: () => { mode.active = false; } }; return mode; }); /* Flick Pan */ EasyPZ.addMode((easypz: EasyPZ) => { const mode = { ids: ['FLICK_PAN'], settings: { minDistance: 3, delay: 300, friction: 0.005 }, active: false, data: { continueTime: 0, positions: [], momentum: null }, onClickTouch: () => { mode.active = false; mode.data.positions = [{x: easypz.mousePos.x, y: easypz.mousePos.y, time: Date.now()}]; if(mode.data.momentum) { mode.data.momentum.stop(); } easypz.callbackAfterTimeoutOrMovement(mode.settings.delay, mode.settings.minDistance).then((dist) => { mode.active = easypz.mouseUpTime < easypz.mouseDownTime && dist >= mode.settings.minDistance; }); }, onMove: () => { if(mode.active) { let relativeX = easypz.mousePos.x - easypz.lastMousePos.x; let relativeY = easypz.mousePos.y - easypz.lastMousePos.y; easypz.onPanned.emit({x: relativeX, y: relativeY}); mode.data.positions.push({x: easypz.mousePos.x, y: easypz.mousePos.y, time: Date.now()}); } }, onClickTouchEnd: () => { if(mode.active) { mode.active = false; let referencePoints = mode.data.positions.filter(flickPos => { return flickPos.time >= Date.now() - 100 && flickPos.time <= Date.now() - 50; }); if(referencePoints.length == 0) return; let refPoint = referencePoints[0]; let dist = EasyPZ.getPositionDistance({x: refPoint.x, y: refPoint.y}, easypz.mousePos); let flickDirection = {x: (easypz.mousePos.x - refPoint.x) / dist, y: (easypz.mousePos.y - refPoint.y) / dist}; let time = Date.now() - refPoint.time; let speed = dist / time; mode.data.momentum = EasyPZ.frictionInteraction(speed, mode.settings.friction, ({dist}) => { let relativeMove = {x: flickDirection.x * dist, y: flickDirection.y * dist }; easypz.onPanned.emit(relativeMove); }); mode.data.momentum.start(); } } }; return mode; }); /* Hold Zoom */ EasyPZ.addMode((easypz: EasyPZ) => { const mode = { ids: ['HOLD_ZOOM_IN', 'HOLD_ZOOM_OUT', 'CLICK_HOLD_ZOOM_IN', 'CLICK_HOLD_ZOOM_OUT'], settings: { maxDistance: 3, delay: 350, zoomInScaleChangePerMs: -0.0015, zoomOutScaleChangePerMs: 0.003, doubleClickTimeout: 300 }, active: false, data: { zoomingOut: false, zoomPos: {x: 0, y: 0} }, onClickTouch: (eventData: EasyPzCallbackData) => { let holdZoomLastChange; let recursiveZoom = () => { if(mode.active) { let timePassed = Date.now() - holdZoomLastChange; let scaleChangePerMs = mode.data.zoomingOut ? mode.settings.zoomOutScaleChangePerMs : mode.settings.zoomInScaleChangePerMs; let scale = 1 + scaleChangePerMs * timePassed; easypz.onZoomed.emit({x: mode.data.zoomPos.x, y: mode.data.zoomPos.y, scaleChange: scale}); holdZoomLastChange = Date.now(); requestAnimationFrame(recursiveZoom); } }; // If the pointer is moved within the first 300ms, it is not considered zooming. easypz.callbackAfterTimeoutOrMovement(mode.settings.delay, mode.settings.maxDistance).then((dist) => { mode.active = easypz.mouseUpTime < easypz.mouseDownTime && dist <= mode.settings.maxDistance; if(mode.active) { holdZoomLastChange = Date.now(); let hasClickedFirst = easypz.mouseDownTime - easypz.lastMouseDownTime < mode.settings.doubleClickTimeout; mode.data.zoomPos = {x: easypz.mousePos.x, y: easypz.mousePos.y}; // start zooming let clickFirst = eventData.modeName === 'CLICK_HOLD_ZOOM_IN' || eventData.modeName === 'CLICK_HOLD_ZOOM_OUT'; if(hasClickedFirst == clickFirst) { mode.data.zoomingOut = eventData.modeName === 'HOLD_ZOOM_OUT' || eventData.modeName === 'CLICK_HOLD_ZOOM_OUT'; recursiveZoom(); } } }); }, onMove: () => { if(mode.active) { mode.data.zoomPos = {x: easypz.mousePos.x, y: easypz.mousePos.y}; } }, onClickTouchEnd: () => { mode.active = false; } }; return mode; }); /* Double Click Zoom */ EasyPZ.addMode((easypz: EasyPZ) => { const mode = { ids: ['DBLCLICK_ZOOM_IN', 'DBLCLICK_ZOOM_OUT', 'DBLRIGHTCLICK_ZOOM_IN', 'DBLRIGHTCLICK_ZOOM_OUT'], settings: { dblClickTime: 300, zoomInScaleChange: 0.33, zoomOutScaleChange: 3, maxHoldTime: 200 }, onClickTouchEnd: (eventData: EasyPzCallbackData) => { let isDblClick = easypz.mouseDownTime - easypz.lastMouseDownTime < mode.settings.dblClickTime; let isHold = easypz.mouseUpTime - easypz.mouseDownTime > mode.settings.maxHoldTime; let isNotRightClick = eventData.modeName.substr(0, 'DBLCLICK'.length) === 'DBLCLICK'; if (isDblClick && !isHold && isNotRightClick) { const zoomingOut = eventData.modeName === 'DBLCLICK_ZOOM_OUT'; let scaleChange = zoomingOut ? mode.settings.zoomOutScaleChange : mode.settings.zoomInScaleChange; easypz.onZoomed.emit({x: easypz.mousePos.x, y: easypz.mousePos.y, scaleChange: scaleChange}); } }, onRightClick: (eventData: EasyPzCallbackData) => { let isDblClick = easypz.mouseDownTime - easypz.lastMouseDownTime < mode.settings.dblClickTime; let isHold = easypz.mouseUpTime - easypz.mouseDownTime > mode.settings.maxHoldTime; let isRightClick = eventData.modeName.substr(0, 'DBLRIGHTCLICK'.length) === 'DBLRIGHTCLICK'; if (isDblClick && !isHold && isRightClick) { const zoomingOut = eventData.modeName === 'DBLRIGHTCLICK_ZOOM_OUT'; let scaleChange = zoomingOut ? mode.settings.zoomOutScaleChange : mode.settings.zoomInScaleChange; easypz.onZoomed.emit({x: easypz.mousePos.x, y: easypz.mousePos.y, scaleChange: scaleChange}); } } }; return mode; }); /* Wheel Zoom */ EasyPZ.addMode((easypz: EasyPZ) => { const mode = { ids: ['WHEEL_ZOOM', 'WHEEL_ZOOM_MOMENTUM', 'WHEEL_ZOOM_EASE'], settings: { zoomInScaleChange: 0.8, zoomOutScaleChange: 1.2, momentumSpeedPercentage: 0.01, momentumFriction: 0.000004, easeDuration: 300 }, onWheel: (eventData: EasyPzCallbackData) => { const delta = eventData.event.wheelDelta ? eventData.event.wheelDelta : -1 * eventData.event.deltaY; const change = delta / Math.abs(delta); const zoomingIn = change > 0; let scale = zoomingIn ? mode.settings.zoomInScaleChange : mode.settings.zoomOutScaleChange; let relativeScale = 1 - scale; let absScale = Math.abs(relativeScale) * mode.settings.momentumSpeedPercentage; let scaleSign = sign(relativeScale); if(eventData.modeName === 'WHEEL_ZOOM_EASE') { this.zoomMomentum = EasyPZ.easeInteraction(absScale, mode.settings.easeDuration, ({dist}) => { let newScale = 1 - scaleSign * dist; easypz.onZoomed.emit({x: easypz.mousePos.x, y: easypz.mousePos.y, scaleChange: newScale}); }); this.zoomMomentum.start(); } else { easypz.onZoomed.emit({x: easypz.mousePos.x, y: easypz.mousePos.y, scaleChange: scale}); if(eventData.modeName === 'WHEEL_ZOOM_MOMENTUM') { this.flickMomentum = EasyPZ.frictionInteraction(absScale, mode.settings.momentumFriction, ({dist}) => { let newScale = 1 - scaleSign * dist; easypz.onZoomed.emit({x: easypz.mousePos.x, y: easypz.mousePos.y, scaleChange: newScale}); }); this.flickMomentum.start(); } } } }; return mode; }); /* Pinch Zoom and Pan */ EasyPZ.addMode((easypz: EasyPZ) => { const mode = { ids: ['PINCH_ZOOM', 'PINCH_ZOOM_QUADRATIC', 'PINCH_ZOOM_POWER_FOUR', 'PINCH_ZOOM_MOMENTUM', 'PINCH_PAN'], settings: { friction: 0.00001 }, data: { momentum: null, posStart1: null, posStart2: null, references: [], zoomPos: {x: 0, y: 0}, zoomCenterPos: {x: 0, y: 0} }, onClickTouch(eventData: EasyPzCallbackData) { if(mode.data.momentum) { mode.data.momentum.stop(); } mode.data.references = []; if(eventData.event.touches && eventData.event.touches.length > 1) { mode.data.posStart1 = easypz.getRelativePosition(eventData.event.touches[0].clientX, eventData.event.touches[0].clientY); mode.data.posStart2 = easypz.getRelativePosition(eventData.event.touches[1].clientX, eventData.event.touches[1].clientY); easypz.resetAbsoluteScale.emit(null); } }, onMove(eventData: EasyPzCallbackData) { if(mode.data.posStart1 && mode.data.posStart2) { const pos1 = easypz.getRelativePosition(eventData.event.touches[0].clientX, eventData.event.touches[0].clientY); const pos2 = easypz.getRelativePosition(eventData.event.touches[1].clientX, eventData.event.touches[1].clientY); const distBefore = EasyPZ.getPositionDistance(mode.data.posStart1, mode.data.posStart2); const distNow = EasyPZ.getPositionDistance(pos1, pos2); const ratio = distBefore / distNow; let power = 1; if(eventData.modeName === 'PINCH_ZOOM_QUADRATIC') power = 2; if(eventData.modeName === 'PINCH_ZOOM_POWER_FOUR') power = 4; if(eventData.modeName === 'PINCH_PAN') power = 0; const scale = Math.pow(ratio, power); mode.data.references.push({time: Date.now(), scale}); mode.data.zoomPos = {x: (mode.data.posStart1.x + mode.data.posStart2.x) / 2, y: (mode.data.posStart1.y + mode.data.posStart2.y) / 2}; mode.data.zoomCenterPos = {x: (pos1.x + pos2.x) / 2, y: (pos1.y + pos2.y) / 2}; easypz.onZoomed.emit({x: mode.data.zoomPos.x, y: mode.data.zoomPos.y, absoluteScaleChange: scale, targetX: mode.data.zoomCenterPos.x, targetY: mode.data.zoomCenterPos.y}); } }, onClickTouchEnd(eventData: EasyPzCallbackData) { mode.data.posStart1 = null; mode.data.posStart1 = null; if(eventData.modeName === 'PINCH_ZOOM_MOMENTUM' && mode.data.references.length > 5) { let refLast = mode.data.references[mode.data.references.length-1]; let ref = mode.data.references[mode.data.references.length-4]; let refTimeDiff = refLast.time - ref.time; let refScaleDiff = refLast.scale - ref.scale; let lastScale = refLast.scale; let scaleChangeSpeed = refScaleDiff / refTimeDiff; let absScaleChangeSpeed = Math.abs(scaleChangeSpeed); let scaleSign = sign(scaleChangeSpeed); mode.data.momentum = EasyPZ.frictionInteraction(absScaleChangeSpeed, mode.settings.friction, ({dist}) => { let newScale = lastScale + scaleSign * dist; easypz.onZoomed.emit({x: this.pinchZoomPos.x, y: this.pinchZoomPos.y, absoluteScaleChange: newScale, targetX: this.pinchZoomCenterPos.x, targetY: this.pinchZoomCenterPos.y}); lastScale = newScale; }); mode.data.momentum.start(); } } }; return mode; }); /* Wheel Pan */ EasyPZ.addMode((easypz: EasyPZ) => { const mode = { ids: ['WHEEL_PAN_X', 'WHEEL_PAN_Y'], settings: { speed: 50 }, onWheel: (eventData: EasyPzCallbackData) => { const delta = eventData.event.wheelDelta ? eventData.event.wheelDelta : -1 * eventData.event.deltaY; let change = delta / Math.abs(delta); let zoomingIn = change > 0; let sign = zoomingIn ? 1 : -1; let panned = {x: 0, y: 0}; const direction = eventData.modeName === 'WHEEL_PAN_X' ? 'x' : 'y'; panned[direction] = mode.settings.speed * sign; easypz.onPanned.emit(panned); } }; return mode; }); /* Brush Zoom */ EasyPZ.addMode((easypz: EasyPZ) => { const mode = { ids: ['BRUSH_ZOOM', 'BRUSH_ZOOM_X', 'BRUSH_ZOOM_Y'], settings: { minDistance: 3, delay: 300, minTime: 150 }, active: false, data: { startPos: {x: 0, y: 0}, el: null }, onClickTouch: () => { if(easypz.numberOfPointers !== 1) { mode.active = false; if(mode.data.el) { mode.data.el.style.display = 'none'; } } else { mode.active = true; if(!mode.data.el) { mode.data.el = document.createElement('div'); mode.data.el.style.border = '1px solid #c00'; mode.data.el.style.background = 'rgba(200,50,50,0.3)'; mode.data.el.style.position = 'absolute'; document.body.appendChild(mode.data.el); } //this.brushZoomDirection = direction; mode.data.startPos = {x: easypz.mousePos.x, y: easypz.mousePos.y}; easypz.callbackAfterTimeoutOrMovement(mode.settings.delay, mode.settings.minDistance).then((dist) => { mode.active = easypz.numberOfPointers == 1 && dist > mode.settings.minDistance; if(!mode.active && mode.data.el) mode.data.el.style.display = 'none'; }); setTimeout(() => { if(easypz.numberOfPointers !== 1) { mode.active = false; if(mode.data.el) mode.data.el.style.display = 'none'; } }, mode.settings.delay); } }, onMove: (eventData) => { if(easypz.numberOfPointers !== 1) { mode.active = false; if(mode.data.el) mode.data.el.style.display = 'none'; } if(mode.active) { let left = easypz.mousePos.x < mode.data.startPos.x ? easypz.mousePos.x : mode.data.startPos.x; let width = Math.abs(mode.data.startPos.x - easypz.mousePos.x); let top = easypz.mousePos.y < mode.data.startPos.y ? easypz.mousePos.y : mode.data.startPos.y; let height = Math.abs(mode.data.startPos.y - easypz.mousePos.y); if(eventData.modeName === 'BRUSH_ZOOM_X') { top = easypz.el.getBoundingClientRect().top; height = easypz.height; } else if(eventData.modeName === 'BRUSH_ZOOM_Y') { left = easypz.el.getBoundingClientRect().left; width = easypz.width; } mode.data.el.style.display = 'block'; mode.data.el.style.left = left + 'px'; mode.data.el.style.top = top + 'px'; mode.data.el.style.width = width + 'px'; mode.data.el.style.height = height + 'px'; } }, onClickTouchEnd: (eventData: EasyPzCallbackData) => { if(mode.active) { mode.active = false; mode.data.el.style.display = 'none'; if(Date.now() - easypz.mouseDownTime > mode.settings.minTime) { let middle = {x: mode.data.startPos.x + (easypz.mousePos.x - mode.data.startPos.x) / 2, y: mode.data.startPos.y + (easypz.mousePos.y - mode.data.startPos.y) / 2 }; const dist = { x: Math.abs(easypz.mousePos.x - mode.data.startPos.x), y: Math.abs(easypz.mousePos.y - mode.data.startPos.y) }; let scaleChange; if(eventData.modeName === 'BRUSH_ZOOM') { scaleChange = Math.max(dist.x / easypz.width, dist.y / easypz.height) * 1.3; } else if(eventData.modeName === 'BRUSH_ZOOM_X') { scaleChange = dist.x / easypz.width * 1.3; } else if(eventData.modeName === 'BRUSH_ZOOM_Y') { scaleChange = dist.y / easypz.height * 1.3; } //this.onZoomed.emit({x: middle.x, y: middle.y, scaleChange: scaleChange }); easypz.onZoomed.emit({x: middle.x, y: middle.y, scaleChange: scaleChange, targetX: this.width / 2, targetY: this.height / 2}); } } } }; return mode; }); /* Dynamic / RubPointing Zoom */ EasyPZ.addMode((easypz: EasyPZ) => { const mode = { ids: ['DYNAMIC_ZOOM_X_STATIC', 'DYNAMIC_ZOOM_X_ORIGINAL_PAN', 'DYNAMIC_ZOOM_X_NORMAL_PAN', 'DYNAMIC_ZOOM_X_ADJUSTABLE', 'DYNAMIC_ZOOM_Y_STATIC', 'DYNAMIC_ZOOM_Y_ORIGINAL_PAN', 'DYNAMIC_ZOOM_Y_NORMAL_PAN', 'DYNAMIC_ZOOM_Y_ADJUSTABLE'], settings: { speed: 0.05, minDistance: 3, delay: 300, minDirectionPercentage: 0.7 }, active: false, data: { startPos: {x: 0, y: 0}, relativePos: {x: 0, y: 0}, direction: 'x' }, onClickTouch: (eventData: EasyPzCallbackData) => { mode.data.direction = eventData.modeName.substr('DYNAMIC_ZOOM_'.length, 1).toLowerCase(); const direction = mode.data.direction; mode.data.startPos = {x: easypz.mousePos.x, y: easypz.mousePos.y}; mode.data.relativePos = {x: 0, y: 0}; easypz.resetAbsoluteScale.emit(null); easypz.callbackAfterTimeoutOrMovement(mode.settings.delay, mode.settings.minDistance).then((dist) => { let distInDirection = Math.abs(mode.data.startPos[direction] - easypz.mousePos[direction]); if (easypz.numberOfPointers > 1 || dist < mode.settings.minDistance || distInDirection / dist < mode.settings.minDirectionPercentage) { mode.active = false; } else if(this.mouseDownTime > this.mouseUpTime) { mode.active = true; } }); }, onMove: (eventData: EasyPzCallbackData) => { if(mode.active) { let relativeMove = {x: 0, y: 0}; const direction = mode.data.direction; EasyPZ.DIMENSIONS.forEach(dimension => { relativeMove[dimension] = easypz.mousePos[dimension] - easypz.lastMousePos[dimension]; }); let dist = easypz.mousePos[direction] - mode.data.startPos[direction]; if(!dist) return; let scale = Math.exp(-1 * mode.settings.speed * dist); EasyPZ.DIMENSIONS.forEach(dimension => { mode.data.relativePos[dimension] += relativeMove[dimension] * scale; }); let actualZoomPosition : {x: number, y: number}; let targetX = null; let targetY = null; let dynamicZoomPosition; if(eventData.modeName === 'DYNAMIC_ZOOM_X_ADJUSTABLE' || eventData.modeName === 'DYNAMIC_ZOOM_Y_ADJUSTABLE') { actualZoomPosition = {x: mode.data.startPos.x + mode.data.relativePos.x, y: mode.data.startPos.y + mode.data.relativePos.y}; targetX = easypz.mousePos.x; targetY = easypz.mousePos.y; dynamicZoomPosition = { x: easypz.mousePos.x, y: easypz.mousePos.y }; } else if(eventData.modeName === 'DYNAMIC_ZOOM_X_STATIC' || eventData.modeName === 'DYNAMIC_ZOOM_Y_STATIC') { dynamicZoomPosition = {x: mode.data.startPos.x, y: mode.data.startPos.y}; } else if(eventData.modeName === 'DYNAMIC_ZOOM_X_NORMAL_PAN' || eventData.modeName === 'DYNAMIC_ZOOM_Y_NORMAL_PAN') { dynamicZoomPosition = {x: mode.data.startPos.x - mode.data.relativePos.x, y: mode.data.startPos.y - mode.data.relativePos.y}; } else if(eventData.modeName === 'DYNAMIC_ZOOM_X_ORIGINAL_PAN' || eventData.modeName === 'DYNAMIC_ZOOM_Y_ORIGINAL_PAN') { dynamicZoomPosition = {x: easypz.mousePos.x, y: easypz.mousePos.y}; } let zoomPos = actualZoomPosition ? actualZoomPosition : dynamicZoomPosition; easypz.onZoomed.emit({x: zoomPos.x, y: zoomPos.y, absoluteScaleChange: scale, targetX: targetX, targetY: targetY}); } }, onClickTouchEnd: () => { mode.active = false; } }; return mode; }); /* Rub Zoom */ EasyPZ.addMode((easypz: EasyPZ) => { const mode = { ids: ['RUB_ZOOM_IN_X', 'RUB_ZOOM_IN_Y', 'RUB_ZOOM_OUT_X', 'RUB_ZOOM_OUT_Y'], settings: { speed: 0.02, minDistance: 15, minDistanceAfterDirectionChange: 10 }, active: false, data: { direction: 'x', hasChangedDirection: false, hasChangedDirectionSign: 0, hasChangedDirectionDirection:'x', zoomPosition: null, zoomReference: null }, onClickTouch: () => { mode.active = false; mode.data.zoomPosition = {x: easypz.mousePos.x, y: easypz.mousePos.y}; mode.data.zoomReference = {x: easypz.mousePos.x, y: easypz.mousePos.y}; }, onMove: (eventData: EasyPzCallbackData) => { if(mode.data.zoomReference) { const direction = eventData.modeName.substr(eventData.modeName.length - 1).toLowerCase(); let distance = Math.abs(mode.data.zoomReference[direction] - easypz.mousePos[direction]); let signBefore = sign(easypz.lastMousePos[direction] - mode.data.zoomReference[direction]); let signNow = sign(easypz.mousePos[direction] - easypz.lastMousePos[direction]); if(signBefore != 0 && signNow != 0 && signBefore != signNow && distance > mode.settings.minDistance) { mode.data.zoomReference = {x: easypz.mousePos.x, y: easypz.mousePos.y}; distance = 0; mode.data.hasChangedDirection = true; mode.data.hasChangedDirectionSign = signNow; mode.data.hasChangedDirectionDirection = direction; } if(!mode.active && mode.data.hasChangedDirection && direction == mode.data.hasChangedDirectionDirection && signNow != mode.data.hasChangedDirectionSign) { mode.data.hasChangedDirection = false; } if(mode.data.hasChangedDirection && distance > mode.settings.minDistanceAfterDirectionChange) { mode.active = true; } let distanceSinceLast = Math.abs(easypz.mousePos[direction] - easypz.lastMousePos[direction]); if(mode.active && distanceSinceLast) { const directionValue = eventData.modeName.substr(0, 'RUB_ZOOM_IN'.length) === 'RUB_ZOOM_IN' ? 1 : -1; const zoomPos = {x: (easypz.mousePos.x + mode.data.zoomReference.x)/2, y: (easypz.mousePos.y + mode.data.zoomReference.y)/2}; const scaleChange = 1 - mode.settings.speed * distanceSinceLast * directionValue; easypz.onZoomed.emit({x: zoomPos.x, y: zoomPos.y, scaleChange: scaleChange}); } } }, onClickTouchEnd: () => { mode.active = false; mode.data.zoomPosition = null; mode.data.zoomReference = null; mode.data.hasChangedDirection = false; } }; return mode; }); EasyPZ.addMode((easypz: EasyPZ) => { const mode = { ids: ['SHIFT_DRAG_ZOOM'], settings: { speed: 0.05 }, active: false, data: {zoomPos: {x:0, y: 0}, currY: 0}, onClickTouch: (e) => { if(e.event.shiftKey) { mode.active = true; mode.data.zoomPos.x = easypz.mousePos.x; mode.data.zoomPos.y = easypz.mousePos.y; mode.data.currY = easypz.mousePos.y; } }, onMove: () => { if(mode.active) { const deltaY = easypz.mousePos.y - mode.data.currY; mode.data.currY = easypz.mousePos.y; easypz.onZoomed.emit({ x: mode.data.zoomPos.x, y: mode.data.zoomPos.y, scaleChange: 1 - mode.settings.speed * deltaY }); } }, onClickTouchEnd: () => { mode.active = false; } }; return mode; }); const easyPZLoader = new EasyPZLoader(); easyPZLoader.checkElements(); window.addEventListener('load', function() { easyPZLoader.checkElements(); }); window.setInterval(function() { easyPZLoader.checkElements(); }, 500);
the_stack
import { Address, ConditionalTransferTypes, EIP712Domain, EventNames, EventPayloads, IConnextClient, NodeResponses, PrivateKey, PublicParams, Receipt, SignedTransferStatus, } from "@connext/types"; import { getChainId, getRandomBytes32, getRandomPrivateKey, getTestEIP712Domain, signReceiptMessage, } from "@connext/utils"; import { providers, constants, utils } from "ethers"; import { AssetOptions, createClient, ETH_AMOUNT_SM, ethProviderUrl, expect, fundChannel, getTestLoggers, TOKEN_AMOUNT, } from "../util"; const { AddressZero } = constants; const { hexlify, randomBytes } = utils; const name = "Signed Transfers"; const { timeElapsed } = getTestLoggers(name); describe(name, () => { let chainId: number; let clientA: IConnextClient; let clientB: IConnextClient; let domainSeparator: EIP712Domain; let privateKeyA: PrivateKey; let privateKeyB: PrivateKey; let provider: providers.JsonRpcProvider; let receipt: Receipt; let start: number; let tokenAddress: Address; before(async () => { provider = new providers.JsonRpcProvider(ethProviderUrl, await getChainId(ethProviderUrl)); const currBlock = await provider.getBlockNumber(); // the node uses a `TIMEOUT_BUFFER` on recipient of 100 blocks // so make sure the current block const TIMEOUT_BUFFER = 100; if (currBlock > TIMEOUT_BUFFER) { // no adjustment needed, return return; } for (let index = currBlock; index <= TIMEOUT_BUFFER + 1; index++) { await provider.send("evm_mine", []); } }); const sendSignedTransfer = async ( transfer: AssetOptions, sender: IConnextClient = clientA, receiver: IConnextClient = clientB, ) => { const [transferRes, installed] = await Promise.all([ sender.conditionalTransfer({ amount: transfer.amount, conditionType: ConditionalTransferTypes.SignedTransfer, paymentId: receipt.paymentId, signerAddress: receiver.signerAddress, chainId, verifyingContract: domainSeparator.verifyingContract, assetId: transfer.assetId, recipient: receiver.publicIdentifier, meta: { foo: "bar", sender: sender.publicIdentifier }, }), new Promise((res, rej) => { receiver.once(EventNames.CONDITIONAL_TRANSFER_CREATED_EVENT, res); sender.once(EventNames.REJECT_INSTALL_EVENT, rej); }), ]); expect(installed).deep.contain({ amount: transfer.amount, assetId: transfer.assetId, type: ConditionalTransferTypes.SignedTransfer, paymentId: receipt.paymentId, sender: sender.publicIdentifier, transferMeta: { signerAddress: receiver.signerAddress, chainId, verifyingContract: domainSeparator.verifyingContract, }, meta: { foo: "bar", recipient: receiver.publicIdentifier, sender: sender.publicIdentifier, paymentId: receipt.paymentId, senderAssetId: transfer.assetId, }, } as EventPayloads.SignedTransferCreated); return [transferRes.appIdentityHash, (installed as any).appIdentityHash]; }; const resolveSignedTransfer = async ( transfer: AssetOptions, signature: string, sender: IConnextClient = clientA, receiver: IConnextClient = clientB, ) => { const [eventData] = await Promise.all([ new Promise(async (res) => { sender.once(EventNames.CONDITIONAL_TRANSFER_UNLOCKED_EVENT, res); }), new Promise((res) => { sender.once(EventNames.UNINSTALL_EVENT, res); }), receiver.resolveCondition({ conditionType: ConditionalTransferTypes.SignedTransfer, paymentId: receipt.paymentId, data: receipt.data, signature, } as PublicParams.ResolveSignedTransfer), ]); expect(eventData).to.deep.contain({ amount: transfer.amount, assetId: transfer.assetId, type: ConditionalTransferTypes.SignedTransfer, paymentId: receipt.paymentId, sender: sender.publicIdentifier, transferMeta: { data: receipt.data, signature, }, meta: { foo: "bar", recipient: receiver.publicIdentifier, sender: sender.publicIdentifier, paymentId: receipt.paymentId, senderAssetId: transfer.assetId || AddressZero, }, } as EventPayloads.SignedTransferUnlocked); }; beforeEach(async () => { start = Date.now(); privateKeyA = getRandomPrivateKey(); const paymentId = getRandomBytes32(); const data = getRandomBytes32(); clientA = await createClient({ signer: privateKeyA, id: "A" }); privateKeyB = getRandomPrivateKey(); tokenAddress = clientA.config.contractAddresses[clientA.chainId].Token!; clientB = await createClient({ signer: privateKeyB, id: "B" }); receipt = { paymentId, data }; chainId = (await clientA.ethProvider.getNetwork()).chainId; domainSeparator = getTestEIP712Domain(chainId); timeElapsed("beforeEach complete", start); }); afterEach(async () => { await clientA.off(); await clientB.off(); }); it("clientA signed transfers eth to clientB through node, clientB is online", async () => { const transfer = { amount: ETH_AMOUNT_SM, assetId: AddressZero }; await fundChannel(clientA, transfer.amount, transfer.assetId); await sendSignedTransfer(transfer); const { [clientA.signerAddress]: clientAPostTransferBal, [clientA.nodeSignerAddress]: nodePostTransferBal, } = await clientA.getFreeBalance(transfer.assetId); expect(clientAPostTransferBal).to.eq(0); const signature = await signReceiptMessage(domainSeparator, receipt, privateKeyB); await resolveSignedTransfer(transfer, signature); const { [clientA.signerAddress]: clientAPostReclaimBal, [clientA.nodeSignerAddress]: nodePostReclaimBal, } = await clientA.getFreeBalance(transfer.assetId); expect(clientAPostReclaimBal).to.eq(0); expect(nodePostReclaimBal).to.eq(nodePostTransferBal.add(transfer.amount)); const { [clientB.signerAddress]: clientBPostTransferBal } = await clientB.getFreeBalance( transfer.assetId, ); expect(clientBPostTransferBal).to.eq(transfer.amount); }); it("clientA signed transfers tokens to clientB through node", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); await sendSignedTransfer(transfer); const { [clientA.signerAddress]: clientAPostTransferBal, [clientA.nodeSignerAddress]: nodePostTransferBal, } = await clientA.getFreeBalance(transfer.assetId); expect(clientAPostTransferBal).to.eq(0); const signature = await signReceiptMessage(domainSeparator, receipt, privateKeyB); await resolveSignedTransfer(transfer, signature); const { [clientA.signerAddress]: clientAPostReclaimBal, [clientA.nodeSignerAddress]: nodePostReclaimBal, } = await clientA.getFreeBalance(transfer.assetId); expect(clientAPostReclaimBal).to.eq(0); expect(nodePostReclaimBal).to.eq(nodePostTransferBal.add(transfer.amount)); const { [clientB.signerAddress]: clientBPostTransferBal } = await clientB.getFreeBalance( transfer.assetId, ); expect(clientBPostTransferBal).to.eq(transfer.amount); }); it("gets a pending signed transfer by lock hash", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); await clientA.conditionalTransfer({ amount: transfer.amount, conditionType: ConditionalTransferTypes.SignedTransfer, paymentId: receipt.paymentId, signerAddress: clientB.signerAddress, chainId, verifyingContract: domainSeparator.verifyingContract, assetId: transfer.assetId, meta: { foo: "bar", sender: clientA.publicIdentifier }, } as PublicParams.SignedTransfer); const retrievedTransfer = await clientB.getSignedTransfer(receipt.paymentId); expect(retrievedTransfer).to.deep.equal({ amount: transfer.amount.toString(), assetId: transfer.assetId, paymentId: receipt.paymentId, senderIdentifier: clientA.publicIdentifier, status: SignedTransferStatus.PENDING, meta: { foo: "bar", sender: clientA.publicIdentifier, paymentId: receipt.paymentId, senderAssetId: transfer.assetId, }, } as NodeResponses.GetSignedTransfer); }); it("gets a completed signed transfer by lock hash", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); await clientA.conditionalTransfer({ amount: transfer.amount, conditionType: ConditionalTransferTypes.SignedTransfer, paymentId: receipt.paymentId, signerAddress: clientB.signerAddress, chainId, verifyingContract: domainSeparator.verifyingContract, assetId: transfer.assetId, meta: { foo: "bar", sender: clientA.publicIdentifier }, } as PublicParams.SignedTransfer); // disconnect so that it cant be unlocked await clientA.off(); const signature = await signReceiptMessage(domainSeparator, receipt, privateKeyB); // wait for transfer to be picked up by receiver await new Promise(async (resolve, reject) => { clientB.once( EventNames.CONDITIONAL_TRANSFER_UNLOCKED_EVENT, resolve, (data) => !!data.paymentId && data.paymentId === receipt.paymentId, ); clientB.once( EventNames.CONDITIONAL_TRANSFER_FAILED_EVENT, reject, (data) => !!data.paymentId && data.paymentId === receipt.paymentId, ); await clientB.resolveCondition({ conditionType: ConditionalTransferTypes.SignedTransfer, paymentId: receipt.paymentId, data: receipt.data, signature, }); }); const retrievedTransfer = await clientB.getSignedTransfer(receipt.paymentId); expect(retrievedTransfer).to.deep.equal({ amount: transfer.amount.toString(), assetId: transfer.assetId, paymentId: receipt.paymentId, senderIdentifier: clientA.publicIdentifier, receiverIdentifier: clientB.publicIdentifier, status: SignedTransferStatus.COMPLETED, meta: { foo: "bar", sender: clientA.publicIdentifier, paymentId: receipt.paymentId, senderAssetId: transfer.assetId, }, } as NodeResponses.GetSignedTransfer); }); it("cannot resolve a signed transfer if signature is wrong", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); await sendSignedTransfer(transfer); const badSig = hexlify(randomBytes(65)); await expect( clientB.resolveCondition({ conditionType: ConditionalTransferTypes.SignedTransfer, paymentId: receipt.paymentId, data: receipt.data, signature: badSig, } as PublicParams.ResolveSignedTransfer), ).to.eventually.be.rejectedWith(/invalid signature|Incorrect signer/); }); it("if sender uninstalls, node should force uninstall receiver first", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); const [senderAppId, receiverAppId] = await sendSignedTransfer(transfer); clientA.uninstallApp(senderAppId); const winner = await Promise.race([ new Promise<EventPayloads.Uninstall>((res) => { clientA.once( EventNames.UNINSTALL_EVENT, res, (data) => data.appIdentityHash === senderAppId, ); }), new Promise<EventPayloads.Uninstall>((res) => { clientB.once(EventNames.UNINSTALL_EVENT, res); }), ]); expect(winner.appIdentityHash).to.be.eq(receiverAppId); }); it("sender cannot uninstall before receiver", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); const [senderAppId] = await sendSignedTransfer(transfer); // disconnect so receiver cannot uninstall await clientB.off(); await clientB.off(); await expect(clientA.uninstallApp(senderAppId)).to.eventually.be.rejected; }); it("sender cannot uninstall unfinalized app when receiver is finalized", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); const signature = await signReceiptMessage(domainSeparator, receipt, privateKeyB); const [senderAppId] = await sendSignedTransfer(transfer); // disconnect so sender cannot unlock await clientA.off(); await Promise.all([ new Promise((res) => { clientB.once(EventNames.CONDITIONAL_TRANSFER_UNLOCKED_EVENT, res); }), clientB.resolveCondition({ conditionType: ConditionalTransferTypes.SignedTransfer, paymentId: receipt.paymentId, data: receipt.data, signature, } as PublicParams.ResolveSignedTransfer), ]); clientA.messaging.connect(); await expect(clientA.uninstallApp(senderAppId)).to.eventually.be.rejected; }); });
the_stack
import { inspect } from 'util'; import checkAppCompatibility, { checkEngineIsSupported, checkEngineVersionIsSet, checkIdenticalShared, checkProvidedVersionOfSharedIsValid, checkRequestedSharedIsProvided, checkRequestedVersionOfSharedIsValid, } from './checkAppCompatibility'; const providingEngine = (providedVersionOfEngine: string) => ({ providedVersionOfEngine, providedVersionOfShared: 'irrelevant', }); const requiringEngine = (engineVersion?: string) => ({ engineVersion, }); const providingShared = (providedVersionOfShared: string) => ({ providedVersionOfEngine: 'irrelevant', providedVersionOfShared, }); const requiringShared = (sharedVersion?: string) => ({ engineVersion: 'irrelevant', sharedVersion, }); const failingCheck = { isDecided: true, isCompatible: false, warning: expect.anything(), longWarning: expect.anything(), }; const successfulCheck = { isDecided: true, isCompatible: true, }; const undecidedCheck = { isDecided: false, }; describe('check compatibility of an app with the launcher', () => { describe('check if the app sets an engine version', () => { it('fails without an engine version', () => { expect( checkEngineVersionIsSet( requiringEngine(undefined), providingEngine('irrelevant') ) ).toMatchObject(failingCheck); }); it('is undefined if any engine version is set', () => { expect( checkEngineVersionIsSet( requiringEngine('^1.0.0'), providingEngine('irrelevant') ) ).toMatchObject(undecidedCheck); }); }); describe('check if the engine version is what the app requires', () => { it('is undefined if the app requires a lower version', () => { expect( checkEngineIsSupported( requiringEngine('^1.0.0'), providingEngine('1.2.3') ) ).toMatchObject(undecidedCheck); }); it('is undefined if the app requires the same version', () => { expect( checkEngineIsSupported( requiringEngine('^1.2.3'), providingEngine('1.2.3') ) ).toMatchObject(undecidedCheck); }); it('is undefined if the engine is just a pre-release', () => { expect( checkEngineIsSupported( requiringEngine('^1.2.3'), providingEngine('1.2.3-alpha.0') ) ).toMatchObject(undecidedCheck); }); it('fails if the app requires a higher version', () => { expect( checkEngineIsSupported( requiringEngine('^2.0.0'), providingEngine('1.2.3') ) ).toMatchObject(failingCheck); }); }); describe('check if the shared versions are identical', () => { describe('succeeds if both are identical non-version numbers', () => { const fixedVersionStrings = [ 'test/branch', 'ec5bfa74', 'file:../pc-nrfconnect-shared/pc-nrfconnect-shared-4.20.0.tgz', 'github:NordicSemiconductor/pc-nrfconnect-shared', // Happens when depending on the master branch of shared ]; fixedVersionStrings.forEach(versionString => it(`for ${versionString}`, () => expect( checkIdenticalShared( requiringShared(versionString), providingShared(versionString) ) ).toMatchObject(successfulCheck)) ); }); it('is undefined if shared versions are different', () => { expect( checkIdenticalShared( requiringShared('test/branch'), providingShared('ec5bfa74149d19b233e446a23b8f09b7f8dde4d8') ) ).toMatchObject(undecidedCheck); }); }); describe('check if the provided version of shared is a testable string', () => { it('is undefined if the app does not depend on shared', () => { expect( checkProvidedVersionOfSharedIsValid( requiringShared(), providingShared('test/branch') ) ).toMatchObject(undecidedCheck); }); it('is undefined if engine provides a normal version of shared', () => { expect( checkProvidedVersionOfSharedIsValid( requiringShared('2.0.0'), providingShared('1.2.3') ) ).toMatchObject(undecidedCheck); }); it('fails if the engine depends on a non numeric version of shared', () => { expect( checkProvidedVersionOfSharedIsValid( requiringShared('2.0.0'), providingShared('test/branch') ) ).toMatchObject(failingCheck); }); }); describe('check if the required version of shared is a testable string', () => { it('is undefined if the app does not depend on shared', () => { expect( checkRequestedVersionOfSharedIsValid( requiringShared(), providingShared('irrelevant') ) ).toMatchObject(undecidedCheck); }); it('is undefined if the app depends on a normal version of shared', () => { expect( checkRequestedVersionOfSharedIsValid( requiringShared('2.0.0'), providingShared('irrelevant') ) ).toMatchObject(undecidedCheck); }); it('fails if the app depends on a non numeric version of shared', () => { expect( checkRequestedVersionOfSharedIsValid( requiringShared('test/branch'), providingShared('irrelevant') ) ).toMatchObject(failingCheck); }); }); describe('check if the provided and required version of shared match', () => { it('is undefined if the app does not depend on shared', () => { expect( checkRequestedSharedIsProvided( requiringShared(), providingShared('3.0.0') ) ).toMatchObject(undecidedCheck); }); it('is undefined if the app depends on a lower version of shared', () => { expect( checkRequestedSharedIsProvided( requiringShared('2.0.0'), providingShared('3.0.0') ) ).toMatchObject(undecidedCheck); }); it('fails if the app depends on a higher version of shared', () => { expect( checkRequestedSharedIsProvided( requiringShared('2.0.1'), providingShared('2.0.0') ) ).toMatchObject(failingCheck); }); }); describe('integrating all the checkes', () => { describe('some checks fails if', () => { [ { description: 'the app fails to specify engine version', app: [undefined, '1.0.0'], engine: ['1.0.0', '1.0.0'], }, { description: 'the app requires a higher engine version', app: ['^1.0.1', '1.0.0'], engine: ['1.0.0', '1.0.0'], }, { description: 'only the engine provides a non-versioned variant of shared', app: ['^1.0.0', '1.0.0'], engine: ['1.0.0', 'ec5bfa74'], }, { description: 'only the app requires a non-versioned variant of shared', app: ['^1.0.0', 'ec5bfa74'], engine: ['1.0.0', '1.0.0'], }, { description: 'the app requires a newer version of shared', app: ['^1.0.0', '1.0.1'], engine: ['1.0.0', '1.0.0'], }, ].forEach( ({ description, app: [engineVersion, sharedVersion], engine: [providedVersionOfEngine, providedVersionOfShared], }) => { const appSpec = { engineVersion, sharedVersion }; const engineSpec = { providedVersionOfEngine, providedVersionOfShared, }; it(`${description}, with app spec ${inspect( appSpec )} and engine spec ${inspect(engineSpec)}`, () => { expect( checkAppCompatibility(appSpec, engineSpec) ).toMatchObject(failingCheck); }); } ); }); describe('all checks are successful if', () => { [ { description: 'all versions are exactly as specified', app: ['^1.0.0', '1.0.0'], engine: ['1.0.0', '1.0.0'], }, { description: 'the provided versions are higher as required', app: ['^1.0.0', '1.0.0'], engine: ['1.0.1', '1.0.1'], }, { description: 'both use the same non-versioned variant of shared', app: ['^1.0.0', 'ec5bfa74'], engine: ['1.0.0', 'ec5bfa74'], }, { description: 'the app does not require shared', app: ['^1.0.0', undefined], engine: ['1.0.0', 'ec5bfa74'], }, ].forEach( ({ description, app: [engineVersion, sharedVersion], engine: [providedVersionOfEngine, providedVersionOfShared], }) => { const appSpec = { engineVersion, sharedVersion }; const engineSpec = { providedVersionOfEngine, providedVersionOfShared, }; it(`${description}, with app spec ${inspect( appSpec )} and engine spec ${inspect(engineSpec)}`, () => { expect( checkAppCompatibility(appSpec, engineSpec) ).toMatchObject(successfulCheck); }); } ); }); }); });
the_stack
import { homedir } from 'os'; import path from 'path'; export const USER_HOME_DIR = homedir(); export const RNV_HOME_DIR = path.join(__dirname, '../..'); // Self check: if in packages => linked, if node_modules => installed export const IS_LINKED = path.dirname(RNV_HOME_DIR).split(path.sep).pop() === 'packages'; export const CURRENT_DIR = path.resolve('.'); export const RNV_NODE_MODULES_DIR = path.join(RNV_HOME_DIR, 'node_modules'); export const ANDROID = 'android'; export const ANDROID_AUTO = 'androidauto'; export const ANDROID_TV = 'androidtv'; export const ANDROID_WEAR = 'androidwear'; export const ALEXA = 'alexa'; export const APPLE_AUTO = 'appleauto'; export const ASTIAN = 'astian'; export const BLACKBERRY = 'blackberry'; export const CHROMECAST = 'chromecast'; export const CHROME_OS = 'chromeos'; export const FIREFOX_OS = 'firefoxos'; export const FIREFOX_TV = 'firefoxtv'; export const FIRE_OS = 'fireos'; export const FIRE_TV = 'firetv'; export const HBBTV = 'hbbtv'; export const IOS = 'ios'; export const KAIOS = 'kaios'; export const MACOS = 'macos'; export const MEEGO = 'meego'; export const NETCAST = 'netcast'; export const OCCULUS = 'occulus'; export const ORSAY = 'orsay'; export const PS4 = 'ps4'; export const ROKU = 'roku'; export const SAILFISH = 'sailfish'; export const TIVO = 'tivo'; export const TIZEN = 'tizen'; export const TIZEN_WATCH = 'tizenwatch'; export const TIZEN_MOBILE = 'tizenmobile'; export const TVOS = 'tvos'; export const UBUNTU = 'ubuntu'; export const UBUNTU_TOUCH = 'ubuntutouch'; export const UNITY = 'unity'; export const VEWD = 'vewd'; export const VIDAA = 'vidaa'; export const VIERACONNECT = 'vieraconnect'; export const VIZIO = 'vizio'; export const WATCHOS = 'watchos'; export const WEB = 'web'; export const WEBTV = 'webtv'; export const WEBOS = 'webos'; export const WEBIAN = 'webian'; export const WII = 'wii'; export const WINDOWS = 'windows'; export const LINUX = 'linux'; export const WP10 = 'wp10'; export const WP8 = 'wp8'; export const XBOX = 'xbox'; export const XBOX360 = 'xbox360'; // Kodi, Boxee, HorizonTV, Mediaroom(Ericsson), YahooSmartTV, Slingbox, Hololens, Occulus, GearVR, WebVR, Saphi export const ICONS = { PHONE: '📱', AUTO: '🚗', TV: '📺', CONSOLE: '🎮', WATCH: '⌚', DESKTOP: '🖥️ ', BROWSER: '🌐', VOICE: '📢', SERVICE: '☁️' }; export const REMOTE_DEBUG_PORT = 8079; // CLI export const CLI_ANDROID_EMULATOR = 'androidEmulator'; export const CLI_ANDROID_ADB = 'androidAdb'; export const CLI_ANDROID_AVDMANAGER = 'androidAvdManager'; export const CLI_ANDROID_SDKMANAGER = 'androidSdkManager'; export const CLI_TIZEN_EMULATOR = 'tizenEmulator'; export const CLI_KAIOS_EMULATOR = 'tizenEmulator'; export const CLI_TIZEN = 'tizen'; export const CLI_SDB_TIZEN = 'tizenSdb'; export const CLI_WEBOS_ARES = 'webosAres'; export const CLI_WEBOS_ARES_PACKAGE = 'webosAresPackage'; export const CLI_WEBOS_ARES_INSTALL = 'webosAresInstall'; export const CLI_WEBOS_ARES_LAUNCH = 'webosAresLaunch'; export const CLI_WEBOS_ARES_SETUP_DEVICE = 'webosAresSetup'; export const CLI_WEBOS_ARES_DEVICE_INFO = 'webosAresDeviceInfo'; export const CLI_WEBOS_ARES_NOVACOM = 'webosAresNovacom'; // SDK export const ANDROID_SDK = 'ANDROID_SDK'; export const ANDROID_NDK = 'ANDROID_NDK'; export const TIZEN_SDK = 'TIZEN_SDK'; export const WEBOS_SDK = 'WEBOS_SDK'; export const KAIOS_SDK = 'KAIOS_SDK'; export const RENATIVE_CONFIG_NAME = 'renative.json'; export const RENATIVE_CONFIG_LOCAL_NAME = 'renative.local.json'; export const RENATIVE_CONFIG_PRIVATE_NAME = 'renative.private.json'; export const RENATIVE_CONFIG_TEMPLATE_NAME = 'renative.template.json'; export const RENATIVE_CONFIG_BUILD_NAME = 'renative.build.json'; export const RENATIVE_CONFIG_RUNTIME_NAME = 'renative.runtime.json'; export const RENATIVE_CONFIG_WORKSPACES_NAME = 'renative.workspaces.json'; export const RENATIVE_CONFIG_PLUGINS_NAME = 'renative.plugins.json'; export const RENATIVE_CONFIG_TEMPLATES_NAME = 'renative.templates.json'; export const RENATIVE_CONFIG_PLATFORMS_NAME = 'renative.platforms.json'; export const RENATIVE_CONFIG_ENGINE_NAME = 'renative.engine.json'; export const RN_CLI_CONFIG_NAME = 'metro.config.js'; export const RN_BABEL_CONFIG_NAME = 'babel.config.js'; export const NEXT_CONFIG_NAME = 'next.config.js'; export const SAMPLE_APP_ID = 'helloworld'; export const IS_TABLET_ABOVE_INCH = 6.5; export const IS_WEAR_UNDER_SIZE = 1000; // width + height export const PACKAGE_JSON_FILEDS = [ 'name', 'version', 'description', 'keywords', 'homepage', 'bugs', 'license', 'author', 'contributors', 'files', 'main', 'browser', 'bin', 'man', 'directories', 'repository', 'scripts', 'config', 'dependencies', 'devDependencies', 'peerDependencies', 'bundledDependencies', 'optionalDependencies', 'engines', 'engineStrict', 'os', 'cpu', 'private', 'publishConfig' ]; // DEPRECATED export const SUPPORTED_PLATFORMS = [ IOS, ANDROID, FIRE_TV, ANDROID_TV, ANDROID_WEAR, WEB, WEBTV, TIZEN, TIZEN_MOBILE, TVOS, WEBOS, MACOS, WINDOWS, LINUX, TIZEN_WATCH, KAIOS, FIREFOX_OS, FIREFOX_TV, CHROMECAST ]; export const SDK_PLATFORMS: any = {}; SDK_PLATFORMS[ANDROID] = ANDROID_SDK; SDK_PLATFORMS[ANDROID_TV] = ANDROID_SDK; SDK_PLATFORMS[FIRE_TV] = ANDROID_SDK; SDK_PLATFORMS[ANDROID_WEAR] = ANDROID_SDK; SDK_PLATFORMS[TIZEN] = TIZEN_SDK; SDK_PLATFORMS[TIZEN_WATCH] = TIZEN_SDK; SDK_PLATFORMS[TIZEN_MOBILE] = TIZEN_SDK; SDK_PLATFORMS[WEBOS] = WEBOS_SDK; SDK_PLATFORMS[KAIOS] = KAIOS_SDK; export const TASK_RUN = 'run'; export const TASK_CONFIGURE = 'configure'; export const TASK_DOCTOR = 'doctor'; export const TASK_BUILD = 'build'; export const TASK_INFO = 'info'; export const TASK_START = 'start'; export const TASK_EXPORT = 'export'; export const TASK_DEBUG = 'debug'; export const TASK_PACKAGE = 'package'; export const TASK_DEPLOY = 'deploy'; export const TASK_LOG = 'log'; export const TASK_CLEAN = 'clean'; export const TASK_INSTALL = 'install'; export const TASK_PUBLISH = 'publish'; export const TASK_STATUS = 'status'; export const TASK_SWITCH = 'switch'; export const TASK_TARGET_LAUNCH = 'target launch'; export const TASK_TARGET_LIST = 'target list'; export const TASK_TARGET = 'target'; export const TASK_TEMPLATE_ADD = 'template add'; export const TASK_TEMPLATE_LIST = 'template list'; export const TASK_TEMPLATE_APPLY = 'template apply'; export const TASK_WORKSPACE_ADD = 'workspace add'; export const TASK_WORKSPACE_CONNECT = 'workspace connect'; export const TASK_WORKSPACE_LIST = 'workspace list'; export const TASK_WORKSPACE_UPDATE = 'workspace update'; export const TASK_PLATFORM_CONFIGURE = 'platform configure'; export const TASK_PLATFORM_CONNECT = 'platform connect'; export const TASK_PLATFORM_EJECT = 'platform eject'; export const TASK_PLATFORM_LIST = 'platform list'; export const TASK_PLATFORM_SETUP = 'platform setup'; export const TASK_PROJECT_CONFIGURE = 'project configure'; export const TASK_PROJECT_UPGRADE = 'project upgrade'; export const TASK_PLUGIN_ADD = 'plugin add'; export const TASK_PLUGIN_LIST = 'plugin list'; export const TASK_PLUGIN_UPDATE = 'plugin update'; export const TASK_CRYPTO_ENCRYPT = 'crypto encrypt'; export const TASK_CRYPTO_DECRYPT = 'crypto decrypt'; export const TASK_CRYPTO_INSTALL_CERTS = 'crypto installCerts'; export const TASK_CRYPTO_INSTALL_PROFILES = 'crypto installProfiles'; export const TASK_CRYPTO_INSTALL_PROFILE = 'crypto installProfile'; export const TASK_CRYPTO_UPDATE_PROFILE = 'crypto updateProfile'; export const TASK_CRYPTO_UPDATE_PROFILES = 'crypto updateProfiles'; export const TASK_HOOKS_RUN = 'hooks run'; export const TASK_HOOKS_LIST = 'hooks list'; export const TASK_HOOKS_PIPES = 'hooks pipes'; export const TASK_PKG = 'pkg'; export const TASK_APP_CONFIGURE = 'app configure'; export const TASK_APP_CREATE = 'app create'; export const TASK_WORKSPACE_CONFIGURE = 'workspace configure'; export const TASK_CONFIGURE_SOFT = 'configureSoft'; export const TASK_KILL = 'kill'; export const CLI_PROPS = [ 'provisioningStyle', 'codeSignIdentity', 'provisionProfileSpecifier' ]; export const PARAM_KEYS: any = { info: { shortcut: 'i', value: 'value', description: 'Show full debug Info' }, updatePods: { shortcut: 'u', description: 'Force update dependencies (iOS only)' }, platform: { shortcut: 'p', value: 'value', description: 'select specific Platform' }, appConfigID: { shortcut: 'c', value: 'value', description: 'select specific app Config id' }, target: { shortcut: 't', value: 'value', description: 'select specific Target device/simulator' }, projectName: { value: 'value', description: 'select the name of the new project', }, projectTemplate: { value: 'value', description: 'select the template of new project', }, templateVersion: { value: 'value', description: 'select the template version', }, title: { value: 'value', description: 'select the title of the app', }, id: { value: 'value', description: 'select the id of the app', }, appVersion: { value: 'value', description: 'select the version of the app', }, workspace: { value: 'value', description: 'select the workspace for the new project', }, template: { shortcut: 'T', value: 'value', isRequired: true, description: 'select specific template' }, device: { shortcut: 'd', value: 'value', description: 'select connected Device' }, scheme: { shortcut: 's', value: 'value', description: 'select build Scheme' }, filter: { shortcut: 'f', value: 'value', isRequired: true, description: 'Filter value' }, list: { shortcut: 'l', description: 'return List of items related to command' }, only: { shortcut: 'o', description: 'run Only top command (Skip dependencies)' }, reset: { shortcut: 'r', description: 'also perform reset of platform build' }, resetHard: { shortcut: 'R', description: 'also perform reset of platform platform and platform assets' }, resetAssets: { shortcut: 'a', description: 'also perform reset of platform assets' }, key: { shortcut: 'k', value: 'value', isRequired: true, description: 'Pass the key/password' }, blueprint: { shortcut: 'b', value: 'value', description: 'Blueprint for targets' }, help: { shortcut: 'h', description: 'Displays help info for particular command' }, host: { shortcut: 'H', value: 'value', isRequired: true, description: 'custom Host ip' }, exeMethod: { shortcut: 'x', value: 'value', description: 'eXecutable method in buildHooks' }, port: { shortcut: 'P', value: 'value', isRequired: true, description: 'custom Port' }, debug: { shortcut: 'D', value: 'value', description: 'enable or disable remote debugger.', examples: [ '--debug weinre //run remote debug with weinre as preference', '--debug chii //run remote debug with chii as preference', '--debug false //force disable remote debug', '--debug //run remote debug with default preference (chii)' ] }, global: { shortcut: 'G', description: 'Flag for setting a config value for all RNV projects' }, engine: { shortcut: 'e', value: 'value', isRequired: true, description: 'engine to be used (next)' }, debugIp: { value: 'value', isRequired: true, description: '(optional) overwrite the ip to which the remote debugger will connect' }, ci: { description: 'CI/CD flag so it wont ask questions' }, mono: { description: 'Monochrome console output without chalk' }, skipNotifications: { description: 'Skip sending any integrated notifications' }, keychain: { value: 'value', isRequired: true, description: 'Name of the keychain' }, provisioningStyle: { value: 'value', isRequired: true, description: 'Set provisioningStyle <Automatic | Manual>' }, codeSignIdentity: { value: 'value', isRequired: true, description: 'Set codeSignIdentity ie <iPhone Distribution>' }, provisionProfileSpecifier: { value: 'value', isRequired: true, description: 'Name of provisionProfile' }, hosted: { description: 'Run in a hosted environment (skip budleAssets)' }, hooks: { description: 'Force rebuild hooks' }, maxErrorLength: { value: 'number', isRequired: true, description: 'Specify how many characters each error should display. Default 200' }, skipTargetCheck: { description: 'Skip Android target check, just display the raw adb devices to choose from' }, analyzer: { description: 'Enable real-time bundle analyzer' }, xcodebuildArchiveArgs: { value: 'value', isRequired: true, description: 'pass down custom xcodebuild arguments' }, xcodebuildExportArgs: { value: 'value', isRequired: true, description: 'pass down custom xcodebuild arguments' }, skipDependencyCheck: { description: 'Skips auto update of npm dependencies if mismatch found' }, skipRnvCheck: { description: 'Skips auto update of rnv dependencies if mismatch found' }, configName: { value: 'value', isRequired: true, description: 'Use custom name for ./renative.json. (applies only at root level)' }, sourceAppConfigID: { value: 'value', isRequired: true, description: 'name of source appConfig folder to copy from' }, hostIp: { value: 'value', isRequired: true, description: 'Custom IP override' }, unlinked: { description: 'Force engines to be loaded from node_modules rather than locally' }, yes: { description: 'Default all prompts to yes' }, gitEnabled: { description: 'Enable git in your newly created project', value: 'value', }, npxMode: { description: 'Ensures you can use local npx rnv version after the command is done' }, packageManager: { value: 'value', isRequired: true, options: ['yarn', 'npm'], description: 'Set specific package manager to use', examples: [ '--packageManager yarn', '--packageManager npm' ] } }; Object.keys(PARAM_KEYS).forEach((k) => { PARAM_KEYS[k].key = k; }); export const PARAMS = { withBase: (arr: any) => [PARAM_KEYS.info, PARAM_KEYS.ci, PARAM_KEYS.mono, PARAM_KEYS.maxErrorLength, PARAM_KEYS.only].concat(arr || []), withConfigure: (arr: any) => [PARAM_KEYS.reset, PARAM_KEYS.resetHard, PARAM_KEYS.engine, PARAM_KEYS.resetAssets, PARAM_KEYS.appConfigID, PARAM_KEYS.scheme, PARAM_KEYS.platform].concat(arr || []), withRun: (arr: any) => [PARAM_KEYS.target, PARAM_KEYS.device, PARAM_KEYS.hosted, PARAM_KEYS.port, PARAM_KEYS.debug, PARAM_KEYS.debugIp, PARAM_KEYS.skipTargetCheck, PARAM_KEYS.host].concat(arr || []), withAll: (arr: any) => Object.values(PARAM_KEYS).concat(arr || []), all: Object.keys(PARAM_KEYS) }; export const configSchema = { analytics: { values: ['true', 'false'], key: 'enableAnalytics', default: true } }; export const RNV_PACKAGES = [ { packageName: 'renative', folderName: 'renative', skipLinking: true }, { packageName: '@rnv/template-starter', folderName: 'template-starter' }, { packageName: '@rnv/template-blank', folderName: 'template-blank' }, { packageName: 'rnv', folderName: 'rnv' }, { packageName: '@rnv/engine-lightning', folderName: 'engine-lightning' }, { packageName: '@rnv/engine-rn', folderName: 'engine-rn' }, { packageName: '@rnv/engine-rn-electron', folderName: 'engine-rn-electron' }, { packageName: '@rnv/engine-rn-windows', folderName: 'engine-rn-windows' }, { packageName: '@rnv/engine-rn-next', folderName: 'engine-rn-next' }, { packageName: '@rnv/engine-rn-tvos', folderName: 'engine-rn-tvos' }, { packageName: '@rnv/engine-rn-web', folderName: 'engine-rn-web' }, { packageName: '@rnv/engine-roku', folderName: 'engine-roku' }, { packageName: '@rnv/integration-docker', folderName: 'integration-docker' }, { packageName: '@rnv/integration-ftp', folderName: 'integration-ftp' }, { packageName: '@rnv/integration-vercel', folderName: 'integration-vercel' }, ]; export const INJECTABLE_CONFIG_PROPS = ['id', 'title', 'entryFile', 'backgroundColor', 'scheme', 'teamID', 'provisioningStyle', 'bundleAssets', 'multipleAPKs', 'pagesDir']; export const INJECTABLE_RUNTIME_PROPS = ['appId', 'scheme', 'timestamp', 'localhost', 'target', 'port']; export const REDASH_URL = 'https://analytics.prod.api.flexn.io/rnv'; export const REDASH_KEY = '471577f3b856fb6348ae913ceb32545c'; export const SENTRY_ENDPOINT = 'https://004caee3caa04c81a10f2ba31a945362@sentry.io/1795473'; export const REMOTE_DEBUGGER_ENABLED_PLATFORMS = [TIZEN, TIZEN_MOBILE, TIZEN_WATCH];
the_stack
import DragList from "../../common/cmpt/DragList"; import Events, { EventName, preloadEvent } from "../../common/util/Events"; import RecyclePool from "../../common/util/RecyclePool"; import Res from "../../common/util/Res"; import Tool from "../../common/util/Tool"; import { ResUrl } from "../../constant/ResUrl"; import Transition from "../data/Transition"; import Editor from "../Editor"; import Line from "../fsm/Line"; import UnitBase from "../fsm/UnitBase"; import UnitState from "../fsm/UnitState"; import UnitStateMachine from "../fsm/UnitStateMachine"; import ParamItem from "../parameters/ParamItem"; import ConditionItem from "./ConditionItem"; import TransitionItem from "./TransitionItem"; const { ccclass, property } = cc._decorator; @ccclass export default class InspectorCtr extends cc.Component { @property(cc.Node) UnitInfo: cc.Node = null; @property(cc.Node) NameNode: cc.Node = null; @property(cc.Node) MotionNode: cc.Node = null; @property(cc.Node) SpeedNode: cc.Node = null; @property(cc.Node) MultiplierNode: cc.Node = null; @property(cc.Node) LoopNode: cc.Node = null; @property(cc.Node) TransitionInfo: cc.Node = null; @property(DragList) TransitionList: DragList = null; @property(cc.Node) ConditionInfo: cc.Node = null; @property(DragList) ConditionList: DragList = null; @property(cc.Label) CurTransLab: cc.Label = null; @property(cc.Toggle) HasExitTime: cc.Toggle = null; private _layout: cc.Layout = null; private _transitionInfoLayout: cc.Layout = null; private _conditionInfoLayout: cc.Layout = null; private _nameEdit: cc.EditBox = null; private _motionEdit: cc.EditBox = null; private _speedEdit: cc.EditBox = null; private _loopToggle: cc.Toggle = null; private _multiplierLabel: cc.Label = null; /** fsm视图中选中的节点 */ private _unit: UnitBase = null; /** fsm视图选中的连线 */ private _line: Line = null; /** 选中的TransitionItem */ private _transitionItem: TransitionItem = null; private _transLayoutDirty: boolean = false; /** 选中的ConditionItem */ private _conditionItem: ConditionItem = null; private _conLayoutDirty: boolean = false; protected onLoad() { this.UnitInfo.active = false; this.TransitionInfo.active = false; this.ConditionInfo.active = false; this._layout = this.getComponent(cc.ScrollView).content.getComponent(cc.Layout); this._transitionInfoLayout = this.TransitionInfo.getComponent(cc.Layout); this._conditionInfoLayout = this.ConditionInfo.getComponent(cc.Layout); this._nameEdit = this.NameNode.children[0].getComponent(cc.EditBox); this._motionEdit = this.MotionNode.children[0].getComponent(cc.EditBox); this._speedEdit = this.SpeedNode.children[0].getComponent(cc.EditBox); this._loopToggle = this.LoopNode.children[0].getComponent(cc.Toggle); this._multiplierLabel = this.MultiplierNode.children[1].getComponent(cc.Label); // 注册拖拽回调 this.TransitionList.setDragCall(this.transitionDragCall, this); this.ConditionList.setDragCall(this.conditionDragCall, this); Events.targetOn(this); } protected onEnable() { // 屏蔽scrollView内部touch事件,防止与拖拽行为产生冲突 let scrollView = this.getComponent(cc.ScrollView); scrollView.node.off(cc.Node.EventType.TOUCH_START, scrollView['_onTouchBegan'], scrollView, true); scrollView.node.off(cc.Node.EventType.TOUCH_MOVE, scrollView['_onTouchMoved'], scrollView, true); scrollView.node.off(cc.Node.EventType.TOUCH_END, scrollView['_onTouchEnded'], scrollView, true); scrollView.node.off(cc.Node.EventType.TOUCH_CANCEL, scrollView['_onTouchCancelled'], scrollView, true); } protected onDestroy() { Events.targetOff(this); } protected lateUpdate() { let doUpdate: boolean = false; if (this._transLayoutDirty) { this._transLayoutDirty = false; this.TransitionList.node.height = 40; this.TransitionList.layout.updateLayout(); this._transitionInfoLayout.updateLayout(); doUpdate = true; } if (this._conLayoutDirty) { this._conLayoutDirty = false; this.ConditionList.node.height = 40; this.ConditionList.layout.updateLayout(); this._conditionInfoLayout.updateLayout(); doUpdate = true; } if (doUpdate) { this._layout.updateLayout(); } } private transitionDragCall(dragIdx: number, toIdx: number) { if (!(this._unit instanceof UnitState) || !this._transitionItem) { return; } this._unit.state.moveTransition(dragIdx, toIdx); } private conditionDragCall(dragIdx: number, toIdx: number) { if (!this._transitionItem || !this._conditionItem) { return; } this._transitionItem.transition.moveCondition(dragIdx, toIdx); } private getTransitionItem() { let prefab = Res.getLoaded(ResUrl.PREFAB.TRANSITION_ITEM); let node: cc.Node = RecyclePool.get(TransitionItem) || cc.instantiate(prefab); node.width = this.TransitionList.node.width; Tool.updateWidget(node); return node; } private putTransitionItem(node: cc.Node) { this._transLayoutDirty = true; RecyclePool.put(TransitionItem, node); } private getConditionItem() { let prefab = Res.getLoaded(ResUrl.PREFAB.CONDITION_ITEM); let node: cc.Node = RecyclePool.get(ConditionItem) || cc.instantiate(prefab); node.width = this.ConditionList.node.width; Tool.updateWidget(node); return node; } private putConditionItem(node: cc.Node) { this._conLayoutDirty = true; RecyclePool.put(ConditionItem, node); } private showUnitInfo() { if (!this._unit) { this.UnitInfo.active = false; return; } if (this._unit instanceof UnitState) { if (this._unit.isAnyState) { this.UnitInfo.active = false; return; } this.NameNode.active = true; this.MotionNode.active = true; this.SpeedNode.active = true; this.MultiplierNode.active = true this.LoopNode.active = true; this._nameEdit.string = this._unit.state.name; this._motionEdit.string = this._unit.state.motion; this._speedEdit.string = `${this._unit.state.speed}`; this._loopToggle.isChecked = this._unit.state.loop; this._multiplierLabel.string = this._unit.state.getMultiplierName(); } else if (this._unit instanceof UnitStateMachine) { this.NameNode.active = true; this.MotionNode.active = false; this.SpeedNode.active = false; this.MultiplierNode.active = false this.LoopNode.active = false; this._nameEdit.string = this._unit.stateMachine.name; } this.UnitInfo.active = true; } private showTransitionInfo() { this.TransitionInfo.active = true; this._transitionItem = null; for (let i = this.TransitionList.node.childrenCount - 1; i >= 0; i--) { this.putTransitionItem(this.TransitionList.node.children[i]); } if (this._unit) { if (this._unit instanceof UnitStateMachine) { this.TransitionInfo.active = false; return; } this._unit.getTransitions().forEach((data: Transition) => { let item = this.getTransitionItem(); this.TransitionList.node.addChild(item); item.getComponent(TransitionItem).onInit(data, this._unit); }); this.TransitionList.canDrag = true; } else if (this._line) { let isFirst: boolean = true; this._line.getTransitions().forEach((data: Transition) => { let item = this.getTransitionItem(); this.TransitionList.node.addChild(item); let transitionItem: TransitionItem = item.getComponent(TransitionItem); transitionItem.onInit(data, this._unit); if (isFirst) { transitionItem.select(isFirst); this._transitionItem = transitionItem; isFirst = false; } }); this.TransitionList.canDrag = false; } } private showConditionInfo() { if (!this._transitionItem) { this.ConditionInfo.active = false; return; } this.ConditionInfo.active = true; this.CurTransLab.string = this._transitionItem.transition.getTransStr(); this.HasExitTime.isChecked = this._transitionItem.transition.hasExitTime; // 根据transition生成condition this._conditionItem = null; for (let i = this.ConditionList.node.childrenCount - 1; i >= 0; i--) { this.putConditionItem(this.ConditionList.node.children[i]); } this._transitionItem.transition.conditions.forEach((e) => { let item = this.getConditionItem(); this.ConditionList.node.addChild(item); item.getComponent(ConditionItem).onInit(e); }); } /** * 隐藏inspector显示的内容 */ private hide() { this._unit = null; this._line = null; this.UnitInfo.active = false; this.TransitionInfo.active = false; this.ConditionInfo.active = false; } //#region editbox、toggle、按钮回调 private onNameChanged() { if (this._unit instanceof UnitState) { if (this._nameEdit.string === '') { this._nameEdit.string = this._unit.state.name; return; } this._unit.state.name = this._nameEdit.string; this._nameEdit.string = this._unit.state.name; } else if (this._unit instanceof UnitStateMachine) { if (this._nameEdit.string === '') { this._nameEdit.string = this._unit.stateMachine.name; return; } this._unit.stateMachine.name = this._nameEdit.string; this._nameEdit.string = this._unit.stateMachine.name; } } private onMotionChanged() { if (!(this._unit instanceof UnitState)) { return; } this._unit.state.motion = this._motionEdit.string; } private onSpeedChanged() { if (!(this._unit instanceof UnitState)) { return; } this._speedEdit.string = this._speedEdit.string.replace(/[^.\d]/g, ''); if (this._speedEdit.string === '') { return; } let speed = parseFloat(this._speedEdit.string); this._unit.state.speed = isNaN(speed) ? 1 : speed; this._speedEdit.string = `${this._unit.state.speed}`; } private onLoopCheckd() { if (!(this._unit instanceof UnitState)) { return; } this._unit.state.loop = this._loopToggle.isChecked; } private onClickMultiplier(event: cc.Event) { if (!(this._unit instanceof UnitState)) { return; } Events.emit(EventName.SHOW_MULTIPLIER, event.target); } private onClickDeleteTransition() { if (!this._transitionItem) { return; } this._transitionItem.delete(); this.putTransitionItem(this._transitionItem.node); this._transitionItem = null; if (this._unit) { this.ConditionInfo.active = false; } else { if (this.TransitionList.node.childrenCount <= 0) { this.hide(); } else { this.ConditionInfo.active = false; } } } private onHasExitTimeCheckd() { if (!this._transitionItem) { return; } this._transitionItem.transition.hasExitTime = this.HasExitTime.isChecked; } private onClickAddCondition() { if (!this._transitionItem) { return; } if (Editor.Inst.Parameters.ParamContent.childrenCount <= 0) { return; } let paramItem: ParamItem = Editor.Inst.Parameters.ParamContent.children[0].getComponent(ParamItem); let data = this._transitionItem.transition.addCondition(paramItem); let node = this.getConditionItem(); this.ConditionList.node.addChild(node); node.getComponent(ConditionItem).onInit(data); } private onClickDeleteCondition() { if (!this._transitionItem || !this._conditionItem) { return; } this._transitionItem.transition.deleteCondition(this._conditionItem.condition); this.putConditionItem(this._conditionItem.node); this._conditionItem = null; } //#endregion //#region 事件监听 @preloadEvent(EventName.STATE_NAME_CHANGED) private onEventStateChanged(unit: UnitState) { if (!this._transitionItem) { return; } this.CurTransLab.string = this._transitionItem.transition.getTransStr(); } @preloadEvent(EventName.TRANSITION_ADD) private onEventTransitionAdd(fromUnit: UnitBase, toUnit: UnitBase, transition: Transition) { if (this._unit === fromUnit) { let item = this.getTransitionItem(); this.TransitionList.node.addChild(item); item.getComponent(TransitionItem).onInit(transition, this._unit); } } @preloadEvent(EventName.TRANSITION_SELECT) private onEventTransitionSelect(item: TransitionItem) { this._transitionItem = item; this.TransitionList.node.children.forEach((e) => { let ti = e.getComponent(TransitionItem); ti.select(ti === item); }); this.showConditionInfo(); } @preloadEvent(EventName.CONDITION_SELECT) private onEventConditionSelect(item: ConditionItem) { this._conditionItem = item; this.ConditionList.node.children.forEach((e) => { let ti = e.getComponent(ConditionItem); ti.select(ti === item); }); } @preloadEvent(EventName.MULTIPLIER_SELECT) private onEventMultiplierSelect(paramItem: ParamItem) { if (!(this._unit instanceof UnitState)) { return; } this._unit.state.multiplierParam = paramItem; this._multiplierLabel.string = this._unit.state.getMultiplierName(); } @preloadEvent(EventName.PARAM_DELETE) private onEventParamDelete(paramItem: ParamItem) { if (!this._transitionItem) { return; } // 删除 if (this._conditionItem && this._conditionItem.condition.paramItem === paramItem) { this._conditionItem = null; } for (let i = this.ConditionList.node.childrenCount - 1; i >= 0; i--) { let ci: ConditionItem = this.ConditionList.node.children[i].getComponent(ConditionItem); if (ci.condition.paramItem === paramItem) { this.putConditionItem(this.ConditionList.node.children[i]); } } } @preloadEvent(EventName.PARAM_NAME_CHANGED) private onEventParamChanged(paramItem: ParamItem) { if (!(this._unit instanceof UnitState) || this._unit.state.multiplierParam !== paramItem) { return; } this._multiplierLabel.string = this._unit.state.multiplierParam.paramName; } @preloadEvent(EventName.INSPECTOR_HIDE) private onEventInspectorHide() { this.hide(); } @preloadEvent(EventName.INSPECTOR_SHOW_UNIT) private onEventShowUnit(unit: UnitBase) { this._unit = unit; this._line = null; this.showUnitInfo(); this.showTransitionInfo(); this.showConditionInfo(); } @preloadEvent(EventName.INSPECTOR_SHOW_LINE) private onEventShowLine(line: Line) { this._unit = null; this._line = line; this.showUnitInfo(); this.showTransitionInfo(); this.showConditionInfo(); } @preloadEvent(EventName.RESIZE) private onEventResize(node: cc.Node) { if (node !== this.node) { return; } Tool.updateWidget(this.node, this.TransitionList.node, this.ConditionList.node); if (!this.TransitionInfo.active) { return; } this.TransitionList.node.children.forEach((e) => { e.width = this.TransitionList.node.width; Tool.updateWidget(e); }); if (!this.ConditionInfo.active) { return; } this.ConditionList.node.children.forEach((e) => { e.width = this.ConditionList.node.width; Tool.updateWidget(e); }); } //#endregion }
the_stack
import { useEffect, useRef, useState } from "react"; import { fireEvent, render, sleep } from "ariakit-test"; import { useBooleanEvent, useControlledState, useEvent, useForceUpdate, useForkRef, useId, useInitialValue, useLazyValue, useLiveRef, usePreviousValue, useRefId, useTagName, useUpdateEffect, useUpdateLayoutEffect, useWrapElement, } from "../hooks"; test("useInitialValue", () => { const TestComponent = () => { const [someState, setSomeState] = useState("some value"); const initialValue = useInitialValue(someState); return ( <button onClick={() => setSomeState("some new value")}> {initialValue} </button> ); }; const { container, getByRole } = render(<TestComponent />); expect(container).toHaveTextContent("some value"); fireEvent.click(getByRole("button")); expect(container).toHaveTextContent("some value"); }); test("useLazyValue", () => { const TestComponent = () => { const [someState, setSomeState] = useState("some value"); const lazyValue = useLazyValue(() => someState); return ( <button onClick={() => setSomeState("some new value")}> {lazyValue} </button> ); }; const { container, getByRole } = render(<TestComponent />); expect(container).toHaveTextContent("some value"); fireEvent.click(getByRole("button")); expect(container).toHaveTextContent("some value"); }); test("useLiveRef", async () => { const effectFunction = jest.fn(); const TestComponent = () => { const [someState, setSomeState] = useState("some value"); const liveRef = useLiveRef(someState); useEffect(() => effectFunction(liveRef.current), [someState]); return <button onClick={() => setSomeState("some new value")} />; }; const { getByRole } = render(<TestComponent />); expect(effectFunction).toHaveBeenCalledTimes(1); expect(effectFunction).toHaveBeenCalledWith("some value"); fireEvent.click(getByRole("button")); expect(effectFunction).toHaveBeenCalledTimes(2); expect(effectFunction).toHaveBeenCalledWith("some new value"); }); test("usePreviousValue", () => { const duringRender = jest.fn(); const TestComponent = () => { const [someState, setSomeState] = useState("some value"); const prevValue = usePreviousValue(someState); duringRender(prevValue); return ( <button onClick={() => setSomeState("some new value")}> {prevValue} </button> ); }; const { container, getByRole } = render(<TestComponent />); expect(container).toHaveTextContent("some value"); fireEvent.click(getByRole("button")); expect(duringRender).nthCalledWith(1, "some value"); expect(duringRender).nthCalledWith(2, "some value"); expect(duringRender).nthCalledWith(3, "some new value"); expect(container).toHaveTextContent("some new value"); }); test("useEvent function is stable", () => { // Check function is stable const effectFunction = jest.fn(); const TestComponent = () => { const [callback, setCallback] = useState(() => effectFunction); const result = useEvent(callback); useEffect(effectFunction, [result]); return <button onClick={() => setCallback(jest.fn())} />; }; const { getByRole } = render(<TestComponent />); expect(effectFunction).toBeCalledTimes(1); fireEvent.click(getByRole("button")); expect(effectFunction).toBeCalledTimes(1); }); test("useEvent errors is used during render", () => { const consoleError = jest.spyOn(console, "error").mockImplementation(); const TestComponent = () => { const result = useEvent(jest.fn()); result(); return null; }; expect(() => render(<TestComponent />)).toThrow( "Cannot call an event handler while rendering." ); consoleError.mockRestore(); }); test("useForkRef", () => { const ref1 = jest.fn(); const ref2 = jest.fn(); const TestComponent = () => { const internalRef = useRef(); const ref = useForkRef(internalRef, ref1, ref2); return <button ref={ref} />; }; const { getByRole } = render(<TestComponent />); expect(ref1).toBeCalledTimes(1); expect(ref2).toBeCalledTimes(1); const button = getByRole("button"); expect(ref1).toHaveBeenCalledWith(button); expect(ref2).toHaveBeenCalledWith(button); }); test("useForkRef no refs provided", () => { let refVal: any; const TestComponent2 = () => { const ref = useForkRef(); refVal = ref; return <div />; }; expect(refVal).toBeUndefined(); render(<TestComponent2 />); expect(refVal).toBeUndefined(); }); test("useRefId", () => { let idVal: string | undefined; const TestComponent = () => { const ref = useRef<HTMLDivElement>(null); const id = useRefId(ref); idVal = id; return <div id="some-id" ref={ref} />; }; expect(idVal).toBeUndefined(); render(<TestComponent />); expect(idVal).toBe("some-id"); }); test("useRefId undefined ref", () => { let idVal: string | undefined; const TestComponent2 = () => { const ref = useRef<HTMLDivElement>(null); const id = useRefId(ref); idVal = id; return <div />; }; expect(idVal).toBeUndefined(); render(<TestComponent2 />); expect(idVal).toBeUndefined(); }); test("useId", () => { const TestComponent = () => { const [idState, setIdState] = useState(""); const id = useId(idState); return <button onClick={() => setIdState("some-id")} id={id} />; }; const { getByRole } = render(<TestComponent />); const button = getByRole("button"); expect(button.id).toBeTruthy(); fireEvent.click(button); expect(button.id).toBe("some-id"); }); test("useTagName", () => { let tagNameVal: string | undefined; const TestComponent = () => { const ref = useRef<HTMLDivElement>(null); const tagName = useTagName(ref); tagNameVal = tagName; return <div ref={ref} />; }; render(<TestComponent />); expect(tagNameVal).toBe("div"); }); test("useTagName with type", () => { let tagNameVal: string | undefined; const TestComponent = () => { const ref = useRef<HTMLDivElement>(null); const tagName = useTagName(ref, "button"); tagNameVal = tagName; return <div ref={ref} />; }; render(<TestComponent />); expect(tagNameVal).toBe("div"); }); test("useTagName with type and element undefined", () => { let tagNameVal: string | undefined; const TestComponent = () => { const ref = useRef<HTMLDivElement>(null); const tagName = useTagName(ref, "button"); tagNameVal = tagName; return <div />; }; render(<TestComponent />); expect(tagNameVal).toBe("button"); }); test("useUpdateEffect", () => { const effectFunction = jest.fn(); const TestComponent = (props: { somePropVale: number }) => { const { somePropVale } = props; useUpdateEffect(effectFunction, [somePropVale]); return <div />; }; const { rerender } = render(<TestComponent somePropVale={0} />); expect(effectFunction).toBeCalledTimes(0); rerender(<TestComponent somePropVale={1} />); expect(effectFunction).toBeCalledTimes(1); rerender(<TestComponent somePropVale={1} />); expect(effectFunction).toBeCalledTimes(1); rerender(<TestComponent somePropVale={2} />); expect(effectFunction).toBeCalledTimes(2); }); test("useUpdateLayoutEffect", () => { const effectFunction = jest.fn(); const TestComponent = (props: { somePropVale: number }) => { const { somePropVale } = props; useUpdateLayoutEffect(effectFunction, [somePropVale]); return <div />; }; const { rerender } = render(<TestComponent somePropVale={0} />); expect(effectFunction).toBeCalledTimes(0); rerender(<TestComponent somePropVale={1} />); expect(effectFunction).toBeCalledTimes(1); rerender(<TestComponent somePropVale={1} />); expect(effectFunction).toBeCalledTimes(1); rerender(<TestComponent somePropVale={2} />); expect(effectFunction).toBeCalledTimes(2); }); test("useControlledState", async () => { const TestComponent = () => { const [controlled, setControlled] = useState(false); const [state, setState] = useState("initial state"); const [controlledState, setControlledState] = useControlledState( "initial controlled state", controlled ? state : undefined, controlled ? setState : undefined ); return ( <div> <button data-testid="controlled" onClick={() => setControlled(!controlled)} /> <button data-testid="update-state" onClick={() => setState("some-state")} /> <button data-testid="update-controlled-state" onClick={() => setControlledState("some-controlled-state")} /> <button data-testid="reset" onClick={() => { setControlled(false); // Have to force this on a separate tick to avoid // the state being reset into the controlled state setTimeout(() => { setState("initial state"); setControlledState("initial controlled state"); }, 0); }} /> <div>{controlledState}</div> </div> ); }; const { container, getByTestId } = render(<TestComponent />); const controlled = getByTestId("controlled"); const updateState = getByTestId("update-state"); const updateControlledState = getByTestId("update-controlled-state"); const reset = getByTestId("reset"); expect(container).toHaveTextContent("initial controlled state"); fireEvent.click(updateControlledState); expect(container).toHaveTextContent("some-controlled-state"); fireEvent.click(controlled); expect(container).toHaveTextContent("initial state"); fireEvent.click(updateState); expect(container).toHaveTextContent("some-state"); fireEvent.click(reset); await sleep(); expect(container).toHaveTextContent("initial controlled state"); fireEvent.click(controlled); expect(container).toHaveTextContent("initial state"); }); test("useForceUpdate", () => { const someFunction = jest.fn(); const TestComponent = () => { const [_, forceUpdateFunc] = useForceUpdate(); someFunction(); useEffect(forceUpdateFunc, []); return <button onClick={() => forceUpdateFunc()} />; }; const { getByRole } = render(<TestComponent />); // Should render twice on mount expect(someFunction).toBeCalledTimes(2); fireEvent.click(getByRole("button")); expect(someFunction).toBeCalledTimes(3); }); test("useBooleanEvent", () => { const someFunc = jest.fn(); const TestComponent = () => { const func = useBooleanEvent(() => true); const bool = useBooleanEvent(true); return ( <div> <button data-testid="func" onClick={() => (func() ? someFunc("func") : null)} /> <button data-testid="bool" onClick={() => (bool() ? someFunc("bool") : null)} /> </div> ); }; const { getByTestId } = render(<TestComponent />); fireEvent.click(getByTestId("func")); expect(someFunc).toBeCalledTimes(1); expect(someFunc).toBeCalledWith("func"); fireEvent.click(getByTestId("bool")); expect(someFunc).toBeCalledTimes(2); expect(someFunc).toBeCalledWith("bool"); }); test("useWrapElement", () => { const DeeplyWrappedComponent = () => { const [count, setCount] = useState(3); const newProps1 = useWrapElement({}, (element) => ( <div data-testid="wrap1">{element}</div> )); const newProps2 = useWrapElement(newProps1, (element) => ( <div data-testid="wrap2">{element}</div> )); const newProps3 = useWrapElement( newProps2, (element) => <div data-testid={`wrap${count}`}>{element}</div>, [count] ); return newProps3.wrapElement( <div data-testid="innerElement"> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); }; const { getByTestId, queryByTestId, getByRole } = render( <DeeplyWrappedComponent /> ); expect(getByTestId("wrap1")).toBeInTheDocument(); expect(getByTestId("wrap2")).toBeInTheDocument(); expect(getByTestId("wrap3")).toBeInTheDocument(); expect(getByTestId("innerElement")).toBeInTheDocument(); fireEvent.click(getByRole("button")); expect(getByTestId("wrap1")).toBeInTheDocument(); expect(getByTestId("wrap2")).toBeInTheDocument(); expect(queryByTestId("wrap3")).not.toBeInTheDocument(); expect(getByTestId("wrap4")).toBeInTheDocument(); });
the_stack
import assert from 'assert'; import * as semver from 'semver'; import * as rpc from 'transparent-rpc'; import * as Tp from 'thingpedia'; import * as ThingTalk from 'thingtalk'; import * as Config from '../config'; import * as db from './db'; import * as device from '../model/device'; import * as organization from '../model/organization'; import * as schemaModel from '../model/schema'; import * as exampleModel from '../model/example'; import * as entityModel from '../model/entity'; import * as stringModel from '../model/strings'; import * as discovery from './discovery'; import * as DatasetUtils from './dataset'; import * as SchemaUtils from './manifest_to_schema'; import * as I18n from './i18n'; import * as codeStorage from './code_storage'; import { NotFoundError, ForbiddenError, BadRequestError } from './errors'; import resolveLocation from './location-linking'; import { parseOldOrNewSyntax } from './compat'; const CATEGORIES = new Set(['media', 'social-network', 'home', 'communication', 'health', 'service', 'data-management']); // FIXME this info needs to be in Thingpedia interface ExtendedEntityRecord extends Tp.BaseClient.EntityTypeRecord { subtype_of ?: string[]|null; } export default class ThingpediaClientCloud extends Tp.BaseClient implements rpc.Stubbable<keyof Tp.BaseClient> { $rpcMethods = [ 'getModuleLocation', 'getDeviceCode', 'getSchemas', 'getMixins', 'getDeviceSetup', 'getDeviceFactories', 'getDeviceList', 'searchDevice', 'getKindByDiscovery', 'getExamplesByKinds', 'getExamplesByKey', 'clickExample', 'lookupEntity', 'lookupLocation', 'getAllEntityTypes', ] as const; private _developerKey : string|null; private _locale : string; protected language : string; protected _dbClient : db.Client|null; private _thingtalkVersion : string; private _needsCompatibility : boolean; constructor(developerKey : string|null|undefined, locale ?: string, thingtalk_version ?: string, dbClient : db.Client|null = null) { super(); this._developerKey = developerKey ?? null; this._locale = locale || 'en-US'; this.language = I18n.localeToLanguage(this._locale); this._dbClient = dbClient; this._thingtalkVersion = thingtalk_version || ThingTalk.version; this._needsCompatibility = semver.satisfies(this._thingtalkVersion, '<2.0.0'); } get developerKey() { return this._developerKey; } get locale() { return this._locale; } protected _withClient<T>(func : (client : db.Client) => Promise<T>) : Promise<T> { if (this._dbClient) return func(this._dbClient); else return db.withClient(func); } protected async _getOrg(dbClient : db.Client) : Promise<{ id : number, is_admin : boolean }|null> { if (!this.developerKey) return null; const [org] = await organization.getByDeveloperKey(dbClient, this.developerKey); return org || null; } protected async _getOrgId(dbClient : db.Client) { const org = await this._getOrg(dbClient); if (org === null) return null; else if (org.is_admin) return -1; else return org.id; } async getModuleLocation(kind : string, version ?: number) { const [approvedVersion, maxVersion] = await this._withClient(async (dbClient) => { const org = await this._getOrg(dbClient); const dev = await device.getDownloadVersion(dbClient, kind, org); if (!dev.downloadable) throw new BadRequestError('No Code Available'); return [dev.approved_version, dev.version]; }); if (maxVersion === null || (version !== undefined && version > maxVersion)) throw new ForbiddenError('Not Authorized'); if (version === undefined) version = maxVersion; const developer = approvedVersion === null || version > approvedVersion; return codeStorage.getDownloadLocation(kind, version, developer); } getDeviceCode(kind : string) { return this._withClient(async (dbClient) => { const orgId = await this._getOrgId(dbClient); const classes = await this._internalGetDeviceCode([kind], orgId, dbClient); if (classes.length < 1) throw new NotFoundError(); return classes[0]; }); } private async _internalGetDeviceCode(kinds : string[], orgId : number|null, dbClient : db.Client) { const devs = await device.getFullCodeByPrimaryKinds(dbClient, kinds, orgId); let schemas : schemaModel.SchemaMetadata[]|undefined; if (this.language !== 'en') schemas = await schemaModel.getMetasByKinds(dbClient, kinds, orgId, this.language); return Promise.all(devs.map(async (dev) => { const code = dev.code; // fast path without parsing the code if (this.language === 'en' && !this._needsCompatibility && !/(makeArgMap|\$context)/.test(code) /* quick check for old-syntax constructs */) return code; const parsed = parseOldOrNewSyntax(code, { locale: 'en-US', timezone: 'UTC' }); assert(parsed instanceof ThingTalk.Ast.Library); const classDef = parsed.classes[0]; if (this.language !== 'en') { assert(schemas); const schema = schemas.find((schema) => schema.kind === dev.primary_kind); if (schema) SchemaUtils.mergeClassDefAndSchema(classDef, schema); } return ThingTalk.Syntax.serialize(parsed, ThingTalk.Syntax.SyntaxType.Normal, undefined, { compatibility: this._thingtalkVersion }); })); } getSchemas(schemas : string[], withMetadata ?: boolean) { if (schemas.length === 0) return Promise.resolve(''); return this._withClient(async (dbClient) => { if (withMetadata) { const orgId = await this._getOrgId(dbClient); return (await this._internalGetDeviceCode(schemas, orgId, dbClient)).join('\n'); } else { const rows = await schemaModel.getTypesAndNamesByKinds(dbClient, schemas, await this._getOrgId(dbClient)); const classDefs = SchemaUtils.schemaListToClassDefs(rows, false); return ThingTalk.Syntax.serialize(classDefs, ThingTalk.Syntax.SyntaxType.Normal, undefined, { compatibility: this._thingtalkVersion }); } }); } searchDevice(q : string) { return this._withClient(async (dbClient) => { const org = await this._getOrg(dbClient); return device.getByFuzzySearch(dbClient, q, org); }); } getDeviceList(klass : string|undefined, page : number, page_size : number) { return this._withClient(async (dbClient) => { const org = await this._getOrg(dbClient); if (klass) { if (['online','physical','data','system'].indexOf(klass) >= 0) return device.getByCategory(dbClient, klass, org, page*page_size, page_size+1); else if (CATEGORIES.has(klass)) return device.getBySubcategory(dbClient, klass, org, page*page_size, page_size+1); else throw new BadRequestError("Invalid class parameter"); } else { return device.getAllApproved(dbClient, org, page*page_size, page_size+1); } }); } private _ensureDeviceFactory(device : device.FactoryRow) : Tp.BaseClient.DeviceFactory|null { if (device.factory !== null) return typeof device.factory === 'string' ? JSON.parse(device.factory) : device.factory; return null; } getDeviceFactories(klass ?: string) { return this._withClient(async (dbClient) => { const org = await this._getOrg(dbClient); let devices; if (klass) { if (['online','physical','data','system'].indexOf(klass) >= 0) devices = await device.getByCategoryWithCode(dbClient, klass, org); else if (CATEGORIES.has(klass)) devices = await device.getBySubcategoryWithCode(dbClient, klass, org); else throw new BadRequestError("Invalid class parameter"); } else { devices = await device.getAllApprovedWithCode(dbClient, org); } const factories = []; for (const d of devices) { const factory = this._ensureDeviceFactory(d); if (factory) factories.push(factory); } return factories; }); } getDeviceSetup(kinds : string[]) { if (kinds.length === 0) return Promise.resolve({}); return this._withClient(async (dbClient) => { const org = await this._getOrg(dbClient); for (let i = 0; i < kinds.length; i++) { if (kinds[i] === 'messaging') kinds[i] = Config.MESSAGING_DEVICE; } const devices = await device.getDevicesForSetup(dbClient, kinds, org); const names : Record<string, string> = {}; devices.forEach((d) => { names[d.primary_kind] = d.name; }); const result : Record<string, Tp.BaseClient.DeviceFactory | Tp.BaseClient.MultipleDeviceFactory> = {}; devices.forEach((d : any) => { try { d.factory = this._ensureDeviceFactory(d); if (d.factory) { if (d.for_kind in result) { if (result[d.for_kind].type !== 'multiple') { const first_choice = result[d.for_kind]; assert(first_choice.type !== 'multiple'); result[d.for_kind] = { type: 'multiple', text: names[d.for_kind] || d.for_kind, choices: [first_choice] }; } const existing = result[d.for_kind]; assert(existing.type === 'multiple'); existing.choices.push(d.factory); } else { result[d.for_kind] = d.factory; } if (d.for_kind === Config.MESSAGING_DEVICE) result['messaging'] = d.factory; } } catch(e) { /**/ } }); for (const kind of kinds) { if (!(kind in result)) result[kind] = { type: 'multiple', text: names[kind] || kind, choices: [] }; } return result; }); } getKindByDiscovery(body : any) : Promise<string> { return this._withClient(async (dbClient) => { const decoded = await discovery.decode(dbClient, body); if (decoded === null) throw new NotFoundError(); return decoded.primary_kind; }); } private _makeDataset(name : string, rows : Array<Omit<exampleModel.PrimitiveTemplateRow, "language"|"type">>, dbClient : db.Client, options = {}) { return DatasetUtils.examplesToDataset(`org.thingpedia.dynamic.${name}`, this.language, rows, { dbClient: dbClient, needs_compatibility: this._needsCompatibility, thingtalk_version: this._thingtalkVersion, ...options }); } getExamplesByKey(key : string, accept = 'application/x-thingtalk') { return this._withClient(async (dbClient) => { const rows = await exampleModel.getByKey(dbClient, key, await this._getOrgId(dbClient), this.language); switch (accept) { case 'application/x-thingtalk;editMode=1': return this._makeDataset(`by_key.${key.replace(/[^a-zA-Z0-9]+/g, '_')}`, rows, dbClient, { editMode: true }); default: return this._makeDataset(`by_key.${key.replace(/[^a-zA-Z0-9]+/g, '_')}`, rows, dbClient); } }); } getExamplesByKinds(kinds : string[], accept = 'application/x-thingtalk') { if (!Array.isArray(kinds)) kinds = [kinds]; if (kinds.length === 0) return Promise.resolve(''); return this._withClient(async (dbClient) => { const rows = await exampleModel.getByKinds(dbClient, kinds, await this._getOrgId(dbClient), this.language); switch (accept) { case 'application/x-thingtalk;editMode=1': if (kinds.length === 1) return this._makeDataset(kinds[0], rows, dbClient, { editMode: true }); return this._makeDataset(`by_kinds.${kinds.map((k) => k.replace(/[^a-zA-Z0-9]+/g, '_')).join('__')}`, rows, dbClient, { editMode: true }); default: return this._makeDataset(`by_kinds.${kinds.map((k) => k.replace(/[^a-zA-Z0-9]+/g, '_')).join('__')}`, rows, dbClient); } }); } getAllExamples(accept = 'application/x-thingtalk') { return this._withClient(async (dbClient) => { const rows = await exampleModel.getBaseByLanguage(dbClient, await this._getOrgId(dbClient), this.language); switch (accept) { case 'application/x-thingtalk;editMode=1': return this._makeDataset(`everything`, rows, dbClient, { editMode: true }); default: return this._makeDataset(`everything`, rows, dbClient); } }); } clickExample(exampleId : number) { return this._withClient((dbClient) => { return exampleModel.click(dbClient, exampleId); }); } lookupEntity(entityType : string, searchTerm : string) { return this._withClient((dbClient) => { return Promise.all([entityModel.lookupWithType(dbClient, this.language, entityType, searchTerm), entityModel.get(dbClient, entityType, this.language)]); }).then(([rows, metarows]) => { const data = rows.map((r) => ({ type: r.entity_id, value: r.entity_value, canonical: r.entity_canonical, name: r.entity_name })); const meta = { name: metarows.name, has_ner_support: metarows.has_ner_support, is_well_known: metarows.is_well_known }; return { data, meta }; }); } lookupLocation(searchTerm : string, around ?: { latitude : number; longitude : number; }) { return resolveLocation(this.locale, searchTerm, around); } getAllDeviceNames() { return this._withClient(async (dbClient) => { return schemaModel.getAllApproved(dbClient, await this._getOrgId(dbClient)); }); } async getThingpediaSnapshot(getMeta ?: boolean, snapshotId = -1) { return this._withClient(async (dbClient) => { if (snapshotId >= 0) { if (getMeta) return schemaModel.getSnapshotMeta(dbClient, snapshotId, this.language, await this._getOrgId(dbClient)); else return schemaModel.getSnapshotTypes(dbClient, snapshotId, await this._getOrgId(dbClient)); } else { if (getMeta) return schemaModel.getCurrentSnapshotMeta(dbClient, this.language, await this._getOrgId(dbClient)); else return schemaModel.getCurrentSnapshotTypes(dbClient, await this._getOrgId(dbClient)); } }); } getAllEntityTypes(snapshotId = -1) : Promise<ExtendedEntityRecord[]> { return this._withClient((dbClient) => { if (snapshotId >= 0) return entityModel.getSnapshot(dbClient, snapshotId); else return entityModel.getAll(dbClient); }).then((rows) => { return rows.map((r) => ({ type: r.id, name: r.name, is_well_known: r.is_well_known, has_ner_support: r.has_ner_support, subtype_of: r.subtype_of ? (r.subtype_of.startsWith('[') ? JSON.parse(r.subtype_of) : [r.subtype_of]) : [] })); }); } getAllStrings() { return this._withClient((dbClient) => { return stringModel.getAll(dbClient, this.language); }).then((rows) => { return rows.map((r) => ({ type: r.type_name, name: r.name, license: r.license, attribution: r.attribution })); }); } invokeQuery() : never { throw new Error(`not implemented yet`); } }
the_stack
import * as React from 'react'; import { getAccumulatedTrafficRateGrpc, getAccumulatedTrafficRateHttp, getTrafficRateGrpc, getTrafficRateHttp } from '../../utils/TrafficRate'; import { InOutRateTableGrpc, InOutRateTableHttp } from '../../components/SummaryPanel/InOutRateTable'; import { RequestChart, StreamChart } from '../../components/SummaryPanel/RpsChart'; import { GraphType, NodeType, SummaryPanelPropType, Protocol, DecoratedGraphNodeData, UNKNOWN, TrafficRate } from '../../types/Graph'; import { IstioMetricsMap, Datapoint, Labels } from '../../types/Metrics'; import { shouldRefreshData, NodeMetricType, getDatapoints, getNodeMetrics, getNodeMetricType, renderNoTraffic, mergeMetricsResponses, hr } from './SummaryPanelCommon'; import { CancelablePromise, makeCancelablePromise } from '../../utils/CancelablePromises'; import { Response } from '../../services/Api'; import { Reporter } from '../../types/MetricsOptions'; import { CyNode, decoratedNodeData } from '../../components/CytoscapeGraph/CytoscapeGraphUtils'; import { KialiIcon } from 'config/KialiIcon'; type SummaryPanelNodeMetricsState = { grpcRequestCountIn: Datapoint[]; grpcRequestCountOut: Datapoint[]; grpcErrorCountIn: Datapoint[]; grpcErrorCountOut: Datapoint[]; grpcSentIn: Datapoint[]; grpcSentOut: Datapoint[]; grpcReceivedIn: Datapoint[]; grpcReceivedOut: Datapoint[]; httpRequestCountIn: Datapoint[] | null; httpRequestCountOut: Datapoint[]; httpErrorCountIn: Datapoint[]; httpErrorCountOut: Datapoint[]; tcpSentIn: Datapoint[]; tcpSentOut: Datapoint[]; tcpReceivedIn: Datapoint[]; tcpReceivedOut: Datapoint[]; }; type SummaryPanelNodeState = SummaryPanelNodeMetricsState & { node: any; loading: boolean; metricsLoadError: string | null; }; const defaultMetricsState: SummaryPanelNodeMetricsState = { grpcRequestCountIn: [], grpcRequestCountOut: [], grpcErrorCountIn: [], grpcErrorCountOut: [], grpcSentIn: [], grpcSentOut: [], grpcReceivedIn: [], grpcReceivedOut: [], httpRequestCountIn: [], httpRequestCountOut: [], httpErrorCountIn: [], httpErrorCountOut: [], tcpSentIn: [], tcpSentOut: [], tcpReceivedIn: [], tcpReceivedOut: [] }; const defaultState: SummaryPanelNodeState = { node: null, loading: false, metricsLoadError: null, ...defaultMetricsState }; type SummaryPanelNodeProps = SummaryPanelPropType; export class SummaryPanelNodeTraffic extends React.Component<SummaryPanelNodeProps, SummaryPanelNodeState> { private metricsPromise?: CancelablePromise<Response<IstioMetricsMap>[]>; constructor(props: SummaryPanelNodeProps) { super(props); this.showTrafficMetrics = this.showTrafficMetrics.bind(this); this.state = { ...defaultState }; } static getDerivedStateFromProps(props: SummaryPanelNodeProps, state: SummaryPanelNodeState) { // if the summaryTarget (i.e. selected node) has changed, then init the state and set to loading. The loading // will actually be kicked off after the render (in componentDidMount/Update). return props.data.summaryTarget !== state.node ? { node: props.data.summaryTarget, loading: true, ...defaultMetricsState } : null; } componentDidMount() { this.updateCharts(this.props); } componentDidUpdate(prevProps: SummaryPanelNodeProps) { if (shouldRefreshData(prevProps, this.props)) { this.updateCharts(this.props); } } componentWillUnmount() { if (this.metricsPromise) { this.metricsPromise.cancel(); } } updateCharts(props: SummaryPanelNodeProps) { const target = props.data.summaryTarget; const nodeData = decoratedNodeData(target); const nodeMetricType = getNodeMetricType(nodeData); const isGrpcRequests = this.isGrpcRequests(); if (this.metricsPromise) { this.metricsPromise.cancel(); this.metricsPromise = undefined; } if (!this.hasGrpcTraffic(nodeData) && !this.hasHttpTraffic(nodeData) && !this.hasTcpTraffic(nodeData)) { this.setState({ loading: false }); return; } // If destination node is inaccessible, we cannot query the data. if (nodeData.isInaccessible) { this.setState({ loading: false }); return; } let promiseIn: Promise<Response<IstioMetricsMap>> = Promise.resolve({ data: {} }); let promiseOut: Promise<Response<IstioMetricsMap>> = Promise.resolve({ data: {} }); // set inbound unless it is a root (because they have no inbound edges) if (!nodeData.isRoot) { const isServiceDestCornerCase = this.isServiceDestCornerCase(nodeMetricType); let promiseRps: Promise<Response<IstioMetricsMap>> = Promise.resolve({ data: {} }); let promiseStream: Promise<Response<IstioMetricsMap>> = Promise.resolve({ data: {} }); if (this.hasHttpIn(nodeData) || (this.hasGrpcIn(nodeData) && isGrpcRequests)) { const filtersRps = ['request_count', 'request_error_count']; // use dest metrics for inbound, except for service nodes which need source metrics to capture source errors const reporter: Reporter = nodeData.nodeType === NodeType.SERVICE && nodeData.isIstio ? 'source' : 'destination'; // For special service dest nodes we want to narrow the data to only TS with 'unknown' workloads (see the related // comparator in getNodeDatapoints). const byLabelsRps = isServiceDestCornerCase ? ['destination_workload', 'request_protocol'] : ['request_protocol']; if (nodeData.isOutside) { byLabelsRps.push('source_workload_namespace'); } promiseRps = getNodeMetrics( nodeMetricType, target, props, filtersRps, 'inbound', reporter, undefined, undefined, byLabelsRps ); } // Aggregate nodes currently only deal with request traffic if (nodeData.nodeType !== NodeType.AGGREGATE) { const filtersStream = [] as string[]; if (this.hasGrpcIn(nodeData)) { filtersStream.push('grpc_sent', 'grpc_received'); } if (this.hasTcpIn(nodeData)) { filtersStream.push('tcp_sent', 'tcp_received'); } if (filtersStream.length > 0) { const byLabelsStream = isServiceDestCornerCase ? ['destination_workload'] : []; if (nodeData.isOutside) { byLabelsStream.push('source_workload_namespace'); } promiseStream = getNodeMetrics( nodeMetricType, target, props, filtersStream, 'inbound', 'source', undefined, undefined, byLabelsStream ); } } promiseIn = mergeMetricsResponses([promiseRps, promiseStream]); } // Ignore outbound traffic if it is a non-root outsider (because they have no outbound edges) or a // service node or aggregate node (because they don't have "real" outbound edges). if ( !([NodeType.SERVICE, NodeType.AGGREGATE].includes(nodeData.nodeType) || (nodeData.isOutside && !nodeData.isRoot)) ) { const filters = [] as string[]; if (this.hasHttpOut(nodeData) || (this.hasGrpcOut(nodeData) && isGrpcRequests)) { filters.push('request_count', 'request_error_count'); } if (this.hasGrpcOut(nodeData) && !isGrpcRequests) { filters.push('grpc_sent', 'grpc_received'); } if (this.hasTcpOut(nodeData)) { filters.push('tcp_sent', 'tcp_received'); } if (filters.length > 0) { // use source metrics for outbound, except for: // - unknown nodes (no source telemetry) // - istio namespace nodes (no source telemetry) const reporter: Reporter = nodeData.nodeType === NodeType.UNKNOWN || nodeData.isIstio ? 'destination' : 'source'; // note: request_protocol is not a valid byLabel for tcp filters but it is ignored by prometheus const byLabels = nodeData.isOutside ? ['destination_service_namespace', 'request_protocol'] : ['request_protocol']; promiseOut = getNodeMetrics( nodeMetricType, target, props, filters, 'outbound', reporter, undefined, undefined, byLabels ); } } this.metricsPromise = makeCancelablePromise(Promise.all([promiseOut, promiseIn])); this.metricsPromise.promise .then(responses => { this.showTrafficMetrics(responses[0].data, responses[1].data, nodeData, nodeMetricType); }) .catch(error => { if (error.isCanceled) { console.debug('SummaryPanelNode: Ignore fetch error (canceled).'); return; } const errorMsg = error.response && error.response.data.error ? error.response.data.error : error.message; this.setState({ loading: false, metricsLoadError: errorMsg, ...defaultMetricsState }); }); this.setState({ loading: true, metricsLoadError: null }); } showTrafficMetrics( outbound: IstioMetricsMap, inbound: IstioMetricsMap, data: DecoratedGraphNodeData, nodeMetricType: NodeMetricType ) { let comparator = (labels: Labels, protocol?: Protocol) => { return protocol ? labels.request_protocol === protocol : true; }; if (this.isServiceDestCornerCase(nodeMetricType)) { comparator = (labels: Labels, protocol?: Protocol) => { return (protocol ? labels.request_protocol === protocol : true) && labels.destination_workload === UNKNOWN; }; } else if (data.isOutside) { // filter out traffic completely outside the active namespaces comparator = (labels: Labels, protocol?: Protocol) => { if (protocol && labels.request_protocol !== protocol) { return false; } if (labels.destination_service_namespace && !this.isActiveNamespace(labels.destination_service_namespace)) { return false; } if (labels.source_workload_namespace && !this.isActiveNamespace(labels.source_workload_namespace)) { return false; } return true; }; } const rcOut = outbound.request_count; const ecOut = outbound.request_error_count; const grpcSentOut = outbound.grpc_sent; const grpcReceivedOut = outbound.grpc_received; const tcpSentOut = outbound.tcp_sent; const tcpReceivedOut = outbound.tcp_received; const rcIn = inbound.request_count; const ecIn = inbound.request_error_count; const grpcSentIn = inbound.grpc_sent; const grpcReceivedIn = inbound.grpc_received; const tcpSentIn = inbound.tcp_sent; const tcpReceivedIn = inbound.tcp_received; this.setState({ loading: false, grpcErrorCountIn: getDatapoints(ecIn, comparator, Protocol.GRPC), grpcErrorCountOut: getDatapoints(ecOut, comparator, Protocol.GRPC), grpcReceivedIn: getDatapoints(grpcReceivedIn, comparator), grpcReceivedOut: getDatapoints(grpcReceivedOut, comparator), grpcRequestCountIn: getDatapoints(rcIn, comparator, Protocol.GRPC), grpcRequestCountOut: getDatapoints(rcOut, comparator, Protocol.GRPC), grpcSentIn: getDatapoints(grpcSentIn, comparator), grpcSentOut: getDatapoints(grpcSentOut, comparator), httpErrorCountIn: getDatapoints(ecIn, comparator, Protocol.HTTP), httpErrorCountOut: getDatapoints(ecOut, comparator, Protocol.HTTP), httpRequestCountIn: getDatapoints(rcIn, comparator, Protocol.HTTP), httpRequestCountOut: getDatapoints(rcOut, comparator, Protocol.HTTP), tcpReceivedIn: getDatapoints(tcpReceivedIn, comparator), tcpReceivedOut: getDatapoints(tcpReceivedOut, comparator), tcpSentIn: getDatapoints(tcpSentIn, comparator), tcpSentOut: getDatapoints(tcpSentOut, comparator) }); } isActiveNamespace = (namespace: string): boolean => { if (!namespace) { return false; } for (const ns of this.props.namespaces) { if (ns.name === namespace) { return true; } } return false; }; render() { const node = this.props.data.summaryTarget; const nodeData = decoratedNodeData(node); const hasGrpc = this.hasGrpcTraffic(nodeData); const hasGrpcIn = hasGrpc && this.hasGrpcIn(nodeData); const hasGrpcOut = hasGrpc && this.hasGrpcOut(nodeData); const hasHttp = this.hasHttpTraffic(nodeData); const hasHttpIn = hasHttp && this.hasHttpIn(nodeData); const hasHttpOut = hasHttp && this.hasHttpOut(nodeData); const hasTcp = this.hasTcpTraffic(nodeData); const hasTcpIn = hasTcp && this.hasTcpIn(nodeData); const hasTcpOut = hasTcp && this.hasTcpOut(nodeData); return ( <> {hasGrpc && this.isGrpcRequests() && ( <> {this.renderGrpcRates(node)} {hr()} </> )} {hasHttp && ( <> {this.renderHttpRates(node)} {hr()} </> )} <div> {this.renderSparklines(node)} {hr()} </div> {hasGrpc && !hasGrpcIn && renderNoTraffic('gRPC inbound')} {hasGrpc && !hasGrpcOut && renderNoTraffic('gRPC outbound')} {!hasGrpc && renderNoTraffic('gRPC')} {hasHttp && !hasHttpIn && renderNoTraffic('HTTP inbound')} {hasHttp && !hasHttpOut && renderNoTraffic('HTTP outbound')} {!hasHttp && renderNoTraffic('HTTP')} {hasTcp && !hasTcpIn && renderNoTraffic('TCP inbound')} {hasTcp && !hasTcpOut && renderNoTraffic('TCP outbound')} {!hasTcp && renderNoTraffic('TCP')} </> ); } private renderGrpcRates = node => { const inbound = getTrafficRateGrpc(node); const outbound = getAccumulatedTrafficRateGrpc(this.props.data.summaryTarget.edgesTo('*')); return ( <> <InOutRateTableGrpc title="gRPC Traffic (requests per second):" inRate={inbound.rate} inRateGrpcErr={inbound.rateGrpcErr} inRateNR={inbound.rateNoResponse} outRate={outbound.rate} outRateGrpcErr={outbound.rateGrpcErr} outRateNR={outbound.rateNoResponse} /> </> ); }; private renderHttpRates = node => { const inbound = getTrafficRateHttp(node); const outbound = getAccumulatedTrafficRateHttp(this.props.data.summaryTarget.edgesTo('*')); return ( <> <InOutRateTableHttp title="HTTP (requests per second):" inRate={inbound.rate} inRate3xx={inbound.rate3xx} inRate4xx={inbound.rate4xx} inRate5xx={inbound.rate5xx} inRateNR={inbound.rateNoResponse} outRate={outbound.rate} outRate3xx={outbound.rate3xx} outRate4xx={outbound.rate4xx} outRate5xx={outbound.rate5xx} outRateNR={outbound.rateNoResponse} /> </> ); }; private renderSparklines = node => { const nodeData = decoratedNodeData(node); if (NodeType.UNKNOWN === nodeData.nodeType) { return ( <> <div> <KialiIcon.Info /> Sparkline charts not supported for unknown node. Use edge for details. </div> </> ); } else if (nodeData.isInaccessible) { return ( <> <div> <KialiIcon.Info /> Sparkline charts cannot be shown because the selected node is inaccessible. </div> </> ); } else if (nodeData.isServiceEntry) { return ( <> <div> <KialiIcon.Info /> Sparkline charts cannot be shown because the selected node is a serviceEntry. </div> </> ); } if (this.state.loading) { return <strong>Loading charts...</strong>; } if (this.state.metricsLoadError) { return ( <div> <KialiIcon.Warning /> <strong>Error loading metrics: </strong> {this.state.metricsLoadError} </div> ); } const isServiceNode = nodeData.nodeType === NodeType.SERVICE; const isInOutSameNode = isServiceNode || nodeData.nodeType === NodeType.AGGREGATE; let serviceWithUnknownSource: boolean = false; if (isServiceNode) { node.incomers().forEach(n => { if (NodeType.UNKNOWN === n.data(CyNode.nodeType)) { serviceWithUnknownSource = true; return false; // Equivalent of break for cytoscapejs forEach API } return undefined; // Every code paths needs to return something to avoid the wrath of the linter. }); } let grpcCharts, httpCharts, tcpCharts; if (this.hasGrpcTraffic(nodeData)) { grpcCharts = this.isGrpcRequests() ? ( <> {this.hasGrpcIn(nodeData) && ( <> <RequestChart label={isInOutSameNode ? 'gRPC - Request Traffic' : 'gRPC - Inbound Request Traffic'} dataRps={this.state.grpcRequestCountIn!} dataErrors={this.state.grpcErrorCountIn} /> {serviceWithUnknownSource && ( <> <div> <KialiIcon.Info /> Traffic from unknown not included. Use edge for details. </div> </> )} </> )} {this.hasGrpcIn(nodeData) && ( <> <RequestChart label="gRPC - Outbound Request Traffic" dataRps={this.state.grpcRequestCountOut} dataErrors={this.state.grpcErrorCountOut} hide={isInOutSameNode} /> {this.isIstioOutboundCornerCase(node) && ( <> <div> <KialiIcon.Info /> Traffic to Istio namespaces not included. Use edge for details. </div> </> )} </> )} </> ) : ( <> {this.hasGrpcIn(nodeData) && ( <StreamChart label={isInOutSameNode ? 'gRPC - Traffic' : 'gRPC - Inbound Traffic'} receivedRates={this.state.grpcReceivedIn} sentRates={this.state.grpcSentIn} unit="messages" /> )} {this.hasGrpcOut(nodeData) && ( <StreamChart label="gRPC - Outbound Traffic" receivedRates={this.state.grpcReceivedOut} sentRates={this.state.grpcSentOut} hide={isInOutSameNode} unit="messages" /> )} </> ); } if (this.hasHttpTraffic(nodeData)) { httpCharts = ( <> {this.hasHttpIn(nodeData) && ( <> <RequestChart label={isInOutSameNode ? 'HTTP - Request Traffic' : 'HTTP - Inbound Request Traffic'} dataRps={this.state.httpRequestCountIn!} dataErrors={this.state.httpErrorCountIn} /> {serviceWithUnknownSource && ( <> <div> <KialiIcon.Info /> Traffic from unknown not included. Use edge for details. </div> </> )} </> )} {this.hasHttpOut(nodeData) && ( <> <RequestChart label="HTTP - Outbound Request Traffic" dataRps={this.state.httpRequestCountOut} dataErrors={this.state.httpErrorCountOut} hide={isInOutSameNode} /> {this.isIstioOutboundCornerCase(node) && ( <> <div> <KialiIcon.Info />" Traffic to Istio namespaces not included. Use edge for details. </div> </> )} </> )} </> ); } if (this.hasTcpTraffic(nodeData)) { tcpCharts = ( <> {this.hasTcpIn(nodeData) && ( <StreamChart label={isInOutSameNode ? 'TCP - Traffic' : 'TCP - Inbound Traffic'} receivedRates={this.state.tcpReceivedIn} sentRates={this.state.tcpSentIn} unit="bytes" /> )} {this.hasTcpOut(nodeData) && ( <StreamChart label="TCP - Outbound Traffic" receivedRates={this.state.tcpReceivedOut} sentRates={this.state.tcpSentOut} hide={isInOutSameNode} unit="bytes" /> )} </> ); } return ( <> {grpcCharts} {httpCharts} {tcpCharts} </> ); }; // We need to handle the special case of a dest service node showing client failures. These service nodes show up in // non-service graphs, even when not injecting service nodes. private isServiceDestCornerCase = (nodeMetricType: NodeMetricType): boolean => { return ( nodeMetricType === NodeMetricType.SERVICE && !this.props.injectServiceNodes && this.props.graphType !== GraphType.SERVICE ); }; // We need to handle the special case of a non-istio, non-unknown node with outbound traffic to istio. // The traffic is lost because it is dest-only and we use source-reporting. private isIstioOutboundCornerCase = (node): boolean => { const nodeData = decoratedNodeData(node); if (nodeData.nodeType === NodeType.UNKNOWN || nodeData.isIstio) { return false; } return node.edgesTo(`node[?${CyNode.isIstio}]`).size() > 0; }; private hasGrpcTraffic = (data: DecoratedGraphNodeData): boolean => { return this.hasGrpcIn(data) || this.hasGrpcOut(data); }; private isGrpcRequests = (): boolean => { return this.props.trafficRates.includes(TrafficRate.GRPC_REQUEST); }; private hasHttpTraffic = (data: DecoratedGraphNodeData): boolean => { return this.hasHttpIn(data) || this.hasHttpOut(data); }; private hasTcpTraffic = (data: DecoratedGraphNodeData): boolean => { return this.hasTcpIn(data) || this.hasTcpOut(data); }; private hasGrpcIn = (data: DecoratedGraphNodeData): boolean => { return data.grpcIn > 0; }; private hasHttpIn = (data: DecoratedGraphNodeData): boolean => { return data.httpIn > 0; }; private hasTcpIn = (data: DecoratedGraphNodeData): boolean => { return data.tcpIn > 0; }; private hasGrpcOut = (data: DecoratedGraphNodeData): boolean => { return data.grpcOut > 0; }; private hasHttpOut = (data: DecoratedGraphNodeData): boolean => { return data.httpOut > 0; }; private hasTcpOut = (data: DecoratedGraphNodeData): boolean => { return data.tcpOut > 0; }; }
the_stack
import * as pci from "@akashic/pdi-common-impl"; import { AssetLoadHandler, AssetLoadError, AudioAssetHint, CompositeOperationString, FontWeightString, ImageData, OperationPluginViewInfo, ScriptAssetRuntimeValue, AudioSystem as PdiAudioSystem, Asset as PdiAsset, Glyph as PdiGlyph, GlyphFactory as PdiGlyphFactory, Surface as PdiSurface, Renderer as PdiRenderer, VideoPlayer as PdiVideoPlayer, VideoSystem as PdiVideoSystem } from "@akashic/pdi-types"; import * as pl from "@akashic/playlog"; import * as g from "../.."; declare global { namespace NodeJS { interface Global { g: any; } } } global.g = g; export class Renderer extends pci.Renderer { methodCallHistoryWithParams: { methodName: string; params?: {}; }[]; constructor() { super(); this.methodCallHistoryWithParams = []; } clearMethodCallHistory(): void { this.methodCallHistoryWithParams = []; } clear(): void { this.methodCallHistoryWithParams.push({ methodName: "clear" }); } get methodCallHistory(): string[] { const ret: string[] = []; for (let i = 0; i < this.methodCallHistoryWithParams.length; ++i) ret.push(this.methodCallHistoryWithParams[i].methodName); return ret; } /** * 指定したメソッド名のパラメータを配列にして返す */ methodCallParamsHistory(name: string): any[] { const params: any[] = []; for (let i = 0; i < this.methodCallHistoryWithParams.length; ++i) { if (this.methodCallHistoryWithParams[i].methodName === name) params.push(this.methodCallHistoryWithParams[i].params); } return params; } drawImage( surface: Surface, offsetX: number, offsetY: number, width: number, height: number, canvasOffsetX: number, canvasOffsetY: number ): void { this.methodCallHistoryWithParams.push({ methodName: "drawImage", params: { surface: surface, offsetX: offsetX, offsetY: offsetY, width: width, height: height, canvasOffsetX: canvasOffsetX, canvasOffsetY: canvasOffsetY } }); } translate(x: number, y: number): void { this.methodCallHistoryWithParams.push({ methodName: "translate", params: { x: x, y: y } }); } transform(matrix: number[]): void { this.methodCallHistoryWithParams.push({ methodName: "transform", params: { matrix: matrix } }); } opacity(opacity: number): void { this.methodCallHistoryWithParams.push({ methodName: "opacity", params: { opacity: opacity } }); } setCompositeOperation(operation: CompositeOperationString): void { this.methodCallHistoryWithParams.push({ methodName: "setCompositeOperation", params: { operation: operation } }); } fillRect(x: number, y: number, width: number, height: number, cssColor: string): void { this.methodCallHistoryWithParams.push({ methodName: "fillRect", params: { x: x, y: y, width: width, height: height, cssColor: cssColor } }); } save(): void { this.methodCallHistoryWithParams.push({ methodName: "save" }); } restore(): void { this.methodCallHistoryWithParams.push({ methodName: "restore" }); } drawSprites( surface: PdiSurface, offsetX: number[], offsetY: number[], width: number[], height: number[], canvasOffsetX: number[], canvasOffsetY: number[], count: number ): void { this.methodCallHistoryWithParams.push({ methodName: "drawSprites", params: { surface: surface, offsetX: offsetX, offsetY: offsetY, width: width, height: height, canvasOffsetX: canvasOffsetX, canvasOffsetY: canvasOffsetY, count: count } }); } setTransform(_matrix: number[]): void { throw new Error("not implemented"); } setOpacity(_opacity: number): void { throw new Error("not implemented"); } setShaderProgram(_shaderProgram: g.ShaderProgram): void { // do nothing } isSupportedShaderProgram(): boolean { return false; } _getImageData(): ImageData { throw new Error("not implemented"); } _putImageData(_imageData: ImageData): void { // do noting. } } export class Surface extends pci.Surface { createdRenderer: PdiRenderer | undefined; constructor(width: number, height: number, drawable?: any) { super(width, height, drawable); } renderer(): PdiRenderer { if (this.createdRenderer == null) { this.createdRenderer = new Renderer(); } return this.createdRenderer; } isPlaying(): boolean { // mock.Surfaceに与えるdrawableの再生状態はdrawable.isPlayingプロパティで与える return !!(this._drawable && this._drawable.isPlaying); } } class LoadFailureController { necessaryRetryCount: number; failureCount: number; constructor(necessaryRetryCount: number) { this.necessaryRetryCount = necessaryRetryCount; this.failureCount = 0; } tryLoad(asset: PdiAsset, loader: AssetLoadHandler): boolean { if (this.necessaryRetryCount < 0) { setTimeout(() => { if (!asset.destroyed()) loader._onAssetError(asset, g.ExceptionFactory.createAssetLoadError("FatalErrorForAssetLoad", false)); }, 0); return false; } if (this.failureCount++ < this.necessaryRetryCount) { setTimeout(() => { if (!asset.destroyed()) loader._onAssetError(asset, g.ExceptionFactory.createAssetLoadError("RetriableErrorForAssetLoad")); }, 0); return false; } return true; } } export class ImageAsset extends pci.ImageAsset { _failureController: LoadFailureController; _surface: Surface | undefined; constructor(necessaryRetryCount: number, id: string, assetPath: string, width: number, height: number) { super(id, assetPath, width, height); this._failureController = new LoadFailureController(necessaryRetryCount); } _load(loader: AssetLoadHandler): void { if (this._failureController.tryLoad(this, loader)) { setTimeout(() => { if (!this.destroyed()) loader._onAssetLoad(this); }, 0); } } asSurface(): PdiSurface { if (this._surface == null) { this._surface = new Surface(this.width, this.height); } return this._surface; } } export interface DelayedAsset { undelay(): void; } export class DelayedImageAsset extends ImageAsset implements DelayedAsset { _delaying: boolean; _lastGivenLoader: AssetLoadHandler; _isError: boolean; _loadingResult: any; constructor(necessaryRetryCount: number, id: string, assetPath: string, width: number, height: number) { super(necessaryRetryCount, id, assetPath, width, height); this._delaying = true; this._lastGivenLoader = undefined!; this._isError = false; this._loadingResult = undefined; } undelay(): void { this._delaying = false; this._flushDelayed(); } _load(loader: AssetLoadHandler): void { if (this._delaying) { // 遅延が要求されている状態で _load() が呼ばれた: loaderを自分に差し替えて _onAssetLoad, _onAssetError の通知を遅延する this._lastGivenLoader = loader; super._load(this); } else { // 遅延が解除された状態で _load() が呼ばれた: 普通のAsset同様に _load() を実行 super._load(loader); } } _onAssetError(_asset: PdiAsset, _error: AssetLoadError): void { this._isError = true; this._loadingResult = arguments; this._flushDelayed(); } _onAssetLoad(_asset: PdiAsset): void { this._isError = false; this._loadingResult = arguments; this._flushDelayed(); } _flushDelayed(): void { if (this._delaying || !this._loadingResult) return; if (this.destroyed()) return; const loader = this._lastGivenLoader; if (this._isError) { loader._onAssetError.apply(loader, this._loadingResult); } else { loader._onAssetLoad.apply(loader, this._loadingResult); } } } export class AudioAsset extends pci.AudioAsset { _failureController: LoadFailureController; constructor( necessaryRetryCount: number, id: string, assetPath: string, duration: number, system: PdiAudioSystem, loop: boolean, hint: AudioAssetHint ) { super(id, assetPath, duration, system, loop, hint); this._failureController = new LoadFailureController(necessaryRetryCount); } _load(loader: AssetLoadHandler): void { if (this._failureController.tryLoad(this, loader)) { setTimeout(() => { if (!this.destroyed()) loader._onAssetLoad(this); }, 0); } } } export class TextAsset extends pci.TextAsset { game: g.Game; _failureController: LoadFailureController; constructor(game: g.Game, necessaryRetryCount: number, id: string, assetPath: string) { super(id, assetPath); this.game = game; this._failureController = new LoadFailureController(necessaryRetryCount); } _load(loader: AssetLoadHandler): void { if (this._failureController.tryLoad(this, loader)) { setTimeout(() => { if ((this.game.resourceFactory as ResourceFactory).scriptContents.hasOwnProperty(this.path)) { this.data = (this.game.resourceFactory as ResourceFactory).scriptContents[this.path]; } else { this.data = ""; } if (!this.destroyed()) loader._onAssetLoad(this); }, 0); } } } export class ScriptAsset extends pci.ScriptAsset { game: g.Game; _failureController: LoadFailureController; constructor(game: g.Game, necessaryRetryCount: number, id: string, assetPath: string) { super(id, assetPath); this.game = game; this._failureController = new LoadFailureController(necessaryRetryCount); } _load(loader: AssetLoadHandler): void { if (this._failureController.tryLoad(this, loader)) { setTimeout(() => { if (!this.destroyed()) loader._onAssetLoad(this); }, 0); } } execute(env: ScriptAssetRuntimeValue): any { if (!(this.game.resourceFactory as ResourceFactory).scriptContents.hasOwnProperty(env.module.filename)) { // 特にスクリプトの内容指定がないケース: // ScriptAssetは任意の値を返してよいが、シーンを記述したスクリプトは // シーンを返す関数を返すことを期待するのでここでは関数を返しておく return (env.module.exports = function (): g.Scene { return new g.Scene({ game: env.game }); }); } else { const prefix = "(function(exports, require, module, __filename, __dirname) {"; const suffix = "})(g.module.exports, g.module.require, g.module, g.filename, g.dirname);"; const content = (this.game.resourceFactory as ResourceFactory).scriptContents[env.module.filename]; const f = new Function("g", prefix + content + suffix); f(env); return env.module.exports; } } } export class VideoAsset extends pci.VideoAsset { constructor(id: string, assetPath: string, width: number, height: number, system: g.VideoSystem, loop: boolean, useRealSize: boolean) { super(id, assetPath, width, height, system, loop, useRealSize); } _load(_loader: AssetLoadHandler): void { throw new Error("not implemented"); } asSurface(): Surface { throw new Error("not implemented"); } getPlayer(): PdiVideoPlayer { throw new Error("not implemented"); } } export class VectorImageAsset extends pci.VectorImageAsset { createSurface(_width: number, _height: number, _sx?: number, _sy?: number, _sWidth?: number, _sHeight?: number): Surface | null { return null; } _load(loader: AssetLoadHandler): void { loader._onAssetLoad(this); } } export class AudioPlayer extends pci.AudioPlayer { canHandleStoppedValue: boolean; constructor(system: PdiAudioSystem) { super(system); this.canHandleStoppedValue = true; } canHandleStopped(): boolean { return this.canHandleStoppedValue; } } export class GlyphFactory extends pci.GlyphFactory { constructor( fontFamily: string | string[], fontSize: number, baselineHeight?: number, fontColor?: string, strokeWidth?: number, strokeColor?: string, strokeOnly?: boolean, fontWeight?: FontWeightString ) { super(fontFamily, fontSize, baselineHeight, fontColor, strokeWidth, strokeColor, strokeOnly, fontWeight); } create(_code: number): PdiGlyph { throw new Error("not implemented"); } } export class ResourceFactory extends pci.ResourceFactory { _game: g.Game; scriptContents: { [key: string]: string }; // 真である限り createXXAsset() が DelayedAsset を生成する(現在は createImageAsset() のみ)。 // DelayedAsset は、flushDelayedAssets() 呼び出しまで読み込み完了(またはエラー)通知を遅延するアセットである。 // コード重複を避けるため、現在は createImageAsset() のみこのフラグに対応している。 createsDelayedAsset: boolean; _necessaryRetryCount: number; _delayedAssets: DelayedAsset[]; constructor() { super(); this.scriptContents = {}; this._game = undefined!; this.createsDelayedAsset = false; this._necessaryRetryCount = 0; this._delayedAssets = []; } init(game: g.Game): void { this._game = game; } // func が呼び出されている間だけ this._necessaryRetryCount を変更する。 // func() とその呼び出し先で生成されたアセットは、指定回数だけロードに失敗したのち成功する。 // -1を指定した場合、ロードは retriable が偽に設定された AssetLoadFatalError で失敗する。 withNecessaryRetryCount(necessaryRetryCount: number, func: () => void): void { const originalValue = this._necessaryRetryCount; try { this._necessaryRetryCount = necessaryRetryCount; func(); } finally { this._necessaryRetryCount = originalValue; } } // createsDelayedAsset が真である間に生成されたアセット(ただし現時点はImageAssetのみ) の、 // 遅延された読み込み完了通知を実行する。このメソッドの呼び出し後、実際の AssetLoader#_onAssetLoad() // などの呼び出しは setTimeout() 経由で行われることがある点に注意。 // (このメソッドの呼び出し側は、後続の処理を setTimeout() 経由で行う必要がある。mock.ts のアセット実装を参照のこと) flushDelayedAssets(): void { this._delayedAssets.forEach((a: DelayedAsset) => a.undelay()); this._delayedAssets = []; } createImageAsset(id: string, assetPath: string, width: number, height: number): ImageAsset { if (this.createsDelayedAsset) { const ret = new DelayedImageAsset(this._necessaryRetryCount, id, assetPath, width, height); this._delayedAssets.push(ret); return ret; } else { return new ImageAsset(this._necessaryRetryCount, id, assetPath, width, height); } } createVectorImageAsset(id: string, assetPath: string, width: number, height: number): VectorImageAsset { return new VectorImageAsset(id, assetPath, width, height); } createAudioAsset( id: string, assetPath: string, duration: number, system: PdiAudioSystem, loop: boolean, hint: AudioAssetHint ): AudioAsset { return new AudioAsset(this._necessaryRetryCount, id, assetPath, duration, system, loop, hint); } createTextAsset(id: string, assetPath: string): TextAsset { return new TextAsset(this._game, this._necessaryRetryCount, id, assetPath); } createScriptAsset(id: string, assetPath: string): ScriptAsset { return new ScriptAsset(this._game, this._necessaryRetryCount, id, assetPath); } createSurface(width: number, height: number): pci.Surface { return new Surface(width, height); } createAudioPlayer(system: PdiAudioSystem): AudioPlayer { return new AudioPlayer(system); } createGlyphFactory( fontFamily: string | string[], fontSize: number, baselineHeight?: number, fontColor?: string, strokeWidth?: number, strokeColor?: string, strokeOnly?: boolean, fontWeight?: FontWeightString ): PdiGlyphFactory { return new GlyphFactory(fontFamily, fontSize, baselineHeight, fontColor, strokeWidth, strokeColor, strokeOnly, fontWeight); } createVideoAsset( _id: string, _assetPath: string, _width: number, _height: number, _system: PdiVideoSystem, _loop: boolean, _useRealSize: boolean ): VideoAsset { throw new Error("not implemented"); } } export class GameHandlerSet implements g.GameHandlerSet { raisedEvents: pl.Event[] = []; raisedTicks: pl.Event[][] = []; eventFilters: g.EventFilter[] = []; modeHistry: g.SceneMode[] = []; raiseTick(events?: pl.Event[]): void { if (events) this.raisedTicks.push(events); } raiseEvent(event: pl.Event): void { this.raisedEvents.push(event); } addEventFilter(func: g.EventFilter, _handleEmpty?: boolean): void { this.eventFilters.push(func); } removeEventFilter(func: g.EventFilter): void { this.eventFilters = this.eventFilters.filter(f => f !== func); } removeAllEventFilters(): void { this.eventFilters = []; } changeSceneMode(mode: g.SceneMode): void { this.modeHistry.push(mode); } shouldSaveSnapshot(): boolean { return false; } saveSnapshot(_frame: number, _snapshot: any, _randGenSer: any, _timestamp?: number): void { // do nothing } getInstanceType(): "active" | "passive" { return "passive"; } getCurrentTime(): number { return 0; } } export class Game extends g.Game { terminatedGame: boolean; autoTickForInternalEvents: boolean; resourceFactory!: ResourceFactory; // NOTE: 継承元クラスで代入 handlerSet!: GameHandlerSet; // NOTE: 継承元クラスで代入 constructor( configuration: g.GameConfiguration, assetBase?: string, selfId?: string, operationPluginViewInfo?: OperationPluginViewInfo, mainFunc?: g.GameMainFunction ) { const resourceFactory = new ResourceFactory(); const handlerSet = new GameHandlerSet(); super({ engineModule: g, configuration, resourceFactory, handlerSet, assetBase, selfId, operationPluginViewInfo, mainFunc }); resourceFactory.init(this); this.terminatedGame = false; this.autoTickForInternalEvents = true; } // 引数がなかった当時の tick の挙動を再現するメソッド。 classicTick(): boolean { const scene = this.scene(); const advance = scene && scene.local !== "full-local"; return this.tick(!!advance); } _pushPostTickTask(fun: () => void, owner: any): void { super._pushPostTickTask(fun, owner); if (this.autoTickForInternalEvents) { setTimeout(() => { this.classicTick(); }, 0); } } _terminateGame(): void { this.terminatedGame = true; } } // g.Entitystateflags の定義はconst enumで書かれているので、javaScriptのテストコードからは直接参照できない。 // よって、g.Entitystateflagsのコードをコピーして利用する export enum EntityStateFlags { /** * 特にフラグが立っていない状態 */ None = 0, /** * 非表示フラグ */ Hidden = 1 << 0, /** * 描画結果がキャッシュ済みであることを示すフラグ */ Cached = 1 << 1, /** * modifiedされ、描画待ちであることを示すフラグ。 */ Modified = 1 << 2, /** * 軽量な描画処理を利用できることを示すフラグ。 */ ContextLess = 1 << 3 } export class CacheableE extends g.CacheableE { renderCache(_renderer: Renderer, _camera: g.Camera2D): void { // do nothing } } export interface AudioSystem extends PdiAudioSystem { _destroyRequestedAssets: { [key: string]: g.AudioAsset }; }
the_stack
const parseFile = require("@microsoft/bf-lu").parser.parseFile; import { IEntityObjectByPosition } from "./IEntityObjectByPosition"; import { IPartOfSpeechTagObjectByPosition } from "./IPartOfSpeechTagObjectByPosition"; import { ITextIntentSequenceLabelObjectByPosition} from "./ITextIntentSequenceLabelObjectByPosition"; import { Data } from "./Data"; import { DataWithSubwordFeaturizer } from "./DataWithSubwordFeaturizer"; import { NgramSubwordFeaturizer } from "../model/language_understanding/featurizer/NgramSubwordFeaturizer"; import { Utility } from "../utility/Utility"; export class LuDataWithSubwordFeaturizer extends DataWithSubwordFeaturizer { public static async createLuDataWithSubwordFeaturizerFromSamplingExistingLuDataUtterances( existingLuDataWithSubwordFeaturizer: LuDataWithSubwordFeaturizer, samplingIndexArray: number[], toResetFeaturizerLabelFeatureMaps: boolean): Promise<LuDataWithSubwordFeaturizer> { // ------------------------------------------------------------------- const luDataWithSubwordFeaturizer: LuDataWithSubwordFeaturizer = await LuDataWithSubwordFeaturizer.createLuDataWithSubwordFeaturizer( existingLuDataWithSubwordFeaturizer.getContent(), existingLuDataWithSubwordFeaturizer.getFeaturizer(), toResetFeaturizerLabelFeatureMaps); // ------------------------------------------------------------------- const luLuisJsonStructure: any = luDataWithSubwordFeaturizer.getLuLuisJsonStructure(); const utterancesArray: any[] = luDataWithSubwordFeaturizer.retrieveLuisLuUtterances(luLuisJsonStructure); const lengthUtterancesArray: number = utterancesArray.length; luLuisJsonStructure.utterances = []; for (const index of samplingIndexArray) { if ((index < 0) || (index > lengthUtterancesArray)) { Utility.debuggingThrow(`(index|${index}|<0)||(index|${index}|>lengthUtterancesArray|${lengthUtterancesArray}|)`); } luLuisJsonStructure.utterances.push(utterancesArray[index]); } // ------------------------------------------------------------------- luDataWithSubwordFeaturizer.luUtterances = luDataWithSubwordFeaturizer.retrieveLuUtterances(luLuisJsonStructure); // ------------------------------------------------------------------- luDataWithSubwordFeaturizer.intentInstanceIndexMapArray = luDataWithSubwordFeaturizer.collectIntents(luDataWithSubwordFeaturizer.luUtterances); luDataWithSubwordFeaturizer.entityTypeInstanceIndexMapArray = luDataWithSubwordFeaturizer.collectEntityTypes(luDataWithSubwordFeaturizer.luUtterances); luDataWithSubwordFeaturizer.intentsUtterancesWeights.intents = luDataWithSubwordFeaturizer.luUtterances.map( (entry: any) => entry.intent as string); luDataWithSubwordFeaturizer.intentsUtterancesWeights.utterances = luDataWithSubwordFeaturizer.luUtterances.map( (entry: any) => entry.text as string); luDataWithSubwordFeaturizer.intentsUtterancesWeights.weights = luDataWithSubwordFeaturizer.luUtterances.map( (entry: any) => entry.weight as number); // ------------------------------------------------------------------- if (toResetFeaturizerLabelFeatureMaps) { luDataWithSubwordFeaturizer.resetFeaturizerLabelFeatureMaps(); } // ------------------------------------------------------------------- luDataWithSubwordFeaturizer.featurizeIntentsUtterances(); // ------------------------------------------------------------------- return luDataWithSubwordFeaturizer; } public static async createLuDataWithSubwordFeaturizerFromFilteringExistingLuDataUtterances( existingLuDataWithSubwordFeaturizer: LuDataWithSubwordFeaturizer, filteringIndexSet: Set<number>, toResetFeaturizerLabelFeatureMaps: boolean): Promise<LuDataWithSubwordFeaturizer> { // ------------------------------------------------------------------- const luDataWithSubwordFeaturizer: LuDataWithSubwordFeaturizer = await LuDataWithSubwordFeaturizer.createLuDataWithSubwordFeaturizer( existingLuDataWithSubwordFeaturizer.getContent(), existingLuDataWithSubwordFeaturizer.getFeaturizer(), toResetFeaturizerLabelFeatureMaps); // ------------------------------------------------------------------- const luLuisJsonStructure: any = luDataWithSubwordFeaturizer.getLuLuisJsonStructure(); const utterancesArray: any[] = luDataWithSubwordFeaturizer.retrieveLuisLuUtterances(luLuisJsonStructure); const lengthUtterancesArray: number = utterancesArray.length; luLuisJsonStructure.utterances = []; for (const index of filteringIndexSet) { if ((index < 0) || (index > lengthUtterancesArray)) { Utility.debuggingThrow(`(index|${index}|<0)||(index|${index}|>lengthUtterancesArray|${lengthUtterancesArray}|)`); } luLuisJsonStructure.utterances.push(utterancesArray[index]); } // ------------------------------------------------------------------- luDataWithSubwordFeaturizer.luUtterances = luDataWithSubwordFeaturizer.retrieveLuUtterances(luLuisJsonStructure); // ------------------------------------------------------------------- luDataWithSubwordFeaturizer.intentInstanceIndexMapArray = luDataWithSubwordFeaturizer.collectIntents(luDataWithSubwordFeaturizer.luUtterances); luDataWithSubwordFeaturizer.entityTypeInstanceIndexMapArray = luDataWithSubwordFeaturizer.collectEntityTypes(luDataWithSubwordFeaturizer.luUtterances); luDataWithSubwordFeaturizer.intentsUtterancesWeights.intents = luDataWithSubwordFeaturizer.luUtterances.map( (entry: any) => entry.intent as string); luDataWithSubwordFeaturizer.intentsUtterancesWeights.utterances = luDataWithSubwordFeaturizer.luUtterances.map( (entry: any) => entry.text as string); luDataWithSubwordFeaturizer.intentsUtterancesWeights.weights = luDataWithSubwordFeaturizer.luUtterances.map( (entry: any) => entry.weight as number); // ------------------------------------------------------------------- if (toResetFeaturizerLabelFeatureMaps) { luDataWithSubwordFeaturizer.resetFeaturizerLabelFeatureMaps(); } // ------------------------------------------------------------------- luDataWithSubwordFeaturizer.featurizeIntentsUtterances(); // ------------------------------------------------------------------- return luDataWithSubwordFeaturizer; } public static async createLuDataWithSubwordFeaturizer( content: string, featurizer: NgramSubwordFeaturizer, toResetFeaturizerLabelFeatureMaps: boolean): Promise<LuDataWithSubwordFeaturizer> { // ------------------------------------------------------------------- const luDataWithSubwordFeaturizer: LuDataWithSubwordFeaturizer = new LuDataWithSubwordFeaturizer(featurizer); luDataWithSubwordFeaturizer.content = content; // ------------------------------------------------------------------- luDataWithSubwordFeaturizer.luObject = await parseFile(content); // ------------------------------------------------------------------- const luLuisJsonStructure: any = luDataWithSubwordFeaturizer.getLuLuisJsonStructure(); // ------------------------------------------------------------------- luDataWithSubwordFeaturizer.luUtterances = luDataWithSubwordFeaturizer.retrieveLuUtterances(luLuisJsonStructure); // ------------------------------------------------------------------- luDataWithSubwordFeaturizer.intentInstanceIndexMapArray = luDataWithSubwordFeaturizer.collectIntents(luDataWithSubwordFeaturizer.luUtterances); luDataWithSubwordFeaturizer.entityTypeInstanceIndexMapArray = luDataWithSubwordFeaturizer.collectEntityTypes(luDataWithSubwordFeaturizer.luUtterances); luDataWithSubwordFeaturizer.intentsUtterancesWeights.intents = luDataWithSubwordFeaturizer.luUtterances.map( (entry: any) => entry.intent as string); luDataWithSubwordFeaturizer.intentsUtterancesWeights.utterances = luDataWithSubwordFeaturizer.luUtterances.map( (entry: any) => entry.text as string); luDataWithSubwordFeaturizer.intentsUtterancesWeights.weights = luDataWithSubwordFeaturizer.luUtterances.map( (entry: any) => entry.weight as number); // ------------------------------------------------------------------- if (toResetFeaturizerLabelFeatureMaps) { luDataWithSubwordFeaturizer.resetFeaturizerLabelFeatureMaps(); } // ------------------------------------------------------------------- luDataWithSubwordFeaturizer.featurizeIntentsUtterances(); // ------------------------------------------------------------------- return luDataWithSubwordFeaturizer; } protected luObject: any = null; protected constructor( featurizer: NgramSubwordFeaturizer) { super(featurizer); } public async createDataFromSamplingExistingDataUtterances( existingDataWithSubwordFeaturizer: DataWithSubwordFeaturizer, labelColumnIndex: number, textColumnIndex: number, weightColumnIndex: number, linesToSkip: number, samplingIndexArray: number[], toResetFeaturizerLabelFeatureMaps: boolean): Promise<Data> { if (!(existingDataWithSubwordFeaturizer instanceof LuDataWithSubwordFeaturizer)) { Utility.debuggingThrow("logic error: the input DataWithSubwordFeaturizer object should be a LuDataWithSubwordFeaturizer object."); } return await LuDataWithSubwordFeaturizer.createLuDataWithSubwordFeaturizerFromSamplingExistingLuDataUtterances( existingDataWithSubwordFeaturizer as LuDataWithSubwordFeaturizer, samplingIndexArray, toResetFeaturizerLabelFeatureMaps); } public async createDataFromFilteringExistingDataUtterances( existingDataWithSubwordFeaturizer: DataWithSubwordFeaturizer, labelColumnIndex: number, textColumnIndex: number, weightColumnIndex: number, linesToSkip: number, filteringIndexSet: Set<number>, toResetFeaturizerLabelFeatureMaps: boolean): Promise<Data> { if (!(existingDataWithSubwordFeaturizer instanceof LuDataWithSubwordFeaturizer)) { Utility.debuggingThrow("logic error: the input DataWithSubwordFeaturizer object should be a LuDataWithSubwordFeaturizer object."); } return LuDataWithSubwordFeaturizer.createLuDataWithSubwordFeaturizerFromFilteringExistingLuDataUtterances( existingDataWithSubwordFeaturizer as LuDataWithSubwordFeaturizer, filteringIndexSet, toResetFeaturizerLabelFeatureMaps); } public retrieveLuisLuUtterances(luLuisJsonStructure: any): any[] { // ---- NOTE: a shallow copy return (luLuisJsonStructure.utterances as any[]); } public retrieveLuUtterances(luLuisJsonStructure: any): ITextIntentSequenceLabelObjectByPosition[] { const weight: number = 1; const utterancesArray: any[] = this.retrieveLuisLuUtterances(luLuisJsonStructure); const luUtterances: ITextIntentSequenceLabelObjectByPosition[] = []; utterancesArray.forEach( (entry: any) => { const entities: IEntityObjectByPosition[] = entry.entities; const partOfSpeechTags: IPartOfSpeechTagObjectByPosition[] = []; const intent: string = entry.intent; const text: string = entry.text; luUtterances.push({ entities, partOfSpeechTags, intent, text, weight, }); }); return luUtterances; } public getLuObject(): any { return this.luObject; } public getLuLuisJsonStructure(): any { return this.luObject.LUISJsonStructure; } public getLuQnaJsonStructure(): any { return this.luObject.qnaJsonStructure; } public getLuQnaAlterationsJsonStructure(): any { return this.luObject.qnaAlterations; } }
the_stack
import type { Placement } from "@floating-ui/dom"; import { autoUpdate, computePosition, flip, offset, shift } from "@floating-ui/dom"; import { Accessor, createContext, createSignal, createUniqueId, JSX, Show, useContext, } from "solid-js"; import { createStore } from "solid-js/store"; import { useStyleConfig } from "../../hope-provider"; import { SystemStyleObject } from "../../styled-system/types"; import { contains, getRelatedTarget, isScrollable, maintainScrollVisibility, } from "../../utils/dom"; import { isChildrenFunction } from "../../utils/solid"; import { getActionFromKey, getIndexByLetter, getUpdatedIndex, MenuActions, MenuItemData, } from "./menu.utils"; type MenuMotionPreset = | "scale-top-left" | "scale-top-right" | "scale-bottom-left" | "scale-bottom-right" | "none"; type MenuChildrenRenderProp = (props: { opened: Accessor<boolean> }) => JSX.Element; interface ThemeableMenuOptions { /** * If `true`, the menu will close when a menu item is selected. */ closeOnSelect?: boolean; /** * Offset between the menu content and the reference (trigger) element. */ offset?: number; /** * Placement of the menu content. */ placement?: Placement; /** * Menu content opening/closing transition. */ motionPreset?: MenuMotionPreset; } export interface MenuProps extends ThemeableMenuOptions { /** * The `id` of the menu. */ id?: string; /** * Children of the menu. */ children?: JSX.Element | MenuChildrenRenderProp; } interface MenuState { /** * If `true`, the menu will be open. */ opened: boolean; /** * If `true`, the menu will close when a menu item is clicked. */ closeOnSelect: boolean; /** * The id of the current `aria-activedescendent` element. */ activeDescendantId?: string; /** * The `id` of the `MenuTrigger`. */ triggerId: string; /** * The `id` of the `MenuContent`. */ menuContentId: string; /** * The prefix of the group labels (`MenuLabel`) `id`. */ labelIdPrefix: string; /** * The prefix of the menutiems (`MenuItem`) `id`. */ itemIdPrefix: string; /** * The list of available item. */ items: MenuItemData[]; /** * Menu opening/closing transition. */ motionPreset?: MenuMotionPreset; /** * Index of the active `MenuItem`. */ activeIndex: number; /** * If `true`, prevent the blur event when clicking a `MenuItem`. */ ignoreBlur: boolean; /** * The string to search for in the `MenuContent`. */ searchString: string; /** * The timeout id of the search functionnality. */ searchTimeoutId?: number; } /** * The wrapper component that provides context for all its children. */ export function Menu(props: MenuProps) { const defaultBaseId = `hope-menu-${createUniqueId()}`; const theme = useStyleConfig().Menu; const [_items, _setItems] = createSignal<Array<MenuItemData>>([]); const [state, setState] = createStore<MenuState>({ get triggerId() { return props.id ?? `${defaultBaseId}-trigger`; }, get menuContentId() { return `${defaultBaseId}-content`; }, get labelIdPrefix() { return `${defaultBaseId}-label`; }, get itemIdPrefix() { return `${defaultBaseId}-item`; }, get activeDescendantId() { return this.opened ? `${this.itemIdPrefix}-${this.activeIndex}` : undefined; }, get closeOnSelect() { return props.closeOnSelect ?? theme?.defaultProps?.root?.closeOnSelect ?? true; }, get motionPreset() { if (props.motionPreset) { return props.motionPreset; } if (theme?.defaultProps?.root?.motionPreset) { return theme?.defaultProps?.root?.motionPreset; } if (props.placement?.startsWith("top")) { return "scale-bottom-left"; } return "scale-top-left"; }, get items() { return _items(); }, opened: false, activeIndex: 0, ignoreBlur: false, searchString: "", searchTimeoutId: undefined, }); // element refs let triggerRef: HTMLButtonElement | undefined; let contentRef: HTMLDivElement | undefined; let cleanupContentAutoUpdate: (() => void) | undefined; const updateContentPosition = async () => { if (!triggerRef || !contentRef) { return; } const { x, y } = await computePosition(triggerRef, contentRef, { placement: props.placement ?? theme?.defaultProps?.root?.placement ?? "bottom-start", middleware: [offset(props.offset ?? theme?.defaultProps?.root?.offset ?? 5), flip(), shift()], }); if (!contentRef) { return; } Object.assign(contentRef.style, { left: `${Math.round(x)}px`, top: `${Math.round(y)}px`, }); }; const getSearchString = (char: string) => { // reset typing timeout and start new timeout // this allows us to make multiple-letter matches, like a native select if (state.searchTimeoutId) { window.clearTimeout(state.searchTimeoutId); } const searchTimeoutId = window.setTimeout(() => { setState("searchString", ""); }, 500); setState("searchTimeoutId", searchTimeoutId); // add most recent letter to saved search string setState("searchString", searchString => (searchString += char)); return state.searchString; }; const onItemChange = (index: number) => { setState("activeIndex", index); }; const isItemDisabledCallback = (index: number) => { return state.items[index].disabled; }; const selectItem = (index: number) => { onItemChange(index); const menuItem = state.items[index]; menuItem.onSelect?.(); if (menuItem.closeOnSelect) { updateOpeningState(false); } else { // if we don't close the menu on select, ensure to bring back focus to the `MenuTrigger` in order to keep keyboard navigation working. focusTrigger(); } }; const focusTrigger = () => { triggerRef?.focus(); }; const onTriggerBlur = (event: FocusEvent) => { // if the blur was provoked by an element inside the trigger, ignore it if (contains(triggerRef, getRelatedTarget(event))) { return; } // do not do blur action if ignoreBlur flag has been set if (state.ignoreBlur) { setState("ignoreBlur", false); return; } if (state.opened) { updateOpeningState(false, false); } }; const onTriggerClick = () => { updateOpeningState(!state.opened, false); }; const onTriggerKeyDown = (event: KeyboardEvent) => { const { key } = event; const max = state.items.length - 1; const action = getActionFromKey(event, state.opened); switch (action) { case MenuActions.Last: case MenuActions.First: case MenuActions.Next: case MenuActions.Previous: event.preventDefault(); return onItemChange( getUpdatedIndex({ currentIndex: state.activeIndex, maxIndex: max, initialAction: action, isItemDisabled: isItemDisabledCallback, }) ); case MenuActions.SelectAndClose: event.preventDefault(); selectItem(state.activeIndex); return; case MenuActions.Close: event.preventDefault(); return updateOpeningState(false); case MenuActions.Type: return onTriggerType(key); case MenuActions.Open: event.preventDefault(); return updateOpeningState(true); case MenuActions.OpenAndFocusLast: event.preventDefault(); return updateOpeningState(true, true, true); } }; const onTriggerType = (letter: string) => { // open the listbox if it is closed updateOpeningState(true); // find the index of the first matching option const searchString = getSearchString(letter); const searchIndex = getIndexByLetter( state.items as MenuItemData[], searchString, state.activeIndex + 1 ); // if a match was found, go to it if (searchIndex >= 0) { onItemChange(searchIndex); } // if no matches, clear the timeout and search string else { window.clearTimeout(state.searchTimeoutId); setState("searchString", ""); } }; const onItemClick = (index: number) => { // if item is disabled ensure to bring back focus to the `MenuTrigger` in order to keep keyboard navigation working. if (state.items[index].disabled) { focusTrigger(); return; } selectItem(index); }; const onItemMouseMove = (index: number) => { // if index is already the active one, do nothing if (state.activeIndex === index) { return; } onItemChange(index); }; const onItemMouseDown = () => { // Clicking an item will cause a blur event, // but we don't want to perform the default keyboard blur action setState("ignoreBlur", true); }; const scheduleContentPositionAutoUpdate = () => { if (state.opened) { updateContentPosition(); // schedule auto update of the content position. if (triggerRef && contentRef) { cleanupContentAutoUpdate = autoUpdate(triggerRef, contentRef, updateContentPosition); } } else { cleanupContentAutoUpdate?.(); } }; const updateOpeningState = (opened: boolean, callFocus = true, lastItemActive = false) => { if (state.opened === opened) { return; } setState("opened", opened); setState("activeIndex", lastItemActive ? state.items.length - 1 : 0); scheduleContentPositionAutoUpdate(); // move focus back to the button, if needed. callFocus && focusTrigger(); }; const onContentMouseLeave = () => { onItemChange(-1); }; const onContentClickOutside = (target: HTMLElement) => { // clicking inside the trigger is not considered an "outside click" if (contains(triggerRef, target)) { return; } updateOpeningState(false, false); }; const isItemActiveDescendant = (index: number) => { return index === state.activeIndex; }; const assignTriggerRef = (el: HTMLButtonElement) => { triggerRef = el; }; const assignContentRef = (el: HTMLDivElement) => { contentRef = el; }; const scrollToItem = (optionRef: HTMLDivElement) => { if (!contentRef) { return; } // ensure the new item is in view if (isScrollable(contentRef)) { maintainScrollVisibility(optionRef, contentRef); } }; const registerItem = (itemData: MenuItemData) => { const index = state.items.findIndex(item => item.key === itemData.key); // do not register the same item twice. if (index != -1) { return index; } // In Solid ^1.4.0 state.options is not up to date after setState call // setState("items", prev => [...prev, itemData]); // return state.items.length - 1; const updatedItems = _setItems(prev => [...prev, itemData]); return updatedItems.length - 1; }; const openedAccessor = () => state.opened; const context: MenuContextValue = { state: state as MenuState, isItemActiveDescendant, assignTriggerRef, assignContentRef, registerItem, scrollToItem, onTriggerBlur, onTriggerClick, onTriggerKeyDown, onContentMouseLeave, onContentClickOutside, onItemClick, onItemMouseMove, onItemMouseDown, }; return ( <MenuContext.Provider value={context}> <Show when={isChildrenFunction(props)} fallback={props.children as JSX.Element}> {(props.children as MenuChildrenRenderProp)?.({ opened: openedAccessor })} </Show> </MenuContext.Provider> ); } /* ------------------------------------------------------------------------------------------------- * Context * -----------------------------------------------------------------------------------------------*/ interface MenuContextValue { state: MenuState; /** * Check if the item is the current active-descendant by comparing its index with the active index. */ isItemActiveDescendant: (index: number) => boolean; /** * Callback to assign the `MenuTrigger` ref. */ assignTriggerRef: (el: HTMLButtonElement) => void; /** * Callback to assign the `MenuContent` ref. */ assignContentRef: (el: HTMLDivElement) => void; /** * Scroll to the active item. */ scrollToItem: (itemRef: HTMLDivElement) => void; /** * Callback to notify the context that a `MenuItem` is mounted. * @return The index of the item. */ registerItem: (itemData: MenuItemData) => number; /** * Callback invoked when the `MenuTrigger` loose focus. */ onTriggerBlur: (event: FocusEvent) => void; /** * Callback invoked when the user click on the `MenuTrigger`. */ onTriggerClick: (event: MouseEvent) => void; /** * Callback invoked when the user trigger the `MenuTrigger` with keyboard. */ onTriggerKeyDown: (event: KeyboardEvent) => void; /** * Callback invoked when the user click on a `MenuItem`. */ onItemClick: (index: number) => void; /** * Callback invoked when the user cursor move on a `MenuItem`. */ onItemMouseMove: (index: number) => void; /** * Callback invoked when the user click on a `MenuItem`. */ onItemMouseDown: () => void; /** * Callback invoked when the user click outside the `MenuContent`. */ onContentClickOutside: (target: HTMLElement) => void; /** * Callback invoked when the user cursor leave the `MenuContent`. */ onContentMouseLeave: () => void; } const MenuContext = createContext<MenuContextValue>(); export function useMenuContext() { const context = useContext(MenuContext); if (!context) { throw new Error("[Hope UI]: useMenuContext must be used within a `<Menu />` component"); } return context; } /* ------------------------------------------------------------------------------------------------- * StyleConfig * -----------------------------------------------------------------------------------------------*/ export interface MenuStyleConfig { baseStyle?: { trigger?: SystemStyleObject; content?: SystemStyleObject; group?: SystemStyleObject; label?: SystemStyleObject; item?: SystemStyleObject; itemText?: SystemStyleObject; itemIconWrapper?: SystemStyleObject; itemCommand?: SystemStyleObject; }; defaultProps?: { root?: ThemeableMenuOptions; }; }
the_stack
import { Nes } from "./nes"; declare var navigator,$; export class GamePadState{ buttonDown:boolean = false; buttonNum:number = -1; buttonTimer = 0; keyName:string = ''; constructor(buttonNum:number,keyName:string) { this.buttonNum = buttonNum; this.keyName = keyName; } } export class KeyMappings{ Mapping_Left:string = null; Mapping_Right:string = null; Mapping_Up:string = null; Mapping_Down:string = null; Mapping_Action_Start:string = null; Mapping_Action_Select:string = null; Mapping_Action_B:string = null; Mapping_Action_A:string = null; Joy_Mapping_Left:number = null; Joy_Mapping_Right:number = null; Joy_Mapping_Up:number = null; Joy_Mapping_Down:number = null; Joy_Mapping_Action_Start:number = null; Joy_Mapping_Action_Select:number = null; Joy_Mapping_Action_B:number = null; Joy_Mapping_Action_A:number = null; } export class InputController{ gamepadButtons:GamePadState[] = []; //for remapping Key_Last:string=''; Joy_Last:number=null; Remap_Check = false; Key_Up=false; Key_Down=false; Key_Left=false; Key_Right=false; Key_Action_Start=false; Key_Action_Select=false; Key_Action_B=false; Key_Action_A=false; Gamepad_Process_Axis=false; Touch_Tap=false; KeyMappings:KeyMappings; DebugKeycodes=false; Code_Right = 2000; Code_Left = 2001; Code_Down = 2002; Code_Up = 2003; Code_A = 2006; Code_B = 2007; Code_Start = 2009; Code_Select = 2008; MobileA=false; MobileA_Counter=0; MobileB=false; MobileB_Counter=0; MobileStart=false; MobileStart_Counter=0; MobileSelect=false; MobileSelect_Counter=0; TurboButtons = false; //touch private touchX_Start:number = 0; private touchY_Start:number = 0; private touch_tap_counter = 0; constructor(touch_element_id?:string,touch_exclude_id?:string){ window["inputController"] = this; //need this for full screen touch support if (touch_element_id) { //you have to do this if there are any html buttons that need to be pressed if (touch_exclude_id){ document.getElementById(touch_exclude_id).addEventListener( 'touchstart', function(e){e.stopPropagation();}, false ); document.getElementById(touch_exclude_id).addEventListener( 'touchend', function(e){ e.stopPropagation();}, false ); } document.getElementById(touch_element_id).addEventListener( 'touchstart', this.touchStart, false ); document.getElementById(touch_element_id).addEventListener( 'touchend', this.touchEnd, false ); document.getElementById(touch_element_id).addEventListener( 'touchmove', this.touchMove, false ); // document.getElementById('divEmuOuter').addEventListener( 'onkeydown', this.keyDown, false ); // document.getElementById('divEmuOuter').addEventListener( 'onkeyup', this.keyUp, false ); document.onkeydown = this.keyDown; document.onkeyup = this.keyUp; document.getElementById('mobileA').addEventListener( 'touchstart', this.mobilePressA.bind(this), false ); document.getElementById('mobileB').addEventListener( 'touchstart', this.mobilePressB.bind(this), false ); document.getElementById('mobileStart').addEventListener( 'touchstart', this.mobilePressStart.bind(this), false ); document.getElementById('mobileSelect').addEventListener( 'touchstart', this.mobilePressSelect.bind(this), false ); document.getElementById('mobileA').addEventListener( 'touchend', this.mobileReleaseA.bind(this), false ); document.getElementById('mobileB').addEventListener( 'touchend', this.mobileReleaseB.bind(this), false ); document.getElementById('mobileStart').addEventListener( 'touchend', this.mobileReleaseStart.bind(this), false ); document.getElementById('mobileSelect').addEventListener( 'touchend', this.mobileReleaseSelect.bind(this), false ); document.getElementById('mobileA').addEventListener( 'touchmove', function(e){e.preventDefault();}, false ); document.getElementById('mobileB').addEventListener( 'touchmove', function(e){e.preventDefault();}, false ); document.getElementById('mobileStart').addEventListener( 'touchmove', function(e){e.preventDefault();}, false ); document.getElementById('mobileSelect').addEventListener( 'touchmove', function(e){e.preventDefault();}, false ); //to hide and show loading panel document.getElementById('menuDiv').addEventListener( 'touchstart', this.canvasTouch.bind(this), false ); } this.KeyMappings = { Mapping_Left:'Left', Mapping_Right:'Right', Mapping_Up:'Up', Mapping_Down:'Down', Mapping_Action_A:'s', Mapping_Action_B:'a', Mapping_Action_Start:'Enter', Mapping_Action_Select:'/', Joy_Mapping_Left:14, Joy_Mapping_Right:15, Joy_Mapping_Down:13, Joy_Mapping_Up:12, Joy_Mapping_Action_A:0, Joy_Mapping_Action_B:2, Joy_Mapping_Action_Start:9, Joy_Mapping_Action_Select:8 } } canvasTouch(event:TouchEvent){ if (event.touches[0].clientY<50) $("#mainContainer").show(); $('#menuDiv').hide(); } mobilePressA(event){ event.preventDefault(); this.Key_Action_A = true; this.MobileA = true; } mobilePressB(event){ event.preventDefault(); this.Key_Action_B = true; this.MobileB = true; } mobilePressStart(event){ event.preventDefault(); this.Key_Action_Start = true; this.MobileStart = true; } mobilePressSelect(event){ event.preventDefault(); this.Key_Action_Select = true; this.MobileSelect = true; } mobileReleaseA(event){ event.preventDefault(); if (this.TurboButtons==false && this.MobileA_Counter<=15) { //don't do sticky buttons } else { this.MobileA = false; this.Key_Action_A = false; this.MobileA_Counter=0; } } mobileReleaseB(event){ event.preventDefault(); if (this.TurboButtons==false && this.MobileB_Counter<=15) { //don't do sticky buttons } else { this.MobileB = false; this.Key_Action_B = false; this.MobileB_Counter=0; } } mobileReleaseStart(event){ event.preventDefault(); this.MobileStart = false; this.Key_Action_Start = false; this.MobileStart_Counter=0; } mobileReleaseSelect(event){ event.preventDefault(); this.MobileSelect = false; this.Key_Action_Select = false; this.MobileSelect_Counter=0; } setupGamePad(){ window.addEventListener("gamepadconnected", this.initGamePad.bind(this)); this.setGamePadButtons(); } setGamePadButtons(){ this.gamepadButtons = []; this.gamepadButtons.push(new GamePadState(this.KeyMappings.Joy_Mapping_Left,this.KeyMappings.Mapping_Left)); this.gamepadButtons.push(new GamePadState(this.KeyMappings.Joy_Mapping_Right,this.KeyMappings.Mapping_Right)); this.gamepadButtons.push(new GamePadState(this.KeyMappings.Joy_Mapping_Down,this.KeyMappings.Mapping_Down)); this.gamepadButtons.push(new GamePadState(this.KeyMappings.Joy_Mapping_Up,this.KeyMappings.Mapping_Up)); this.gamepadButtons.push(new GamePadState(this.KeyMappings.Joy_Mapping_Action_Start,this.KeyMappings.Mapping_Action_Start)); this.gamepadButtons.push(new GamePadState(this.KeyMappings.Joy_Mapping_Action_B,this.KeyMappings.Mapping_Action_B)); this.gamepadButtons.push(new GamePadState(this.KeyMappings.Joy_Mapping_Action_Select,this.KeyMappings.Mapping_Action_Select)); this.gamepadButtons.push(new GamePadState(this.KeyMappings.Joy_Mapping_Action_A,this.KeyMappings.Mapping_Action_A)); } private initGamePad(e) { try{ if (e.gamepad.buttons.length>0) { // this.message = '<b>Gamepad Detected:</b><br>' + e.gamepad.id; } }catch{} console.log("Gamepad connected at index %d: %s. %d buttons, %d axes.", e.gamepad.index, e.gamepad.id, e.gamepad.buttons.length, e.gamepad.axes.length); } processGamepad(){ try{ var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads : []); if (!gamepads) return; var gp = null; for (let i=0;i<gamepads.length;i++) { if (gamepads[i] && gamepads[i].buttons.length>0) gp = gamepads[i]; } if (gp) { for(let i=0;i<gp.buttons.length;i++) { if (this.DebugKeycodes) { if (gp.buttons[i].pressed) console.log(i); } if (gp.buttons[i].pressed) this.Joy_Last = i; } this.gamepadButtons.forEach(button => { if (gp.buttons[button.buttonNum].pressed) { if (button.buttonTimer==0) { this.sendKeyDownEvent(button.keyName); } button.buttonDown = true; button.buttonTimer++; } else if (button.buttonDown) { if (!gp.buttons[button.buttonNum].pressed) { button.buttonDown = false; button.buttonTimer = 0; this.sendKeyUpEvent(button.keyName); } } }); //process axes if (this.Gamepad_Process_Axis) { try { let horiz_axis = gp.axes[0] as number; let vertical_axis = gp.axes[1] as number; if (horiz_axis<-.5) { if (!this.Key_Left) { this.sendKeyDownEvent(this.KeyMappings.Mapping_Left); } } else { if (this.Key_Left) { this.sendKeyUpEvent(this.KeyMappings.Mapping_Left); } } if (horiz_axis>.5) { if (!this.Key_Right) { this.sendKeyDownEvent(this.KeyMappings.Mapping_Right); } } else { if (this.Key_Right) { this.sendKeyUpEvent(this.KeyMappings.Mapping_Right); } } if (vertical_axis>.5) { if (!this.Key_Down) { this.sendKeyDownEvent(this.KeyMappings.Mapping_Down); } } else { if (this.Key_Down) { this.sendKeyUpEvent(this.KeyMappings.Mapping_Down); } } if (vertical_axis<-.5) { if (!this.Key_Up) { this.sendKeyDownEvent(this.KeyMappings.Mapping_Up); } } else { if (this.Key_Up) { this.sendKeyUpEvent(this.KeyMappings.Mapping_Up); } } }catch(error){} } } }catch{} } sendKeyDownEvent(key:string) { let keyEvent = new KeyboardEvent('Gamepad Event Down',{key:key}); this.keyDown(keyEvent); } sendKeyUpEvent(key:string) { let keyEvent = new KeyboardEvent('Gamepad Event Up',{key:key}); this.keyUp(keyEvent); } keyDown(event:KeyboardEvent) { try { //fix for monaco editor generating inputs for emulator if ((event.target as any).type == 'textarea') return; }catch(error){} // if (event.target.localName=='textarea') let input_controller = window["inputController"] as InputController; input_controller.Key_Last = event.key; if (input_controller.DebugKeycodes) console.log(event); //handle both Chrome and Edge version of arrow keys if (event.key=='ArrowLeft') event = new KeyboardEvent('',{key:'Left'}); if (event.key=='ArrowRight') event = new KeyboardEvent('',{key:'Right'}); if (event.key=='ArrowUp') event = new KeyboardEvent('',{key:'Up'}); if (event.key=='ArrowDown') event = new KeyboardEvent('',{key:'Down'}); if (event.key==input_controller.KeyMappings.Mapping_Down) { input_controller.Key_Down = true; } if (event.key==input_controller.KeyMappings.Mapping_Up) { input_controller.Key_Up = true; } if (event.key==input_controller.KeyMappings.Mapping_Left) { input_controller.Key_Left = true; } if (event.key==input_controller.KeyMappings.Mapping_Right) { input_controller.Key_Right = true; } if (event.key==input_controller.KeyMappings.Mapping_Action_Start) { input_controller.Key_Action_Start = true; } if (event.key==input_controller.KeyMappings.Mapping_Action_B) { input_controller.Key_Action_B = true; } if (event.key==input_controller.KeyMappings.Mapping_Action_Select) { input_controller.Key_Action_Select= true; } if (event.key==input_controller.KeyMappings.Mapping_Action_A) { input_controller.Key_Action_A = true; } } keyUp(event:KeyboardEvent) { if (event.key=='ArrowLeft') event = new KeyboardEvent('',{key:'Left'}); if (event.key=='ArrowRight') event = new KeyboardEvent('',{key:'Right'}); if (event.key=='ArrowUp') event = new KeyboardEvent('',{key:'Up'}); if (event.key=='ArrowDown') event = new KeyboardEvent('',{key:'Down'}); let input_controller = window["inputController"] as InputController; if (event.key==input_controller.KeyMappings.Mapping_Down) { input_controller.Key_Down = false; } if (event.key==input_controller.KeyMappings.Mapping_Up) { input_controller.Key_Up = false; } if (event.key==input_controller.KeyMappings.Mapping_Left) { input_controller.Key_Left = false; } if (event.key==input_controller.KeyMappings.Mapping_Right) { input_controller.Key_Right = false; } if (event.key==input_controller.KeyMappings.Mapping_Action_Start) { input_controller.Key_Action_Start = false; } if (event.key==input_controller.KeyMappings.Mapping_Action_B) { input_controller.Key_Action_B = false; } if (event.key==input_controller.KeyMappings.Mapping_Action_Select) { input_controller.Key_Action_Select = false; } if (event.key==input_controller.KeyMappings.Mapping_Action_A) { input_controller.Key_Action_A = false; } } touchStart(event:TouchEvent){ event.preventDefault(); let input_controller = window["inputController"] as InputController; //prevent multi-touch from grabbing the wrong touch event //there may be more than 2 touches so just loop until it's found for(let i = 0;i<event.touches.length;i++) { let touch = event.touches[i]; if (touch.target["id"]=="divTouchSurface" || touch.target["id"]=="startDiv") { input_controller.touchX_Start = touch.clientX; input_controller.touchY_Start = touch.clientY; } } } touchMove(event:TouchEvent){ event.preventDefault(); let input_controller = window["inputController"] as InputController; //prevent multi-touch from grabbing the wrong touch event for(let i = 0;i<event.touches.length;i++) { let touch = event.touches[i]; if (touch.target["id"]=="divTouchSurface" || touch.target["id"]=="startDiv") { var amount_horizontal = touch.clientX-input_controller.touchX_Start; var amount_vertical = touch.clientY-input_controller.touchY_Start; if (amount_horizontal>10) { if (!input_controller.Key_Right) { input_controller.sendKeyDownEvent(input_controller.KeyMappings.Mapping_Right); input_controller.Key_Right=true; } } if (amount_horizontal<-10) { if (!input_controller.Key_Left) { input_controller.sendKeyDownEvent(input_controller.KeyMappings.Mapping_Left); input_controller.Key_Left=true; } } if (amount_vertical>10) { //mario hack let nes = window["myApp"].nes as Nes; let isMario = false; let marioDontKeyDown = false; if (nes.rom_name=="smb.nes") isMario = true; if (isMario && (input_controller.Key_Left || input_controller.Key_Right)) marioDontKeyDown = true; if (!input_controller.Key_Down && marioDontKeyDown==false) { input_controller.sendKeyDownEvent(input_controller.KeyMappings.Mapping_Down); input_controller.Key_Down=true; } } if (amount_vertical<-10) { if (!input_controller.Key_Up) { input_controller.sendKeyDownEvent(input_controller.KeyMappings.Mapping_Up); input_controller.Key_Up=true; } } } } } touchEnd(event:TouchEvent){ event.preventDefault(); event.stopPropagation(); let input_controller = window["inputController"] as InputController; if (input_controller.Key_Left==false && input_controller.Key_Right==false && input_controller.Key_Down==false && input_controller.Key_Up==false) input_controller.Touch_Tap=true; if (input_controller.Key_Right) { input_controller.sendKeyUpEvent(input_controller.KeyMappings.Mapping_Right); input_controller.Key_Right=false; } if (input_controller.Key_Left) { input_controller.sendKeyUpEvent(input_controller.KeyMappings.Mapping_Left); input_controller.Key_Left=false; } if (input_controller.Key_Up) { input_controller.sendKeyUpEvent(input_controller.KeyMappings.Mapping_Up); input_controller.Key_Up=false; } if (input_controller.Key_Down) { input_controller.sendKeyUpEvent(input_controller.KeyMappings.Mapping_Down); input_controller.Key_Down=false; } } update(){ this.processGamepad(); if (this.Touch_Tap){ this.touch_tap_counter++; } if (this.touch_tap_counter>1) { this.Touch_Tap = false; this.touch_tap_counter = 0; } //used for double tap detection this.MobileA_Counter++; this.MobileB_Counter++; this.MobileStart_Counter++; this.MobileSelect_Counter++; //a hack - need to refactor if (this.Remap_Check){ if (this.Key_Last!='' || this.Joy_Last) { window["myApp"].remapPressed(); this.Remap_Check = false; } } } //input check loop loop(){ this.update(); window.requestAnimationFrame(this.loop.bind(this)); } }
the_stack
import { blockchainTests, constants, describe, expect, getRandomPortion, randomAddress, } from '@0x/contracts-test-utils'; import { BigNumber, hexUtils } from '@0x/utils'; import { LogWithDecodedArgs } from 'ethereum-types'; import { artifacts } from '../artifacts'; import { TestMintableERC20TokenContract, TestNoEthRecipientContract, TestUniswapV3FactoryContract, TestUniswapV3FactoryPoolCreatedEventArgs, TestUniswapV3PoolContract, TestWethContract, UniswapV3FeatureContract, } from '../wrappers'; blockchainTests.resets('UniswapV3Feature', env => { const { MAX_UINT256, NULL_ADDRESS, ZERO_AMOUNT } = constants; const POOL_FEE = 1234; const MAX_SUPPLY = new BigNumber('10e18'); let uniFactory: TestUniswapV3FactoryContract; let feature: UniswapV3FeatureContract; let weth: TestWethContract; let tokens: TestMintableERC20TokenContract[]; const sellAmount = getRandomPortion(MAX_SUPPLY); const buyAmount = getRandomPortion(MAX_SUPPLY); let taker: string; const recipient = randomAddress(); let noEthRecipient: TestNoEthRecipientContract; before(async () => { [, taker] = await env.getAccountAddressesAsync(); weth = await TestWethContract.deployFrom0xArtifactAsync( artifacts.TestWeth, env.provider, env.txDefaults, artifacts, ); tokens = await Promise.all( [...new Array(3)].map(async () => TestMintableERC20TokenContract.deployFrom0xArtifactAsync( artifacts.TestMintableERC20Token, env.provider, env.txDefaults, artifacts, ), ), ); noEthRecipient = await TestNoEthRecipientContract.deployFrom0xArtifactAsync( artifacts.TestNoEthRecipient, env.provider, env.txDefaults, artifacts, ); uniFactory = await TestUniswapV3FactoryContract.deployFrom0xArtifactAsync( artifacts.TestUniswapV3Factory, env.provider, env.txDefaults, artifacts, ); feature = await UniswapV3FeatureContract.deployFrom0xArtifactAsync( artifacts.TestUniswapV3Feature, env.provider, env.txDefaults, artifacts, weth.address, uniFactory.address, await uniFactory.POOL_INIT_CODE_HASH().callAsync(), ); await Promise.all( [...tokens, weth].map(t => t.approve(feature.address, MAX_UINT256).awaitTransactionSuccessAsync({ from: taker }), ), ); }); function isWethContract(t: TestMintableERC20TokenContract | TestWethContract): t is TestWethContract { return !!(t as any).deposit; } async function mintToAsync( token: TestMintableERC20TokenContract | TestWethContract, owner: string, amount: BigNumber, ): Promise<void> { if (isWethContract(token)) { await token.depositTo(owner).awaitTransactionSuccessAsync({ value: amount }); } else { await token.mint(owner, amount).awaitTransactionSuccessAsync(); } } async function createPoolAsync( token0: TestMintableERC20TokenContract | TestWethContract, token1: TestMintableERC20TokenContract | TestWethContract, balance0: BigNumber, balance1: BigNumber, ): Promise<TestUniswapV3PoolContract> { const r = await uniFactory .createPool(token0.address, token1.address, new BigNumber(POOL_FEE)) .awaitTransactionSuccessAsync(); const pool = new TestUniswapV3PoolContract( (r.logs[0] as LogWithDecodedArgs<TestUniswapV3FactoryPoolCreatedEventArgs>).args.pool, env.provider, env.txDefaults, ); await mintToAsync(token0, pool.address, balance0); await mintToAsync(token1, pool.address, balance1); return pool; } function encodePath(tokens_: Array<TestMintableERC20TokenContract | TestWethContract>): string { const elems: string[] = []; tokens_.forEach((t, i) => { if (i) { elems.push(hexUtils.leftPad(POOL_FEE, 3)); } elems.push(hexUtils.leftPad(t.address, 20)); }); return hexUtils.concat(...elems); } describe('sellTokenForTokenToUniswapV3()', () => { it('1-hop swap', async () => { const [sellToken, buyToken] = tokens; const pool = await createPoolAsync(sellToken, buyToken, ZERO_AMOUNT, buyAmount); await mintToAsync(sellToken, taker, sellAmount); await feature .sellTokenForTokenToUniswapV3(encodePath([sellToken, buyToken]), sellAmount, buyAmount, recipient) .awaitTransactionSuccessAsync({ from: taker }); // Test pools always ask for full sell amount and pay entire balance. expect(await sellToken.balanceOf(taker).callAsync()).to.bignumber.eq(0); expect(await buyToken.balanceOf(recipient).callAsync()).to.bignumber.eq(buyAmount); expect(await sellToken.balanceOf(pool.address).callAsync()).to.bignumber.eq(sellAmount); }); it('2-hop swap', async () => { const pools = [ await createPoolAsync(tokens[0], tokens[1], ZERO_AMOUNT, buyAmount), await createPoolAsync(tokens[1], tokens[2], ZERO_AMOUNT, buyAmount), ]; await mintToAsync(tokens[0], taker, sellAmount); await feature .sellTokenForTokenToUniswapV3(encodePath(tokens), sellAmount, buyAmount, recipient) .awaitTransactionSuccessAsync({ from: taker }); // Test pools always ask for full sell amount and pay entire balance. expect(await tokens[0].balanceOf(taker).callAsync()).to.bignumber.eq(0); expect(await tokens[2].balanceOf(recipient).callAsync()).to.bignumber.eq(buyAmount); expect(await tokens[0].balanceOf(pools[0].address).callAsync()).to.bignumber.eq(sellAmount); expect(await tokens[1].balanceOf(pools[1].address).callAsync()).to.bignumber.eq(buyAmount); }); it('1-hop underbuy fails', async () => { const [sellToken, buyToken] = tokens; await createPoolAsync(sellToken, buyToken, ZERO_AMOUNT, buyAmount.minus(1)); await mintToAsync(sellToken, taker, sellAmount); const tx = feature .sellTokenForTokenToUniswapV3(encodePath([sellToken, buyToken]), sellAmount, buyAmount, recipient) .awaitTransactionSuccessAsync({ from: taker }); return expect(tx).to.revertWith('UniswapV3Feature/UNDERBOUGHT'); }); it('2-hop underbuy fails', async () => { await createPoolAsync(tokens[0], tokens[1], ZERO_AMOUNT, buyAmount); await createPoolAsync(tokens[1], tokens[2], ZERO_AMOUNT, buyAmount.minus(1)); await mintToAsync(tokens[0], taker, sellAmount); const tx = feature .sellTokenForTokenToUniswapV3(encodePath(tokens), sellAmount, buyAmount, recipient) .awaitTransactionSuccessAsync({ from: taker }); return expect(tx).to.revertWith('UniswapV3Feature/UNDERBOUGHT'); }); it('null recipient is sender', async () => { const [sellToken, buyToken] = tokens; await createPoolAsync(sellToken, buyToken, ZERO_AMOUNT, buyAmount); await mintToAsync(sellToken, taker, sellAmount); await feature .sellTokenForTokenToUniswapV3(encodePath([sellToken, buyToken]), sellAmount, buyAmount, NULL_ADDRESS) .awaitTransactionSuccessAsync({ from: taker }); // Test pools always ask for full sell amount and pay entire balance. expect(await buyToken.balanceOf(taker).callAsync()).to.bignumber.eq(buyAmount); }); }); describe('sellEthForTokenToUniswapV3()', () => { it('1-hop swap', async () => { const [buyToken] = tokens; const pool = await createPoolAsync(weth, buyToken, ZERO_AMOUNT, buyAmount); await feature .sellEthForTokenToUniswapV3(encodePath([weth, buyToken]), buyAmount, recipient) .awaitTransactionSuccessAsync({ from: taker, value: sellAmount }); // Test pools always ask for full sell amount and pay entire balance. expect(await buyToken.balanceOf(recipient).callAsync()).to.bignumber.eq(buyAmount); expect(await weth.balanceOf(pool.address).callAsync()).to.bignumber.eq(sellAmount); }); it('null recipient is sender', async () => { const [buyToken] = tokens; const pool = await createPoolAsync(weth, buyToken, ZERO_AMOUNT, buyAmount); await feature .sellEthForTokenToUniswapV3(encodePath([weth, buyToken]), buyAmount, NULL_ADDRESS) .awaitTransactionSuccessAsync({ from: taker, value: sellAmount }); // Test pools always ask for full sell amount and pay entire balance. expect(await buyToken.balanceOf(taker).callAsync()).to.bignumber.eq(buyAmount); expect(await weth.balanceOf(pool.address).callAsync()).to.bignumber.eq(sellAmount); }); }); describe('sellTokenForEthToUniswapV3()', () => { it('1-hop swap', async () => { const [sellToken] = tokens; const pool = await createPoolAsync(sellToken, weth, ZERO_AMOUNT, buyAmount); await mintToAsync(sellToken, taker, sellAmount); await feature .sellTokenForEthToUniswapV3(encodePath([sellToken, weth]), sellAmount, buyAmount, recipient) .awaitTransactionSuccessAsync({ from: taker }); // Test pools always ask for full sell amount and pay entire balance. expect(await sellToken.balanceOf(taker).callAsync()).to.bignumber.eq(0); expect(await env.web3Wrapper.getBalanceInWeiAsync(recipient)).to.bignumber.eq(buyAmount); expect(await sellToken.balanceOf(pool.address).callAsync()).to.bignumber.eq(sellAmount); }); it('null recipient is sender', async () => { const [sellToken] = tokens; const pool = await createPoolAsync(sellToken, weth, ZERO_AMOUNT, buyAmount); await mintToAsync(sellToken, taker, sellAmount); const takerBalanceBefore = await env.web3Wrapper.getBalanceInWeiAsync(taker); await feature .sellTokenForEthToUniswapV3(encodePath([sellToken, weth]), sellAmount, buyAmount, NULL_ADDRESS) .awaitTransactionSuccessAsync({ from: taker, gasPrice: ZERO_AMOUNT }); // Test pools always ask for full sell amount and pay entire balance. expect((await env.web3Wrapper.getBalanceInWeiAsync(taker)).minus(takerBalanceBefore)).to.bignumber.eq( buyAmount, ); expect(await sellToken.balanceOf(pool.address).callAsync()).to.bignumber.eq(sellAmount); }); it('fails if receipient cannot receive ETH', async () => { const [sellToken] = tokens; await mintToAsync(sellToken, taker, sellAmount); const tx = feature .sellTokenForEthToUniswapV3( encodePath([sellToken, weth]), sellAmount, buyAmount, noEthRecipient.address, ) .awaitTransactionSuccessAsync({ from: taker }); return expect(tx).to.be.rejectedWith('revert'); }); }); });
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { Policies } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { DevTestLabsClient } from "../devTestLabsClient"; import { Policy, PoliciesListNextOptionalParams, PoliciesListOptionalParams, PoliciesListResponse, PoliciesGetOptionalParams, PoliciesGetResponse, PoliciesCreateOrUpdateOptionalParams, PoliciesCreateOrUpdateResponse, PoliciesDeleteOptionalParams, PolicyFragment, PoliciesUpdateOptionalParams, PoliciesUpdateResponse, PoliciesListNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing Policies operations. */ export class PoliciesImpl implements Policies { private readonly client: DevTestLabsClient; /** * Initialize a new instance of the class Policies class. * @param client Reference to the service client */ constructor(client: DevTestLabsClient) { this.client = client; } /** * List policies in a given policy set. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param policySetName The name of the policy set. * @param options The options parameters. */ public list( resourceGroupName: string, labName: string, policySetName: string, options?: PoliciesListOptionalParams ): PagedAsyncIterableIterator<Policy> { const iter = this.listPagingAll( resourceGroupName, labName, policySetName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage( resourceGroupName, labName, policySetName, options ); } }; } private async *listPagingPage( resourceGroupName: string, labName: string, policySetName: string, options?: PoliciesListOptionalParams ): AsyncIterableIterator<Policy[]> { let result = await this._list( resourceGroupName, labName, policySetName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext( resourceGroupName, labName, policySetName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( resourceGroupName: string, labName: string, policySetName: string, options?: PoliciesListOptionalParams ): AsyncIterableIterator<Policy> { for await (const page of this.listPagingPage( resourceGroupName, labName, policySetName, options )) { yield* page; } } /** * List policies in a given policy set. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param policySetName The name of the policy set. * @param options The options parameters. */ private _list( resourceGroupName: string, labName: string, policySetName: string, options?: PoliciesListOptionalParams ): Promise<PoliciesListResponse> { return this.client.sendOperationRequest( { resourceGroupName, labName, policySetName, options }, listOperationSpec ); } /** * Get policy. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param policySetName The name of the policy set. * @param name The name of the policy. * @param options The options parameters. */ get( resourceGroupName: string, labName: string, policySetName: string, name: string, options?: PoliciesGetOptionalParams ): Promise<PoliciesGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, labName, policySetName, name, options }, getOperationSpec ); } /** * Create or replace an existing policy. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param policySetName The name of the policy set. * @param name The name of the policy. * @param policy A Policy. * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, labName: string, policySetName: string, name: string, policy: Policy, options?: PoliciesCreateOrUpdateOptionalParams ): Promise<PoliciesCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, labName, policySetName, name, policy, options }, createOrUpdateOperationSpec ); } /** * Delete policy. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param policySetName The name of the policy set. * @param name The name of the policy. * @param options The options parameters. */ delete( resourceGroupName: string, labName: string, policySetName: string, name: string, options?: PoliciesDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, labName, policySetName, name, options }, deleteOperationSpec ); } /** * Allows modifying tags of policies. All other properties will be ignored. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param policySetName The name of the policy set. * @param name The name of the policy. * @param policy A Policy. * @param options The options parameters. */ update( resourceGroupName: string, labName: string, policySetName: string, name: string, policy: PolicyFragment, options?: PoliciesUpdateOptionalParams ): Promise<PoliciesUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, labName, policySetName, name, policy, options }, updateOperationSpec ); } /** * ListNext * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param policySetName The name of the policy set. * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( resourceGroupName: string, labName: string, policySetName: string, nextLink: string, options?: PoliciesListNextOptionalParams ): Promise<PoliciesListNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, labName, policySetName, nextLink, options }, listNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/policysets/{policySetName}/policies", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PolicyList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [ Parameters.apiVersion, Parameters.expand, Parameters.filter, Parameters.top, Parameters.orderby ], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labName, Parameters.policySetName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/policysets/{policySetName}/policies/{name}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.Policy }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion, Parameters.expand], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName, Parameters.policySetName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/policysets/{policySetName}/policies/{name}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.Policy }, 201: { bodyMapper: Mappers.Policy }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.policy, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName, Parameters.policySetName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/policysets/{policySetName}/policies/{name}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName, Parameters.policySetName ], headerParameters: [Parameters.accept], serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/policysets/{policySetName}/policies/{name}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.Policy }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.policy1, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName, Parameters.policySetName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PolicyList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [ Parameters.apiVersion, Parameters.expand, Parameters.filter, Parameters.top, Parameters.orderby ], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labName, Parameters.policySetName ], headerParameters: [Parameters.accept], serializer };
the_stack
import * as cdk from '@aws-cdk/core'; import * as ec2 from '@aws-cdk/aws-ec2'; import * as elbv2 from '@aws-cdk/aws-elasticloadbalancingv2'; import * as iam from '@aws-cdk/aws-iam'; import * as kms from '@aws-cdk/aws-kms'; import * as ecs from '@aws-cdk/aws-ecs'; import * as sns from '@aws-cdk/aws-sns'; import * as cw from '@aws-cdk/aws-cloudwatch'; import * as cwe from '@aws-cdk/aws-events'; import * as cwet from '@aws-cdk/aws-events-targets'; import * as cwl from '@aws-cdk/aws-logs'; import * as cw_actions from '@aws-cdk/aws-cloudwatch-actions'; import * as ecr from '@aws-cdk/aws-ecr'; import { IBLEAFrontend } from './blea-frontend-interface'; export interface BLEAECSAppStackProps extends cdk.StackProps { myVpc: ec2.Vpc; appKey: kms.IKey; repository: ecr.Repository; imageTag: string; alarmTopic: sns.Topic; webFront: IBLEAFrontend; } export class BLEAECSAppStack extends cdk.Stack { public readonly ecsClusterName: string; public readonly ecsServiceName: string; public readonly appTargetGroupName: string; public readonly appServerSecurityGroup: ec2.SecurityGroup; public readonly albTgUnHealthyHostCountAlarm: cw.Alarm; public readonly ecsTargetUtilizationPercent: number; public readonly ecsScaleOnRequestCount: number; constructor(scope: cdk.Construct, id: string, props: BLEAECSAppStackProps) { super(scope, id, props); // --------------------- Fargate Cluster ---------------------------- // ---- PreRequesties // Role for ECS Agent // The task execution role grants the Amazon ECS container and Fargate agents permission to make AWS API calls on your behalf. // https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_execution_IAM_role.html const executionRole = new iam.Role(this, 'EcsTaskExecutionRole', { assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com'), managedPolicies: [iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AmazonECSTaskExecutionRolePolicy')], }); // Role for Container // With IAM roles for Amazon ECS tasks, you can specify an IAM role that can be used by the containers in a task. // https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html const serviceTaskRole = new iam.Role(this, 'EcsServiceTaskRole', { assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com'), }); // SecurityGroup for Fargate service // - Inbound access will be added automatically on associating ALB // - Outbound access will be used for DB and AWS APIs const securityGroupForFargate = new ec2.SecurityGroup(this, 'SgFargate', { vpc: props.myVpc, allowAllOutbound: true, // for AWS APIs }); this.appServerSecurityGroup = securityGroupForFargate; // CloudWatch Logs Group for Container const fargateLogGroup = new cwl.LogGroup(this, 'FargateLogGroup', { retention: cwl.RetentionDays.THREE_MONTHS, encryptionKey: props.appKey, }); // Permission to access KMS Key from CloudWatch Logs props.appKey.addToResourcePolicy( new iam.PolicyStatement({ actions: ['kms:Encrypt*', 'kms:Decrypt*', 'kms:ReEncrypt*', 'kms:GenerateDataKey*', 'kms:Describe*'], principals: [new iam.ServicePrincipal(`logs.${cdk.Stack.of(this).region}.amazonaws.com`)], resources: ['*'], conditions: { ArnLike: { 'kms:EncryptionContext:aws:logs:arn': `arn:aws:logs:${cdk.Stack.of(this).region}:${ cdk.Stack.of(this).account }:*`, }, }, }), ); // ---- Cluster definition // Fargate Cluster // - Enabling CloudWatch ContainerInsights const ecsCluster = new ecs.Cluster(this, 'Cluster', { vpc: props.myVpc, containerInsights: true, enableFargateCapacityProviders: true, }); this.ecsClusterName = ecsCluster.clusterName; // Task definition // https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html const ecsTask = new ecs.FargateTaskDefinition(this, 'EcsTask', { executionRole: executionRole, taskRole: serviceTaskRole, cpu: 256, memoryLimitMiB: 512, }); // Container const ecsContainer = ecsTask.addContainer('EcsApp', { // -- SAMPLE: if you want to use your ECR repository, you can use like this. image: ecs.ContainerImage.fromEcrRepository(props.repository, props.imageTag), // -- SAMPLE: if you want to use DockerHub, you can use like this. // image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"), environment: { ENVIRONMENT_VARIABLE_SAMPLE_KEY: 'Environment Variable Sample Value', }, logging: ecs.LogDriver.awsLogs({ streamPrefix: 'BLEA-ECSApp-', logGroup: fargateLogGroup, }), // -- SAMPLE: Get value from SecretsManager // secrets: { // SECRET_VARIABLE_SAMPLE_KEY: ecs.Secret.fromSecretsManager(secretsManagerConstruct, 'secret_key'), // }, }); ecsContainer.addPortMappings({ containerPort: 80, }); // Service const ecsService = new ecs.FargateService(this, 'FargateService', { cluster: ecsCluster, taskDefinition: ecsTask, desiredCount: 2, // The LATEST is recommended platform version. // But if you need another version replace this. // See also: // - https://docs.aws.amazon.com/AmazonECS/latest/userguide/platform_versions.html // - https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecs.FargatePlatformVersion.html platformVersion: ecs.FargatePlatformVersion.LATEST, // https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ecs-readme.html#fargate-capacity-providers capacityProviderStrategies: [ { capacityProvider: 'FARGATE', weight: 1, }, // -- SAMPLE: Fargate Spot //{ // capacityProvider: 'FARGATE_SPOT', // weight: 2, //}, ], vpcSubnets: props.myVpc.selectSubnets({ subnetGroupName: 'Private', // For public DockerHub //subnetGroupName: 'Protected' // For your ECR. Need to use PrivateLinke for ECR }), securityGroups: [securityGroupForFargate], }); this.ecsServiceName = ecsService.serviceName; // Define ALB Target Group // https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-elasticloadbalancingv2.ApplicationTargetGroup.html const lbForAppTargetGroup = props.webFront.appAlbListerner.addTargets('EcsApp', { protocol: elbv2.ApplicationProtocol.HTTP, targets: [ecsService], deregistrationDelay: cdk.Duration.seconds(30), }); this.appTargetGroupName = lbForAppTargetGroup.targetGroupFullName; // SAMPLE: Another way, how to set attibute to TargetGroup - example) Modify algorithm type // lbForAppTargetGroup.setAttribute('load_balancing.algorithm.type', 'least_outstanding_requests'); // SAMPLE: Setup HealthCheck for app // lbForAppTargetGroup.configureHealthCheck({ // path: '/health', // enabled: true, // }); // ECS Task AutoScaling // https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ecs-readme.html#task-auto-scaling const ecsScaling = ecsService.autoScaleTaskCount({ minCapacity: 2, maxCapacity: 10, }); // Scaling with CPU Utilization avarage on all tasks this.ecsTargetUtilizationPercent = 50; // Used in Dashboard Stack ecsScaling.scaleOnCpuUtilization('CpuScaling', { targetUtilizationPercent: this.ecsTargetUtilizationPercent, }); // Scaling with Requests per tasks this.ecsScaleOnRequestCount = 10000; // Used in Dashboard Stack ecsScaling.scaleOnRequestCount('RequestScaling', { requestsPerTarget: this.ecsScaleOnRequestCount, targetGroup: lbForAppTargetGroup, }); // ----------------------- Alarms for ECS ----------------------------- ecsService .metricCpuUtilization({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'FargateCpuUtil', { evaluationPeriods: 3, datapointsToAlarm: 3, threshold: 80, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); // RunningTaskCount - CloudWatch Container Insights metric (Custom metric) // This is a sample of full set configuration for Metric and Alarm // See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html#alarm-evaluation // // new cw.Metric({ // metricName: 'RunningTaskCount', // namespace: 'ECS/ContainerInsights', // dimensions: { // ClusterName: ecsCluster.clusterName, // ServiceName: ecsService.serviceName, // }, // period: cdk.Duration.minutes(1), // statistic: cw.Statistic.AVERAGE, // }) // .createAlarm(this, 'RunningTaskCount', { // evaluationPeriods: 3, // datapointsToAlarm: 2, // threshold: 1, // comparisonOperator: cw.ComparisonOperator.LESS_THAN_THRESHOLD, // actionsEnabled: true, // }) // .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); // ----------------------- Alarms for ALB ----------------------------- // Alarm for ALB - ResponseTime props.webFront.appAlb .metricTargetResponseTime({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'AlbResponseTime', { evaluationPeriods: 3, threshold: 100, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); // Alarm for ALB - HTTP 4XX Count props.webFront.appAlb .metricHttpCodeElb(elbv2.HttpCodeElb.ELB_4XX_COUNT, { period: cdk.Duration.minutes(1), statistic: cw.Statistic.SUM, }) .createAlarm(this, 'AlbHttp4xx', { evaluationPeriods: 3, threshold: 10, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); // Alarm for ALB - HTTP 5XX Count props.webFront.appAlb .metricHttpCodeElb(elbv2.HttpCodeElb.ELB_5XX_COUNT, { period: cdk.Duration.minutes(1), statistic: cw.Statistic.SUM, }) .createAlarm(this, 'AlbHttp5xx', { evaluationPeriods: 3, threshold: 10, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); // Alarm for ALB TargetGroup - HealthyHostCount lbForAppTargetGroup .metricHealthyHostCount({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'AlbTgHealthyHostCount', { evaluationPeriods: 3, threshold: 1, comparisonOperator: cw.ComparisonOperator.LESS_THAN_THRESHOLD, actionsEnabled: true, }) .addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); // Alarm for ALB TargetGroup - UnHealthyHostCount // This alarm will be used on Dashbaord this.albTgUnHealthyHostCountAlarm = lbForAppTargetGroup .metricUnhealthyHostCount({ period: cdk.Duration.minutes(1), statistic: cw.Statistic.AVERAGE, }) .createAlarm(this, 'AlbTgUnHealthyHostCount', { evaluationPeriods: 3, threshold: 1, comparisonOperator: cw.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }); this.albTgUnHealthyHostCountAlarm.addAlarmAction(new cw_actions.SnsAction(props.alarmTopic)); // ----------------------- Event notification for ECS ----------------------------- // https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_cwe_events.html#ecs_service_events new cwe.Rule(this, 'ECSServiceActionEventRule', { description: 'CloudWatch Event Rule to send notification on ECS Service action events.', enabled: true, eventPattern: { source: ['aws.ecs'], detailType: ['ECS Service Action'], detail: { eventType: ['WARN', 'ERROR'], }, }, targets: [new cwet.SnsTopic(props.alarmTopic)], }); // https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_cwe_events.html#ecs_service_deployment_events new cwe.Rule(this, 'ECSServiceDeploymentEventRule', { description: 'CloudWatch Event Rule to send notification on ECS Service deployment events.', enabled: true, eventPattern: { source: ['aws.ecs'], detailType: ['ECS Deployment State Change'], detail: { eventType: ['WARN', 'ERROR'], }, }, targets: [new cwet.SnsTopic(props.alarmTopic)], }); } }
the_stack
import * as d3 from 'd3'; import type {DataListItem, Indicator} from '~/resource/hyper-parameter'; import EventEmitter from 'eventemitter3'; import {ScaleMethod} from '~/resource/hyper-parameter'; import intersection from 'lodash/intersection'; const PUBLIC_PATH: string = import.meta.env.SNOWPACK_PUBLIC_PATH; type YScale = | d3.ScalePoint<string | number> | d3.ScaleLogarithmic<number, number> | d3.ScaleLinear<number, number> | d3.ScaleQuantile<number>; type GridIndicator = Indicator & { scale: ScaleMethod; x: number; yScale: YScale; grid: d3.Selection<SVGGElement, unknown, null, undefined> | null; }; interface LineData { data: DataListItem; color: string; line: d3.Selection<SVGGElement, unknown, null, undefined> | null; } const INDICATORS_HEIGHT = 25; const MIN_COLUMN_WIDTH = 60; const GRID_PADDING = 5; interface EventTypes { hover: [number | null]; select: [number | null]; dragging: [string, number, string[]]; dragged: [string[]]; } export default class ParallelCoordinatesGraph extends EventEmitter<EventTypes> { static GRAPH_HEIGHT = 300; static GRID_BRUSH_WIDTH = 20; private svg; private containerWidth; private colors: string[] = []; private data: DataListItem[] = []; private grids: GridIndicator[] = []; private lines: LineData[] = []; private hoveredLineIndex: number | null = null; private selectedLineIndex: number | null = null; private brushedLineIndexesArray: (number[] | null)[] = []; private dragStartX = 0; private draggingIndicator: GridIndicator | null = null; get svgWidth() { return this.columnWidth * this.grids.length + ParallelCoordinatesGraph.GRID_BRUSH_WIDTH / 2; } get columnWidth() { if (this.grids.length === 0) { return 0; } return Math.max( (this.containerWidth - ParallelCoordinatesGraph.GRID_BRUSH_WIDTH) / this.grids.length, MIN_COLUMN_WIDTH ); } get brushedLineIndexes() { return this.brushedLineIndexesArray.every(i => i == null) ? null : intersection(...this.brushedLineIndexesArray.filter(i => i != null)); } get sequenceGrids() { return [...this.grids].sort((a, b) => a.x - b.x); } constructor(container: HTMLElement) { super(); this.containerWidth = container.getBoundingClientRect().width; const [width, height] = [this.containerWidth, ParallelCoordinatesGraph.GRAPH_HEIGHT + INDICATORS_HEIGHT]; this.svg = d3 .select(container) .append('svg') .attr('width', width) .attr('height', height) .attr('viewBox', `0 0 ${width} ${height}`) .on('click', () => { this.unselectLine(); }); } private getDataByIndicator(indicator: Indicator) { return this.data.map(row => row[indicator.group][indicator.name]); } private removeGrids() { this.brushedLineIndexesArray = []; this.grids.forEach(indicator => { indicator.grid?.remove(); indicator.grid = null; }); } private drawGrids() { this.brushedLineIndexesArray = Array(this.grids.length).fill(null); this.sequenceGrids.forEach((indicator, index) => { const x = indicator.x; const g = this.svg.append('g').classed('grid', true).attr('transform', `translate(${x}, 0)`); const indicatorG = g.append('g').classed('indicator', true).classed(indicator.group, true); const text = indicatorG.append('text').attr('x', 0).attr('y', 0).text(indicator.name); let textLength = text.node()?.getComputedTextLength() ?? 0; while (textLength > this.columnWidth - ParallelCoordinatesGraph.GRID_BRUSH_WIDTH / 2) { text.text(text.text().slice(0, -1) + '...'); textLength = text.node()?.getComputedTextLength() ?? 0; } indicatorG .append('image') .classed('dragger', true) .attr('x', -15) .attr('y', -1) .attr('width', 16) .attr('height', 16) .attr('href', `${PUBLIC_PATH}/icons/dragger.svg`) .call( d3 .drag() // FIXME: complete types, `NEXT TIME MUST` :) // eslint-disable-next-line @typescript-eslint/no-explicit-any .container(this.svg as any) .on('start', ({x}) => this.dragstart(indicator, x)) .on('drag', ({x}) => this.dragging(indicator, x)) // eslint-disable-next-line @typescript-eslint/no-explicit-any .on('end', () => this.dragend()) as any ); const axisG = g.append('g').classed('axis', true).attr('transform', `translate(0, ${INDICATORS_HEIGHT})`); const scale = indicator.yScale; const axis = d3.axisRight(scale as d3.AxisScale<d3.AxisDomain>); if (indicator.scale === ScaleMethod.QUANTILE) { (axis as d3.Axis<number>) .tickValues((scale as d3.ScaleQuantile<number>).quantiles()) .tickFormat(d3.format('-.6g')); } axisG.call(axis); const gridHeight = ParallelCoordinatesGraph.GRAPH_HEIGHT - 2 * GRID_PADDING; const brushWidth = ParallelCoordinatesGraph.GRID_BRUSH_WIDTH; const brushG = axisG .append('g') .classed('grid-brush', true) .attr('transform', `translate(${-brushWidth / 2}, 0)`); brushG.call( d3 .brushY() .extent([ [0, GRID_PADDING - 0.5], [brushWidth, gridHeight + GRID_PADDING + 0.5] ]) .on('brush end', ({selection}) => this.brushed(index, selection)) ); brushG .select('.selection') .attr('fill', null) .attr('fill-opacity', null) .attr('stroke', null) .attr('stroke-width', null); indicator.grid = g; }); } private removeLines() { this.lines.forEach(line => { line.line?.remove(); line.line = null; }); } private drawLines() { this.lines.forEach((row, rowIndex) => { const g = this.svg.append('g').attr('transform', `translate(0, ${INDICATORS_HEIGHT})`); g.append('path').classed('line', true).attr('fill', 'none').attr('stroke-width', 1); g.append('path') .classed('hover-trigger', true) .attr('stroke', 'transparent') .attr('fill', 'none') .attr('stroke-width', 7) .on('mouseenter', () => { if (g.classed('disabled')) { return; } this.hoverLine(rowIndex); }) .on('mouseleave', () => { if (g.classed('disabled')) { return; } this.unhoverLine(); }) .on('click', (e: Event) => { if (g.classed('disabled')) { return; } this.selectLine(rowIndex); e.stopPropagation(); }); row.line = g; }); this.updateLines(false); this.updateLineColors(); this.updateLineWidths(); } private updateLineColors() { this.lines.forEach((row, i) => { const disabled = this.brushedLineIndexes != null && !this.brushedLineIndexes.includes(i); const group = row.line?.classed('disabled', disabled); const line = group?.select('.line'); const circles = group?.selectAll('.select-indicator'); if (disabled) { line?.attr('stroke', null); circles?.attr('stroke', null); } else { this.select(line, true)?.attr('stroke', row.color); this.select(circles, true)?.attr('stroke', row.color); } }); } private updateLineWidths() { this.lines.forEach((g, i) => { let width = 1; if (i === this.hoveredLineIndex || i === this.selectedLineIndex) { width = 3; } this.select(g.line?.select('.line'), true)?.attr('stroke-width', width); }); } private hoverLine(index: number) { this.emit('hover', index); this.hoveredLineIndex = index; this.updateLineWidths(); } private unhoverLine() { if (this.hoveredLineIndex != null) { this.hoveredLineIndex = null; this.emit('hover', null); } this.updateLineWidths(); } private selectLine(index: number) { this.emit('select', index); this.selectedLineIndex = index; const line = this.lines[index]; this.lines.forEach(line => line.line?.selectAll('.select-indicator').remove()); this.sequenceGrids.forEach(g => { line.line ?.append('circle') .classed('select-indicator', true) .attr('cx', g.x) .attr('cy', g.yScale(line.data[g.group][g.name] as number) ?? 0) .attr('r', 4) .attr('stroke', line.color); }); this.updateLineWidths(); } private unselectLine() { if (this.selectedLineIndex != null) { this.lines[this.selectedLineIndex].line?.selectAll('.select-indicator').remove(); this.selectedLineIndex = null; this.emit('select', null); } this.updateLineWidths(); } private calculateLineColors() { this.lines.forEach((line, i) => { line.color = this.colors[i] ?? '#000'; }); } private calculateXScale() { const d = ParallelCoordinatesGraph.GRID_BRUSH_WIDTH / 2; const scale = d3 .scalePoint() .domain(this.sequenceGrids.map(i => i.name)) .range([d, d + this.columnWidth * (this.sequenceGrids.length - 1)]); this.sequenceGrids.forEach(grid => { grid.x = scale(grid.name) ?? 0; }); } private calculateYScales() { const yScales = this.grids.map(grid => { const gridHeight = ParallelCoordinatesGraph.GRAPH_HEIGHT - 2 * GRID_PADDING; let range = [gridHeight + GRID_PADDING, GRID_PADDING]; if (grid.type === 'continuous') { let scale; const values = this.getDataByIndicator(grid).map(v => +v); const extent = d3.extent(values) as [number, number]; if (grid.scale === ScaleMethod.LOGARITHMIC) { scale = d3.scaleLog(); } else if (grid.scale === ScaleMethod.QUANTILE) { const kNumQuantiles = 20; scale = d3.scaleQuantile(); range = d3.range(kNumQuantiles).map(i => range[0] - (i * gridHeight) / (kNumQuantiles - 1)); } else { scale = d3.scaleLinear(); } return (scale.domain(extent) as d3.ScaleLinear<number, number>).range(range) as YScale; } return d3 .scalePoint() .domain((grid.selectedValues as string[]) ?? []) .range(range) .padding(0.1) as YScale; }); this.grids.forEach((grid, i) => { grid.yScale = yScales[i]; }); } private getDiscreteLineBySelection(index: number, [y1, y2]: [number, number]) { const indicator = this.grids[index]; const scale = indicator.yScale as d3.ScalePoint<string | number>; const domain = scale.domain(); const step = scale.step(); const padding = scale.padding() * step; const start = domain.length - Math.min(Math.floor((y2 - GRID_PADDING - padding) / step), domain.length - 1) - 1; const end = domain.length - Math.max(Math.ceil((y1 - GRID_PADDING - padding) / step), 0) - 1; return this.data.reduce<number[]>((result, row, i) => { const vi = domain.indexOf(row[indicator.group][indicator.name]); if (vi >= start && vi <= end) { result.push(i); } return result; }, []); } private getContinuousLineBySelection(index: number, [y1, y2]: [number, number]) { const indicator = this.grids[index]; const scale = indicator.yScale; let start: number; let end: number; if (indicator.scale === ScaleMethod.QUANTILE) { const quantileScale = scale as d3.ScaleQuantile<number>; const range = quantileScale.range(); const domains = range .filter(y => y1 <= y && y <= y2) .map(y => { const domain = quantileScale.invertExtent(y); return y === range[range.length - 1] ? [domain[0], domain[1] + 1] : domain; }); [start, end] = d3.extent(d3.merge<number>(domains)) as [number, number]; } else { const invertScale = (scale as d3.ScaleLogarithmic<number, number> | d3.ScaleLinear<number, number>).invert; start = invertScale(y1); end = invertScale(y2); } if (start > end) { [start, end] = [end, start]; } return this.data.reduce<number[]>((result, row, i) => { const v = row[indicator.group][indicator.name] as number; if (v >= start && v <= end) { result.push(i); } return result; }, []); } private brushed(index: number, selection: [number, number] | null) { const indicator = this.sequenceGrids[index]; if (selection == null) { this.brushedLineIndexesArray[index] = null; } else { if (indicator.type !== 'continuous') { this.brushedLineIndexesArray[index] = this.getDiscreteLineBySelection(index, selection); } else { this.brushedLineIndexesArray[index] = this.getContinuousLineBySelection(index, selection); } } this.updateLineColors(); } private dragstart(indicator: GridIndicator, x: number) { this.draggingIndicator = {...indicator}; this.dragStartX = x; indicator.grid?.classed('dragging', true); } private dragging(indicator: GridIndicator, x: number) { if (this.draggingIndicator) { const dx = x - this.dragStartX; const newX = Math.min( this.svgWidth - this.columnWidth + ParallelCoordinatesGraph.GRID_BRUSH_WIDTH / 2, Math.max(0, this.draggingIndicator.x + dx) ); indicator.x = newX; this.calculateXScale(); this.sequenceGrids.forEach(({grid, name, x}) => grid?.attr('transform', `translate(${name === indicator.name ? newX : x}, 0)`) ); this.updateLines(false, {indicator: indicator.name, x: newX}); this.emit( 'dragging', indicator.name, newX - indicator.x, this.sequenceGrids.map(({name}) => name) ); } } private dragend() { this.draggingIndicator?.grid?.classed('dragging', false); this.draggingIndicator = null; this.updateGrids(); this.updateLines(); this.emit( 'dragged', this.sequenceGrids.map(({name}) => name) ); } private updateGrids(animation = true) { this.sequenceGrids.forEach(({grid, x}) => this.select(grid, animation)?.attr('transform', `translate(${x}, 0)`) ); } private updateLines(animation = true, extra?: {indicator: string; x: number}) { this.lines.forEach(g => { const circles = g.line?.selectAll('.select-indicator').nodes() ?? []; const line = d3.line()( this.sequenceGrids.map(({group, name, x: gx, yScale}, i) => { let x = gx; const y = yScale(g.data[group][name] as number) ?? 0; if (extra && extra.indicator === name) { x = extra.x; } if (circles[i]) { this.select(d3.select(circles[i]), animation)?.attr('cx', x).attr('cy', y); } return [x, y]; }) ); this.select(g.line?.selectAll('path'), animation)?.attr('d', line ?? ''); }); } private select<T extends d3.BaseType, G extends d3.BaseType>( selection: d3.Selection<T, unknown, G, unknown> | null | undefined, animation = false ) { if (animation) { return selection?.transition().duration(75); } return selection; } private setSvgSize() { const width = this.svgWidth; const height = ParallelCoordinatesGraph.GRAPH_HEIGHT + INDICATORS_HEIGHT; this.svg.attr('width', width).attr('height', height).attr('viewBox', `0 0 ${width} ${height}`); } resize(containerWidth: number) { this.containerWidth = containerWidth; this.setSvgSize(); this.calculateXScale(); this.updateGrids(false); this.updateLines(false); } setColors(colors: string[]) { this.colors = colors; this.calculateLineColors(); this.updateLineColors(); } setScaleMethod(name: string, scaleMethod: ScaleMethod) { const indicator = this.grids.find(grid => grid.name === name); if (indicator) { indicator.scale = scaleMethod; this.removeGrids(); this.calculateYScales(); this.drawGrids(); this.updateLines(); } } render(indicators: Indicator[], data: DataListItem[]) { if (indicators.length !== this.grids.length) { this.unselectLine(); } else { for (const newIdi of indicators) { const oldIdi = this.grids.find(g => g.name === newIdi.name); if (!oldIdi || oldIdi.group !== newIdi.group || oldIdi.type !== newIdi.type) { this.unselectLine(); break; } } } this.unhoverLine(); this.removeLines(); this.removeGrids(); this.grids = indicators.map(indicator => ({ ...indicator, scale: ScaleMethod.LINEAR, x: 0, yScale: d3.scaleLinear(), grid: null })); this.data = data; this.setSvgSize(); this.calculateXScale(); this.calculateYScales(); this.lines = data.map(row => { return { data: row, color: '', line: null }; }); this.calculateLineColors(); this.drawLines(); this.drawGrids(); } dispose() { this.removeLines(); this.removeGrids(); this.svg.remove(); } }
the_stack
export enum WindowAction { Minimize = "window.minimize", Maximize = "window.maximize", Restore = "window.restore", Close = "window.close" } export interface FileSelection { canceled: boolean; filePaths: string[]; } export interface OpenFileSelectorOptions { directory?: boolean; } export interface OpenTerminalOptions { command?: string; // terminal inside machine machine?: string; } export interface ProxyServiceOptions { http?: boolean; keepAlive?: boolean; } export interface GlobalUserSettings { startApi: boolean; minimizeToSystemTray: boolean; path: string; logging: { level: string; }; connector: { default: string | undefined; }; } export interface GlobalUserSettingsOptions extends GlobalUserSettings { program: Partial<Program>; engine: Partial<ContainerEngine>; } export interface Controller { name: string; path?: string; version?: string; scope?: string; } export interface Program { name: string; path?: string; version?: string; title?: string; homepage?: string; } export interface EngineConnectorApiSettings { baseURL: string; connectionString: string; } export interface EngineConnectorSettings { api: EngineConnectorApiSettings; program: Program; controller?: Controller; } export interface EngineUserSettingsOptions { id: string; // engine client instance id settings: Partial<EngineConnectorSettings>; } export interface EngineApiOptions { adapter: ContainerAdapter; engine: ContainerEngine; id: string; // engine client instance id // scope: string; // ControllerScope Name baseURL: string; connectionString: string; } export interface EngineProgramOptions { adapter: ContainerAdapter; engine: ContainerEngine; id: string; // engine client instance id // program: Partial<Program>; controller?: Partial<Controller>; } export interface SystemConnection { Identity: string; Name: string; URI: string; } export interface ProgramOutput { stdout?: string | null; stderr?: string | null; } export interface ProgramExecutionResult { pid: number; success: boolean; stdout?: string; stderr?: string; command: string; code: number; } export interface TestResult { subject: string; success: boolean; details?: any; } export interface ProgramTestResult extends TestResult { program?: { path: string; version: string; } scopes?: ControllerScope[]; } export interface Machine { Name: string; Active: boolean; Running: boolean; LastUp: string; VMType: string; Created: string; } export interface WSLDistribution { Name: string; State: string; Version: string; Default: boolean; Current: boolean; } export interface LIMAInstance { Name: string; Status: string; SSH: string; Arch: string; CPUs: string; Memory: string; Disk: string; Dir: string; } export type ControllerScope = Machine | WSLDistribution | LIMAInstance; export enum Platforms { Browser = "browser", Linux = "Linux", Mac = "Darwin", Windows = "Windows_NT", Unknown = "unknown" } export enum ContainerAdapter { PODMAN = "podman", DOCKER = "docker", } export enum ContainerEngine { PODMAN_NATIVE = "podman.native", PODMAN_SUBSYSTEM_WSL = "podman.subsystem.wsl", PODMAN_SUBSYSTEM_LIMA = "podman.subsystem.lima", PODMAN_VIRTUALIZED = "podman.virtualized", PODMAN_REMOTE = "podman.remote", // Docker DOCKER_NATIVE = "docker.native", DOCKER_SUBSYSTEM_WSL = "docker.subsystem.wsl", DOCKER_SUBSYSTEM_LIMA = "docker.subsystem.lima", DOCKER_VIRTUALIZED = "docker.virtualized", DOCKER_REMOTE = "docker.remote", } export interface EngineConnectorSettingsMap { expected: EngineConnectorSettings; user: Partial<EngineConnectorSettings>; current: EngineConnectorSettings; } export interface Connector { id: string; adapter: ContainerAdapter; engine: ContainerEngine; availability: { all: boolean; engine: boolean; api: boolean; program: boolean; controller?: boolean; report: { engine: string; api: string; program: string; controller?: string; } }; settings: EngineConnectorSettingsMap; scopes?: ControllerScope[]; } export interface ApplicationDescriptor { environment: string; version: string; osType: Platforms; provisioned: boolean; running: boolean; // computed connectors: Connector[]; currentConnector: Connector; userSettings: GlobalUserSettings; } export interface ConnectOptions { startApi: boolean; id: string; settings: EngineConnectorSettings; } export interface ContainerClientResult<T = unknown> { success: boolean; result: T; warnings: any[]; } export interface Distribution { distribution: string; variant: string; version: string; } export interface SystemVersion { APIVersion: string; Built: number; BuiltTime: string; GitCommit: string; GoVersion: string; OsArch: string; Version: string; } export interface SystemPlugin {} export interface SystemPluginMap { [key: string]: SystemPlugin; } export interface SystemInfoHost { os: string; kernel: string; hostname: string; distribution: Distribution; } export interface SystemInfoRegistries { [key: string]: string[]; } export interface SystemInfo { host: SystemInfoHost; plugins: SystemPluginMap; registries: SystemInfoRegistries; store: any; version: SystemVersion; } export interface ContainerStats { read: string; preread: string; pids_stats: any; blkio_stats: { io_service_bytes_recursive: any[]; io_serviced_recursive: null; io_queue_recursive: null; io_service_time_recursive: null; io_wait_time_recursive: null; io_merged_recursive: null; io_time_recursive: null; sectors_recursive: null; }; num_procs: number; storage_stats: any; cpu_stats: { cpu_usage: { total_usage: number; percpu_usage: number[]; usage_in_kernelmode: number; usage_in_usermode: number; }; system_cpu_usage: number; online_cpus: number; cpu: number; throttling_data: { periods: number; throttled_periods: number; throttled_time: number; }; }; precpu_stats: { cpu_usage: { total_usage: number; usage_in_kernelmode: number; usage_in_usermode: number; }; cpu: number; throttling_data: { periods: number; throttled_periods: number; throttled_time: number; }; }; memory_stats: { usage: number; max_usage: number; limit: number; }; name: string; Id: string; networks: { network: { rx_bytes: number; rx_packets: number; rx_errors: number; rx_dropped: number; tx_bytes: number; tx_packets: number; tx_errors: number; tx_dropped: number; }; }; } export interface ContainerInspect { Env: string[]; } // See libpod/define/podstate.go export enum ContainerStateList { CREATED = "created", ERROR = "error", EXITED = "exited", PAUSED = "paused", RUNNING = "running", DEGRADED = "degraded", STOPPED = "stopped", } export interface ContainerState { Dead: boolean; Error: string; ExitCode: number; FinishedAt: string; Healthcheck: { Status: string; FailingStreak: number; Log: any; }; OOMKilled: boolean; OciVersion: string; Paused: boolean; Pid: number; Restarting: boolean; Running: boolean; StartedAt: string; Status: ContainerStateList; } export interface ContainerPort { containerPort: number; hostPort: number; hostIP: string; // alternative - why ?!? container_port: number; host_port: number; host_ip: string; range: number; protocol: string; } export interface ContainerPorts { [key: string]: ContainerPort; } export interface ContainerNetworkSettingsPorts { HostIp: string; HostPort: string; } export interface ContainerNetworkSettingsPortsMap { [key: string]: ContainerNetworkSettingsPorts[]; } export interface ContainerNetworkSettings { EndpointID: string; Gateway: string; IPAddress: string; IPPrefixLen: number; IPv6Gateway: string; GlobalIPv6Address: string; GlobalIPv6PrefixLen: number; MacAddress: string; Bridge: string; SandboxID: string; HairpinMode: false; LinkLocalIPv6Address: string; LinkLocalIPv6PrefixLen: number; Ports: ContainerNetworkSettingsPortsMap; SandboxKey: string; } export interface ContainerNetworkSettings { EndpointID: string; Gateway: string; IPAddress: string; IPPrefixLen: number; IPv6Gateway: string; GlobalIPv6Address: string; GlobalIPv6PrefixLen: number; MacAddress: string; Bridge: string; SandboxID: string; HairpinMode: false; LinkLocalIPv6Address: string; LinkLocalIPv6PrefixLen: number; Ports: ContainerNetworkSettingsPortsMap; SandboxKey: string; } export interface ContainerConnectOptions { id: string; title?: string; shell?: string; } export interface Container { AutoRemove: boolean; Command: string[]; Created: string; CreatedAt: string; ExitCode: number; Exited: false; ExitedAt: number; Id: string; Image: string; ImageName?: string; ImageID: string; // For Docker API it is prefixed by sha256: IsInfra: boolean; Labels: { [key: string]: string } | null; Config: ContainerInspect; Stats: ContainerStats | null; Logs?: string[] | null; Mounts: any[]; Names: string[]; Name?: string; Namespaces: any; Networks: any | null; Pid: number; Pod: string; PodName: string; Ports: ContainerPorts; Size: any | null; StartedAt: number; State: ContainerStateList | ContainerState; Status: string; // NetworkSettings?: ContainerNetworkSettings; Kube?: string; // Computed Computed: { Name?: string; Group?: string; NameInGroup?: string; DecodedState: ContainerStateList; } } export interface ContainerGroup { Id: string; // uuid v4 Name?: string; Items: Container[]; Report: { [key in ContainerStateList]: number }; } export interface ContainerImageHistory { id: string; created: string; Created: string; CreatedBy: string; Size: number; Comment: string; } export interface ContainerImage { Containers: number; Created: number; CreatedAt: string; Digest: string; History: ContainerImageHistory[]; // custom field Id: string; Labels: { maintainer: string; } | null; Names: string[]; NamesHistory?: string[]; ParentId: string; RepoTags?: string[]; SharedSize: number; Size: number; VirtualSize: number; // computed Name: string; Tag: string; Registry: string; // from detail Config: { Cmd: string[]; Env: string[]; ExposedPorts: { [key: string]: number; }; StopSignal: string; WorkDir: string; }; // Docker specific RepoDigests?: string[]; } export interface SecretSpecDriverOptionsMap { [key: string]: string; } export interface SecretSpecDriver { Name: string; Options: SecretSpecDriverOptionsMap; } export interface SecretSpec { Driver: SecretSpecDriver; Name: string; } export interface Secret { ID: string; Spec: SecretSpec; CreatedAt: string; UpdatedAt: string; } export interface Volume { Anonymous: boolean; CreatedAt: string; GID: number; UID: number; Driver: string; Labels: { [key: string]: string }; Mountpoint: string; Name: string; Options: { [key: string]: string }; Scope: string; Status: { [key: string]: string }; } export interface ContainerImagePortMapping { guid: string; container_port: number; host_ip: string; host_port: number; protocol: "tcp" | "udp" | "sdp"; } export interface ContainerImageMount { driver: "local"; device?: string; type: "bind" | "tmpfs" | "volume" | "image" | "devpts"; source?: string; destination: string; access?: "rw" | "ro"; size?: number; } export const MOUNT_TYPES = ["bind", "tmpfs", "volume", "image", "devpts"]; export const MOUNT_ACCESS = [ { title: "Read only", type: "ro" }, { title: "Read / Write", type: "rw" } ]; export enum PodStatusList { CREATED = "Created", ERROR = "Error", EXITED = "Exited", PAUSED = "Paused", RUNNING = "Running", DEGRADED = "Degraded", STOPPED = "Stopped", DEAD = "Dead", } export interface PodContainer {} export interface PodProcessReport { Processes: string[]; Titles: string[]; } export interface Pod { Cgroup: string; Created: string; Id: string; InfraId: string; Labels: { [key: string]: string }; Name: string; NameSpace: string; Networks: string[]; Status: PodStatusList; Pid: string; NumContainers: number; Containers: PodContainer[]; // computed Processes: PodProcessReport; Kube?: string; Logs?: ProgramOutput; } export interface SystemStore { configFile: string; containerStore: { number: number; paused: number; running: number; stopped: number; }; } export interface SystemPruneReport { ContainerPruneReports: any; ImagePruneReports: any; PodPruneReport: any; ReclaimedSpace: number; VolumePruneReports: any; } export interface SystemResetReport {} export interface FindProgramOptions { engine: ContainerEngine; id: string; // connector id program: string; scope?: string; } export interface GenerateKubeOptions { entityId: string; } export interface CreateMachineOptions {} export interface FetchMachineOptions { Name: string; // name or id } export interface ContainerClientResponse<T = unknown> { ok: boolean; status: number; statusText: string; data: T; headers: {[key: string]: string}; } export interface ContainerClientResult<T = unknown> { success: boolean; result: T; warnings: any[]; } export interface ProxyRequest { request: any; baseURL: string; socketPath: string; engine: ContainerEngine; adapter: ContainerAdapter; scope?: string; } export interface NetworkIPAMOptions { [key: string]: string; } export interface NetworkSubnetLeaseRange { end_ip: string; start_ip: string; } export interface NetworkSubnet { gateway: string; lease_range: NetworkSubnetLeaseRange; subnet: string; } export interface Network { created: string; dns_enabled: boolean; driver: string; id: string; internal: boolean; ipam_options: NetworkIPAMOptions; ipv6_enabled: boolean; labels: { [key:string]: string}; name: string; network_interface: string; options: { [key:string]: string}; subnets: NetworkSubnet[]; } export interface SecurityVulnerability { Severity: string; Published: string; Description: string; VulnerabilityID: string; PrimaryURL: string; // injected guid: string; } export interface SecurityReportResultGroup { Class: string; Target: string; Type: string; Vulnerabilities: SecurityVulnerability[]; // injected guid: string; } export interface SecurityReportResult { Results: SecurityReportResultGroup[]; } export interface SecurityReport { provider: string; status: "success" | "failure"; fault?: { details: string; error: string; }; result?: SecurityReportResult; scanner: { database: { DownloadedAt: string; NextUpdate: string; UpdatedAt: string; Version: string; }, name: string; path: string; version: string; }, counts: { CRITICAL: number; HIGH: number; MEDIUM: number; LOW: number; } } export default interface Application { setup: () => any; minimize: () => void; maximize: () => void; restore: () => void; close: () => void; exit: () => void; relaunch: () => void; openDevTools: () => void; openFileSelector: (options?: OpenFileSelectorOptions) => Promise<FileSelection>; openTerminal: (options?: OpenTerminalOptions) => Promise<boolean>; getEngine: () => Promise<ContainerEngine>; // settings setGlobalUserSettings: (settings: Partial<GlobalUserSettings>) => Promise<GlobalUserSettings>; getGlobalUserSettings: () => Promise<GlobalUserSettings>; setEngineUserSettings: (id: string, settings: Partial<EngineConnectorSettings>) => Promise<EngineConnectorSettings>; getEngineUserSettings: (id: string) => Promise<EngineConnectorSettings>; getPodLogs: (Id: string, tail?: number) => Promise<ProgramExecutionResult>; generateKube: (Id: string) => Promise<ProgramExecutionResult>; getControllerScopes: () => Promise<ControllerScope[]>; getMachines: () => Promise<Machine[]>; connectToMachine: (Name: string) => Promise<boolean>; restartMachine: (Name: string) => Promise<boolean>; stopMachine: (Name: string) => Promise<boolean>; startMachine: (Name: string) => Promise<boolean>; removeMachine: (Name: string) => Promise<boolean>; createMachine: (opts: any) => Promise<Machine>; inspectMachine: (Name: string) => Promise<Machine>; getSystemInfo: () => Promise<SystemInfo>; connectToContainer: (item: ContainerConnectOptions) => Promise<boolean>; testProgramReachability: (opts: EngineProgramOptions) => Promise<ProgramTestResult>; testApiReachability: (opts: EngineApiOptions) => Promise<TestResult>; findProgram: (opts: FindProgramOptions) => Promise<Program>; pruneSystem: () => Promise<SystemPruneReport>; resetSystem: () => Promise<SystemResetReport>; // proxy proxyHTTPRequest: <T>(request: ProxyRequest) => Promise<T>; checkSecurity: (opts?: any) => Promise<SecurityReport>; // startup start: (opts?: ConnectOptions) => Promise<ApplicationDescriptor>; };
the_stack
import * as moment from "moment"; import * as React from "react"; import * as DayPicker from "react-day-picker"; import { Link } from "react-router-dom"; import { Button, Container, Form, Header, Icon, Input, Popup, Progress, Segment } from "semantic-ui-react"; import { IEpisode } from "../../../lib/interfaces"; import { colors, globalStyles } from "../../../lib/styles"; interface IEpisodeProps { error?: string; onError?: (message: string) => void; item: IEpisode; progress?: number; uploadError?: string; editItemHandler: (params: { episodeId: string }) => Promise<void>; deleteItemHandler: (item: IEpisode) => void; publishItemHandler: (item: IEpisode) => void; unpublishItemHandler: (item: IEpisode) => void; } interface IEpisodeState { error?: string; } const onEpisodeEdit = (props: IEpisodeProps) => async (e: React.MouseEvent<HTMLButtonElement>) => { await props.editItemHandler({ episodeId: props.item._id }); window.location.href = `/#/episode/${props.item._id}`; }; const onEpisodeOpen = async (props: IEpisodeProps) => { await props.editItemHandler({ episodeId: props.item._id }); window.location.href = `/#/episode/${props.item._id}`; }; const onEpisodeDelete = (props: IEpisodeProps) => (e: React.MouseEvent<HTMLButtonElement>) => { const verified = confirm("Are you sure you want to delete this episode?"); if (verified) { props.deleteItemHandler(props.item); } e.preventDefault(); }; const onPublishItem = (props: IEpisodeProps) => (e: React.MouseEvent<HTMLButtonElement>) => { const item = props.item; let error = ""; if (!item.audioUrl) { error += "Audio"; } if (!item.title) { error += (error ? ", " : "") + "Title"; } if (!item.summary) { error += (error ? ", " : "") + "Summary"; } if (!item.fullContent) { error += (error ? ", " : "") + "Full Content"; } if (error) { props.onError("Please fill out all of the missing details before publishing: " + error); } else { props.publishItemHandler(props.item); } e.preventDefault(); }; const onSchedulePublish = (props: IEpisodeProps) => (e: React.MouseEvent<HTMLButtonElement>) => { // Scheduled publish action [TO-DO] e.preventDefault(); }; const onUnpublishItem = (props: IEpisodeProps) => (e: React.MouseEvent<HTMLButtonElement>) => { props.unpublishItemHandler(props.item); e.preventDefault(); }; interface IScheduleButtonProps { currentEpisode?: IEpisode; publishItemHandler: (item: IEpisode) => void; } export interface IScheduleButtonState { pickingDate?: boolean; time_of_day?: string; scheduledDate?: Date; scheduledHours?: string; scheduledMinutes?: string; } class ScheduleButton extends React.Component<IScheduleButtonProps, IScheduleButtonState> { public state: IScheduleButtonState = { pickingDate: false, time_of_day: "AM", scheduledHours: "00", scheduledMinutes: "00", scheduledDate: new Date(), }; public render() { return ( <Popup trigger={ <div style={{ width: 40, marginLeft: 50 }}> <Popup trigger={ <Form.Button onClick={(e) => { e.preventDefault(); this.setState({ pickingDate: true }); }} style={{ ...style.publishButton, fontSize: "120%", width: 40 }} > <Icon size="large" name="calendar" /> </Form.Button>} style={style.tooltip} basic size="tiny" content="Schedule" /> </div>} style={style.calendarTooltip} on="click" size="tiny" open={this.state.pickingDate} onClose={() => this.setState({ pickingDate: false })} onOpen={() => this.setState({ pickingDate: true })} content={ <div> <Header textAlign="center" as="h3"> Schedule Publish </Header> <DayPicker initialMonth={this.state.scheduledDate} selectedDays={this.state.scheduledDate} onDayClick={(e: Date) => { this.setState({ scheduledDate: e }); }} /> <Segment style={{ paddingBottom: 0, paddingTop: 0, }} basic> <Input value={this.state.scheduledHours} onChange={(e, input) => { let val = input.value; if (Number(val) > 12) { val = "12"; } if (Number(val) < 0) { val = "00"; } this.setState({ scheduledHours: val }); }} style={{ width: 47, padding: 0 }} type={"number"} placeholder="00" /> <span style={{ marginLeft: 5, marginRight: 5 }}>:</span> <Input value={this.state.scheduledMinutes} // tslint:disable-next-line:max-line-length onChange={(e, input) => { let val = input.value; if (Number(val) > 60) { val = "60"; } if (Number(val) < 0) { val = "00"; } this.setState({ scheduledMinutes: val }); }} type={"number"} style={{ width: 47, padding: 0 }} placeholder="00" /> <Button.Group floated="right" style={{ marginLeft: 5 }}> <Button style={{ padding: 10.5, paddingLeft: 10, paddingRight: 10, // tslint:disable-next-line:max-line-length backgroundColor: this.state.time_of_day === "AM" ? "lightgray" : "#EEE", }} onClick={() => this.switchTimeOfDay("AM")}>AM</Button> <Button style={{ padding: 10.5, paddingLeft: 10, paddingRight: 10, // tslint:disable-next-line:max-line-length backgroundColor: this.state.time_of_day === "PM" ? "lightgray" : "#EEE", }} onClick={() => this.switchTimeOfDay("PM")}>PM</Button> </Button.Group> </Segment> <Segment basic> <Button onClick={() => this.setState({ pickingDate: false })} basic size="small" floated="left" negative>Cancel</Button> <Button onClick={(e) => { const schedule = this.state.scheduledDate; let hours = this.state.scheduledHours; const minutes = this.state.scheduledMinutes; if (this.state.time_of_day === "PM") { hours = String(Number(hours) + 12); } schedule.setHours(Number(hours)); schedule.setMinutes(Number(minutes)); schedule.setSeconds(0); schedule.setMilliseconds(0); const item = { ...this.props.currentEpisode, published: true, publishedAt: schedule, }; if (item.audioUrl) { item.published = true; this.props.publishItemHandler(item); } }} size="small" floated="right" positive>Schedule</Button> </Segment> </div> } /> ); } protected switchTimeOfDay(new_time) { this.setState({ time_of_day: new_time, }); } } const renderPublishButton = (props: IEpisodeProps) => { if (props.item.published) { return ( <span> <Popup style={{ ...globalStyles.tooltip, margin: 0, marginBottom: 5, marginLeft: 15, }} basic size="tiny" trigger={ <Button floated="left" style={style.publishButton} onClick={onUnpublishItem(props)} > <Icon name="delete calendar" style={style.publishIcon} /> </Button>} content="Unpublish" /> <div style={{ marginLeft: 0 }}> {(new Date(props.item.publishedAt)).getTime() <= (new Date()).getTime() ? "Published on " : "Scheduled for " } {moment(props.item.publishedAt).format("l")} {(new Date(props.item.publishedAt)).getTime() <= (new Date()).getTime() ? "" : " " + moment(props.item.publishedAt).format("LT") } </div> </span> ); } return ( <span> <Popup style={{ ...globalStyles.tooltip, margin: 0, marginBottom: 0, marginLeft: 15, }} basic size="tiny" trigger={ <Button floated="left" style={style.publishButton} onClick={onPublishItem(props)} > <Icon size="large" name="external share" style={style.publishIcon} /> </Button>} content="Publish" /> <div> <ScheduleButton currentEpisode={props.item} publishItemHandler={props.publishItemHandler} /> </div> </span> ); }; const renderUploadProgressBar = (props: IEpisodeProps) => { const uploadProgress: number = props.progress; const uploadError: string = props.uploadError; if ((!uploadProgress || uploadProgress === 100) && !uploadError) { return null; } return ( <div style={{ color: uploadError ? colors.negative : colors.positive, display: "flex", flexDirection: "row", fontSize: "80%", justifyContent: "center", }}> Uploading audio <Progress error={!!uploadError} color="green" percent={uploadProgress} style={style.uploadProgress} size="small" /> {!!uploadError ? uploadError : (uploadProgress + "%") } </div> ); }; const renderError = (props: IEpisodeProps) => { return (props.error ? ( <div style={style.errorMessage}> {props.error} </div> ) : null); }; function EpisodeCard(props: IEpisodeProps) { return ( <Segment style={style.card}> <Header style={style.header} > {renderError(props)} {renderUploadProgressBar(props)} <Popup style={{ ...globalStyles.tooltip, margin: 0, marginBottom: 0, marginLeft: 20, }} basic size="tiny" trigger={ <Button floated="right" style={style.editIcon} onClick={onEpisodeEdit(props)}> <Icon link name="edit" /> </Button>} content="Edit" /> </Header> <Segment basic style={style.content}> <a onClick={(e) => onEpisodeOpen(props)} style={style.title}> {props.item.title} </a> {props.item.published ? <Header style={style.downloadsCount} floated="right" as="h4"> {props.item.downloadsCount || 0} downloads </Header> : null } </Segment> <div style={style.footer}> <span style={style.footerDate}> {renderPublishButton(props)} </span> <span> <Popup style={{ ...globalStyles.tooltip, margin: 0, marginBottom: 0, marginLeft: 10, }} basic size="tiny" trigger={ <Button style={style.trashIcon} floated="right" onClick={onEpisodeDelete(props)}> <Icon link name="trash outline" /> </Button>} content="Delete" /> </span> </div> </Segment> ); } // tslint:disable-next-line:max-classes-per-file export default class Episode extends React.Component<IEpisodeProps, {}> { public state = { error: "", }; public onError(message: string) { this.setState({ error: message }); } public render() { return ( <div> {EpisodeCard({ ...this.props, ...this.state, onError: (message) => this.onError(message) })} </div> ); } } const style = { card: { marginBottom: 15, }, footer: { display: "flex", }, footerDate: { color: "gray", flex: 1, }, publishButton: { margin: 0, padding: 0, paddingLeft: 5, backgroundColor: "transparent", }, uploadProgress: { width: "20%", marginRight: 15, marginLeft: 15, marginTop: 6, }, header: { paddingBottom: 15, flex: 1, flexDirection: "row", flexWrap: "nowrap", }, editIcon: { backgroundColor: "transparent", padding: 0, paddingLeft: 10, marginRight: -10, fontSize: "160%", }, trashIcon: { backgroundColor: "transparent", padding: 0, paddingLeft: 10, marginRight: -10, marginTop: 0, fontSize: "200%", }, content: { paddingLeft: 0, paddingRight: 0, border: 0, fontSize: "120%", overflow: "hidden", display: "flex", }, title: { cursor: "pointer", textAlign: "left", ...globalStyles.text, whiteSpace: "nowrap", overflow: "hidden" as "hidden", textOverflow: "ellipsis", }, downloadsCount: { color: colors.mainVibrant, fontWeight: "700", minWidth: 100, textAlign: "right", justifyContent: "flex-end", flex: 1, }, publishIcon: { fontSize: "200%", }, calendarIcon: { fontSize: "180%", marginLeft: 0, margin: 0, padding: 0, paddingLeft: 5, backgroundColor: "transparent", }, errorMessage: { color: colors.negative, fontSize: "80%", fontWeight: 700 as 700, textAlign: "center", }, tooltip: { ...globalStyles.tooltip, margin: 0, marginBottom: -10, marginLeft: 15, }, calendarTooltip: { }, };
the_stack
import * as nls from 'vs/nls'; import { Event, Emitter } from 'vs/base/common/event'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { ALL_INTERFACES_ADDRESSES, isAllInterfaces, isLocalhost, ITunnelService, LOCALHOST_ADDRESSES, PortAttributesProvider, ProvidedOnAutoForward, ProvidedPortAttributes, RemoteTunnel, TunnelPrivacyId, TunnelProtocol } from 'vs/platform/tunnel/common/tunnel'; import { Disposable, IDisposable } from 'vs/base/common/lifecycle'; import { IEditableData } from 'vs/workbench/common/views'; import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { TunnelInformation, TunnelDescription, IRemoteAuthorityResolverService, TunnelPrivacy } from 'vs/platform/remote/common/remoteAuthorityResolver'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IAddressProvider } from 'vs/platform/remote/common/remoteAgentConnection'; import { isNumber, isObject, isString } from 'vs/base/common/types'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { hash } from 'vs/base/common/hash'; import { ILogService } from 'vs/platform/log/common/log'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { flatten } from 'vs/base/common/arrays'; import Severity from 'vs/base/common/severity'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { URI } from 'vs/base/common/uri'; import { deepClone } from 'vs/base/common/objects'; export const IRemoteExplorerService = createDecorator<IRemoteExplorerService>('remoteExplorerService'); export const REMOTE_EXPLORER_TYPE_KEY: string = 'remote.explorerType'; const TUNNELS_TO_RESTORE = 'remote.tunnels.toRestore'; export const TUNNEL_VIEW_ID = '~remote.forwardedPorts'; export const TUNNEL_VIEW_CONTAINER_ID = '~remote.forwardedPortsContainer'; export const PORT_AUTO_FORWARD_SETTING = 'remote.autoForwardPorts'; export const PORT_AUTO_SOURCE_SETTING = 'remote.autoForwardPortsSource'; export const PORT_AUTO_SOURCE_SETTING_PROCESS = 'process'; export const PORT_AUTO_SOURCE_SETTING_OUTPUT = 'output'; export enum TunnelType { Candidate = 'Candidate', Detected = 'Detected', Forwarded = 'Forwarded', Add = 'Add' } export interface ITunnelItem { tunnelType: TunnelType; remoteHost: string; remotePort: number; localAddress?: string; protocol: TunnelProtocol; localUri?: URI; localPort?: number; name?: string; closeable?: boolean; source: { source: TunnelSource; description: string; }; privacy: TunnelPrivacy; processDescription?: string; readonly label: string; } export enum TunnelEditId { None = 0, New = 1, Label = 2, LocalPort = 3 } interface TunnelProperties { remote: { host: string; port: number }; local?: number; name?: string; source?: { source: TunnelSource; description: string; }; elevateIfNeeded?: boolean; privacy?: string; } export enum TunnelSource { User, Auto, Extension } export const UserTunnelSource = { source: TunnelSource.User, description: nls.localize('tunnel.source.user', "User Forwarded") }; export const AutoTunnelSource = { source: TunnelSource.Auto, description: nls.localize('tunnel.source.auto', "Auto Forwarded") }; export interface Tunnel { remoteHost: string; remotePort: number; localAddress: string; localUri: URI; protocol: TunnelProtocol; localPort?: number; name?: string; closeable?: boolean; privacy: TunnelPrivacyId | string; runningProcess: string | undefined; hasRunningProcess?: boolean; pid: number | undefined; source: { source: TunnelSource; description: string; }; } export function makeAddress(host: string, port: number): string { return host + ':' + port; } export function parseAddress(address: string): { host: string; port: number } | undefined { const matches = address.match(/^([a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*:)?([0-9]+)$/); if (!matches) { return undefined; } return { host: matches[1]?.substring(0, matches[1].length - 1) || 'localhost', port: Number(matches[2]) }; } export function mapHasAddress<T>(map: Map<string, T>, host: string, port: number): T | undefined { const initialAddress = map.get(makeAddress(host, port)); if (initialAddress) { return initialAddress; } if (isLocalhost(host)) { // Do localhost checks for (const testHost of LOCALHOST_ADDRESSES) { const testAddress = makeAddress(testHost, port); if (map.has(testAddress)) { return map.get(testAddress); } } } else if (isAllInterfaces(host)) { // Do all interfaces checks for (const testHost of ALL_INTERFACES_ADDRESSES) { const testAddress = makeAddress(testHost, port); if (map.has(testAddress)) { return map.get(testAddress); } } } return undefined; } export function mapHasAddressLocalhostOrAllInterfaces<T>(map: Map<string, T>, host: string, port: number): T | undefined { const originalAddress = mapHasAddress(map, host, port); if (originalAddress) { return originalAddress; } const otherHost = isAllInterfaces(host) ? 'localhost' : (isLocalhost(host) ? '0.0.0.0' : undefined); if (otherHost) { return mapHasAddress(map, otherHost, port); } return undefined; } export enum OnPortForward { Notify = 'notify', OpenBrowser = 'openBrowser', OpenBrowserOnce = 'openBrowserOnce', OpenPreview = 'openPreview', Silent = 'silent', Ignore = 'ignore' } export interface Attributes { label: string | undefined; onAutoForward: OnPortForward | undefined; elevateIfNeeded: boolean | undefined; requireLocalPort: boolean | undefined; protocol: TunnelProtocol | undefined; } interface PortRange { start: number; end: number } interface HostAndPort { host: string; port: number } interface PortAttributes extends Attributes { key: number | PortRange | RegExp | HostAndPort; } export class PortsAttributes extends Disposable { private static SETTING = 'remote.portsAttributes'; private static DEFAULTS = 'remote.otherPortsAttributes'; private static RANGE = /^(\d+)\-(\d+)$/; private static HOST_AND_PORT = /^([a-z0-9\-]+):(\d{1,5})$/; private portsAttributes: PortAttributes[] = []; private defaultPortAttributes: Attributes | undefined; private _onDidChangeAttributes = new Emitter<void>(); public readonly onDidChangeAttributes = this._onDidChangeAttributes.event; constructor(private readonly configurationService: IConfigurationService) { super(); this._register(configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration(PortsAttributes.SETTING) || e.affectsConfiguration(PortsAttributes.DEFAULTS)) { this.updateAttributes(); } })); this.updateAttributes(); } private updateAttributes() { this.portsAttributes = this.readSetting(); this._onDidChangeAttributes.fire(); } getAttributes(port: number, host: string, commandLine?: string): Attributes | undefined { let index = this.findNextIndex(port, host, commandLine, this.portsAttributes, 0); const attributes: Attributes = { label: undefined, onAutoForward: undefined, elevateIfNeeded: undefined, requireLocalPort: undefined, protocol: undefined }; while (index >= 0) { const found = this.portsAttributes[index]; if (found.key === port) { attributes.onAutoForward = found.onAutoForward ?? attributes.onAutoForward; attributes.elevateIfNeeded = (found.elevateIfNeeded !== undefined) ? found.elevateIfNeeded : attributes.elevateIfNeeded; attributes.label = found.label ?? attributes.label; attributes.requireLocalPort = found.requireLocalPort; attributes.protocol = found.protocol; } else { // It's a range or regex, which means that if the attribute is already set, we keep it attributes.onAutoForward = attributes.onAutoForward ?? found.onAutoForward; attributes.elevateIfNeeded = (attributes.elevateIfNeeded !== undefined) ? attributes.elevateIfNeeded : found.elevateIfNeeded; attributes.label = attributes.label ?? found.label; attributes.requireLocalPort = (attributes.requireLocalPort !== undefined) ? attributes.requireLocalPort : undefined; attributes.protocol = attributes.protocol ?? found.protocol; } index = this.findNextIndex(port, host, commandLine, this.portsAttributes, index + 1); } if (attributes.onAutoForward !== undefined || attributes.elevateIfNeeded !== undefined || attributes.label !== undefined || attributes.requireLocalPort !== undefined || attributes.protocol !== undefined) { return attributes; } // If we find no matches, then use the other port attributes. return this.getOtherAttributes(); } private hasStartEnd(value: number | PortRange | RegExp | HostAndPort): value is PortRange { return ((<any>value).start !== undefined) && ((<any>value).end !== undefined); } private hasHostAndPort(value: number | PortRange | RegExp | HostAndPort): value is HostAndPort { return ((<any>value).host !== undefined) && ((<any>value).port !== undefined) && isString((<any>value).host) && isNumber((<any>value).port); } private findNextIndex(port: number, host: string, commandLine: string | undefined, attributes: PortAttributes[], fromIndex: number): number { if (fromIndex >= attributes.length) { return -1; } const shouldUseHost = !isLocalhost(host) && !isAllInterfaces(host); const sliced = attributes.slice(fromIndex); const foundIndex = sliced.findIndex((value) => { if (isNumber(value.key)) { return shouldUseHost ? false : value.key === port; } else if (this.hasStartEnd(value.key)) { return shouldUseHost ? false : (port >= value.key.start && port <= value.key.end); } else if (this.hasHostAndPort(value.key)) { return (port === value.key.port) && (host === value.key.host); } else { return commandLine ? value.key.test(commandLine) : false; } }); return foundIndex >= 0 ? foundIndex + fromIndex : -1; } private readSetting(): PortAttributes[] { const settingValue = this.configurationService.getValue(PortsAttributes.SETTING); if (!settingValue || !isObject(settingValue)) { return []; } const attributes: PortAttributes[] = []; for (let attributesKey in settingValue) { if (attributesKey === undefined) { continue; } const setting = (<any>settingValue)[attributesKey]; let key: number | PortRange | RegExp | HostAndPort | undefined = undefined; if (Number(attributesKey)) { key = Number(attributesKey); } else if (isString(attributesKey)) { if (PortsAttributes.RANGE.test(attributesKey)) { const match = attributesKey.match(PortsAttributes.RANGE); key = { start: Number(match![1]), end: Number(match![2]) }; } else if (PortsAttributes.HOST_AND_PORT.test(attributesKey)) { const match = attributesKey.match(PortsAttributes.HOST_AND_PORT); key = { host: match![1], port: Number(match![2]) }; } else { let regTest: RegExp | undefined = undefined; try { regTest = RegExp(attributesKey); } catch (e) { // The user entered an invalid regular expression. } if (regTest) { key = regTest; } } } if (!key) { continue; } attributes.push({ key: key, elevateIfNeeded: setting.elevateIfNeeded, onAutoForward: setting.onAutoForward, label: setting.label, requireLocalPort: setting.requireLocalPort, protocol: setting.protocol }); } const defaults = <any>this.configurationService.getValue(PortsAttributes.DEFAULTS); if (defaults) { this.defaultPortAttributes = { elevateIfNeeded: defaults.elevateIfNeeded, label: defaults.label, onAutoForward: defaults.onAutoForward, requireLocalPort: defaults.requireLocalPort, protocol: defaults.protocol }; } return this.sortAttributes(attributes); } private sortAttributes(attributes: PortAttributes[]): PortAttributes[] { function getVal(item: PortAttributes, thisRef: PortsAttributes) { if (isNumber(item.key)) { return item.key; } else if (thisRef.hasStartEnd(item.key)) { return item.key.start; } else if (thisRef.hasHostAndPort(item.key)) { return item.key.port; } else { return Number.MAX_VALUE; } } return attributes.sort((a, b) => { return getVal(a, this) - getVal(b, this); }); } private getOtherAttributes() { return this.defaultPortAttributes; } static providedActionToAction(providedAction: ProvidedOnAutoForward | undefined) { switch (providedAction) { case ProvidedOnAutoForward.Notify: return OnPortForward.Notify; case ProvidedOnAutoForward.OpenBrowser: return OnPortForward.OpenBrowser; case ProvidedOnAutoForward.OpenBrowserOnce: return OnPortForward.OpenBrowserOnce; case ProvidedOnAutoForward.OpenPreview: return OnPortForward.OpenPreview; case ProvidedOnAutoForward.Silent: return OnPortForward.Silent; case ProvidedOnAutoForward.Ignore: return OnPortForward.Ignore; default: return undefined; } } public async addAttributes(port: number, attributes: Partial<Attributes>, target: ConfigurationTarget) { let settingValue = this.configurationService.inspect(PortsAttributes.SETTING); const remoteValue: any = settingValue.userRemoteValue; let newRemoteValue: any; if (!remoteValue || !isObject(remoteValue)) { newRemoteValue = {}; } else { newRemoteValue = deepClone(remoteValue); } if (!newRemoteValue[`${port}`]) { newRemoteValue[`${port}`] = {}; } for (const attribute in attributes) { newRemoteValue[`${port}`][attribute] = (<any>attributes)[attribute]; } return this.configurationService.updateValue(PortsAttributes.SETTING, newRemoteValue, target); } } const MISMATCH_LOCAL_PORT_COOLDOWN = 10 * 1000; // 10 seconds export class TunnelModel extends Disposable { readonly forwarded: Map<string, Tunnel>; private readonly inProgress: Map<string, true> = new Map(); readonly detected: Map<string, Tunnel>; private remoteTunnels: Map<string, RemoteTunnel>; private _onForwardPort: Emitter<Tunnel | void> = new Emitter(); public onForwardPort: Event<Tunnel | void> = this._onForwardPort.event; private _onClosePort: Emitter<{ host: string; port: number }> = new Emitter(); public onClosePort: Event<{ host: string; port: number }> = this._onClosePort.event; private _onPortName: Emitter<{ host: string; port: number }> = new Emitter(); public onPortName: Event<{ host: string; port: number }> = this._onPortName.event; private _candidates: Map<string, CandidatePort> | undefined; private _onCandidatesChanged: Emitter<Map<string, { host: string; port: number }>> = new Emitter(); // onCandidateChanged returns the removed candidates public onCandidatesChanged: Event<Map<string, { host: string; port: number }>> = this._onCandidatesChanged.event; private _candidateFilter: ((candidates: CandidatePort[]) => Promise<CandidatePort[]>) | undefined; private tunnelRestoreValue: Promise<string | undefined>; private _onEnvironmentTunnelsSet: Emitter<void> = new Emitter(); public onEnvironmentTunnelsSet: Event<void> = this._onEnvironmentTunnelsSet.event; private _environmentTunnelsSet: boolean = false; public readonly configPortsAttributes: PortsAttributes; private restoreListener: IDisposable | undefined; private knownPortsRestoreValue: string | undefined; private portAttributesProviders: PortAttributesProvider[] = []; constructor( @ITunnelService private readonly tunnelService: ITunnelService, @IStorageService private readonly storageService: IStorageService, @IConfigurationService private readonly configurationService: IConfigurationService, @IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService, @IRemoteAuthorityResolverService private readonly remoteAuthorityResolverService: IRemoteAuthorityResolverService, @IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService, @ILogService private readonly logService: ILogService, @IDialogService private readonly dialogService: IDialogService ) { super(); this.configPortsAttributes = new PortsAttributes(configurationService); this.tunnelRestoreValue = this.getTunnelRestoreValue(); this._register(this.configPortsAttributes.onDidChangeAttributes(this.updateAttributes, this)); this.forwarded = new Map(); this.remoteTunnels = new Map(); this.tunnelService.tunnels.then(async (tunnels) => { const attributes = await this.getAttributes(tunnels.map(tunnel => { return { port: tunnel.tunnelRemotePort, host: tunnel.tunnelRemoteHost }; })); for (const tunnel of tunnels) { if (tunnel.localAddress) { const key = makeAddress(tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort); const matchingCandidate = mapHasAddressLocalhostOrAllInterfaces(this._candidates ?? new Map(), tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort); this.forwarded.set(key, { remotePort: tunnel.tunnelRemotePort, remoteHost: tunnel.tunnelRemoteHost, localAddress: tunnel.localAddress, protocol: attributes?.get(tunnel.tunnelRemotePort)?.protocol ?? TunnelProtocol.Http, localUri: await this.makeLocalUri(tunnel.localAddress, attributes?.get(tunnel.tunnelRemotePort)), localPort: tunnel.tunnelLocalPort, runningProcess: matchingCandidate?.detail, hasRunningProcess: !!matchingCandidate, pid: matchingCandidate?.pid, privacy: tunnel.privacy, source: UserTunnelSource, }); this.remoteTunnels.set(key, tunnel); } } }); this.detected = new Map(); this._register(this.tunnelService.onTunnelOpened(async (tunnel) => { const key = makeAddress(tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort); if (!mapHasAddressLocalhostOrAllInterfaces(this.forwarded, tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort) && !mapHasAddressLocalhostOrAllInterfaces(this.inProgress, tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort) && tunnel.localAddress) { const matchingCandidate = mapHasAddressLocalhostOrAllInterfaces(this._candidates ?? new Map(), tunnel.tunnelRemoteHost, tunnel.tunnelRemotePort); const attributes = (await this.getAttributes([{ port: tunnel.tunnelRemotePort, host: tunnel.tunnelRemoteHost }]))?.get(tunnel.tunnelRemotePort); this.forwarded.set(key, { remoteHost: tunnel.tunnelRemoteHost, remotePort: tunnel.tunnelRemotePort, localAddress: tunnel.localAddress, protocol: attributes?.protocol ?? TunnelProtocol.Http, localUri: await this.makeLocalUri(tunnel.localAddress, attributes), localPort: tunnel.tunnelLocalPort, closeable: true, runningProcess: matchingCandidate?.detail, hasRunningProcess: !!matchingCandidate, pid: matchingCandidate?.pid, privacy: tunnel.privacy, source: UserTunnelSource, }); } await this.storeForwarded(); this.remoteTunnels.set(key, tunnel); this._onForwardPort.fire(this.forwarded.get(key)!); })); this._register(this.tunnelService.onTunnelClosed(address => { return this.onTunnelClosed(address); })); } private async onTunnelClosed(address: { host: string; port: number }) { const key = makeAddress(address.host, address.port); if (this.forwarded.has(key)) { this.forwarded.delete(key); await this.storeForwarded(); this._onClosePort.fire(address); } } private makeLocalUri(localAddress: string, attributes?: Attributes) { if (localAddress.startsWith('http')) { return URI.parse(localAddress); } const protocol = attributes?.protocol ?? 'http'; return URI.parse(`${protocol}://${localAddress}`); } private async getStorageKey(): Promise<string> { const workspace = this.workspaceContextService.getWorkspace(); const workspaceHash = workspace.configuration ? hash(workspace.configuration.path) : (workspace.folders.length > 0 ? hash(workspace.folders[0].uri.path) : undefined); return `${TUNNELS_TO_RESTORE}.${this.environmentService.remoteAuthority}.${workspaceHash}`; } private async getTunnelRestoreValue(): Promise<string | undefined> { const deprecatedValue = this.storageService.get(TUNNELS_TO_RESTORE, StorageScope.WORKSPACE); if (deprecatedValue) { this.storageService.remove(TUNNELS_TO_RESTORE, StorageScope.WORKSPACE); await this.storeForwarded(); return deprecatedValue; } return this.storageService.get(await this.getStorageKey(), StorageScope.GLOBAL); } async restoreForwarded() { if (this.configurationService.getValue('remote.restoreForwardedPorts')) { const tunnelRestoreValue = await this.tunnelRestoreValue; if (tunnelRestoreValue && (tunnelRestoreValue !== this.knownPortsRestoreValue)) { const tunnels = <Tunnel[] | undefined>JSON.parse(tunnelRestoreValue) ?? []; this.logService.trace(`ForwardedPorts: (TunnelModel) restoring ports ${tunnels.map(tunnel => tunnel.remotePort).join(', ')}`); for (let tunnel of tunnels) { if (!mapHasAddressLocalhostOrAllInterfaces(this.detected, tunnel.remoteHost, tunnel.remotePort)) { await this.forward({ remote: { host: tunnel.remoteHost, port: tunnel.remotePort }, local: tunnel.localPort, name: tunnel.name, privacy: tunnel.privacy, elevateIfNeeded: true }); } } } } if (!this.restoreListener) { // It's possible that at restore time the value hasn't synced. const key = await this.getStorageKey(); this.restoreListener = this._register(this.storageService.onDidChangeValue(async (e) => { if (e.key === key) { this.tunnelRestoreValue = Promise.resolve(this.storageService.get(await this.getStorageKey(), StorageScope.GLOBAL)); await this.restoreForwarded(); } })); } } private async storeForwarded() { if (this.configurationService.getValue('remote.restoreForwardedPorts')) { const valueToStore = JSON.stringify(Array.from(this.forwarded.values()).filter(value => value.source.source === TunnelSource.User)); if (valueToStore !== this.knownPortsRestoreValue) { this.knownPortsRestoreValue = valueToStore; this.storageService.store(await this.getStorageKey(), this.knownPortsRestoreValue, StorageScope.GLOBAL, StorageTarget.USER); } } } private mismatchCooldown = new Date(); private async showPortMismatchModalIfNeeded(tunnel: RemoteTunnel, expectedLocal: number, attributes: Attributes | undefined) { if (!tunnel.tunnelLocalPort || !attributes?.requireLocalPort) { return; } if (tunnel.tunnelLocalPort === expectedLocal) { return; } const newCooldown = new Date(); if ((this.mismatchCooldown.getTime() + MISMATCH_LOCAL_PORT_COOLDOWN) > newCooldown.getTime()) { return; } this.mismatchCooldown = newCooldown; const mismatchString = nls.localize('remote.localPortMismatch.single', "Local port {0} could not be used for forwarding to remote port {1}.\n\nThis usually happens when there is already another process using local port {0}.\n\nPort number {2} has been used instead.", expectedLocal, tunnel.tunnelRemotePort, tunnel.tunnelLocalPort); return this.dialogService.show(Severity.Info, mismatchString); } async forward(tunnelProperties: TunnelProperties, attributes?: Attributes | null): Promise<RemoteTunnel | void> { const existingTunnel = mapHasAddressLocalhostOrAllInterfaces(this.forwarded, tunnelProperties.remote.host, tunnelProperties.remote.port); attributes = attributes ?? ((attributes !== null) ? (await this.getAttributes([tunnelProperties.remote]))?.get(tunnelProperties.remote.port) : undefined); const localPort = (tunnelProperties.local !== undefined) ? tunnelProperties.local : tunnelProperties.remote.port; if (!existingTunnel) { const authority = this.environmentService.remoteAuthority; const addressProvider: IAddressProvider | undefined = authority ? { getAddress: async () => { return (await this.remoteAuthorityResolverService.resolveAuthority(authority)).authority; } } : undefined; const key = makeAddress(tunnelProperties.remote.host, tunnelProperties.remote.port); this.inProgress.set(key, true); const tunnel = await this.tunnelService.openTunnel(addressProvider, tunnelProperties.remote.host, tunnelProperties.remote.port, localPort, (!tunnelProperties.elevateIfNeeded) ? attributes?.elevateIfNeeded : tunnelProperties.elevateIfNeeded, tunnelProperties.privacy, attributes?.protocol); if (tunnel && tunnel.localAddress) { const matchingCandidate = mapHasAddressLocalhostOrAllInterfaces<CandidatePort>(this._candidates ?? new Map(), tunnelProperties.remote.host, tunnelProperties.remote.port); const protocol = (tunnel.protocol ? ((tunnel.protocol === TunnelProtocol.Https) ? TunnelProtocol.Https : TunnelProtocol.Http) : (attributes?.protocol ?? TunnelProtocol.Http)); const newForward: Tunnel = { remoteHost: tunnel.tunnelRemoteHost, remotePort: tunnel.tunnelRemotePort, localPort: tunnel.tunnelLocalPort, name: attributes?.label ?? tunnelProperties.name, closeable: true, localAddress: tunnel.localAddress, protocol, localUri: await this.makeLocalUri(tunnel.localAddress, attributes), runningProcess: matchingCandidate?.detail, hasRunningProcess: !!matchingCandidate, pid: matchingCandidate?.pid, source: tunnelProperties.source ?? UserTunnelSource, privacy: tunnel.privacy, }; this.forwarded.set(key, newForward); this.remoteTunnels.set(key, tunnel); this.inProgress.delete(key); await this.storeForwarded(); await this.showPortMismatchModalIfNeeded(tunnel, localPort, attributes); this._onForwardPort.fire(newForward); return tunnel; } } else { const newName = attributes?.label ?? tunnelProperties.name; if (newName !== existingTunnel.name) { existingTunnel.name = newName; this._onForwardPort.fire(); } if ((attributes?.protocol || (existingTunnel.protocol !== TunnelProtocol.Http)) && (attributes?.protocol !== existingTunnel.protocol)) { await this.close(existingTunnel.remoteHost, existingTunnel.remotePort); tunnelProperties.source = existingTunnel.source; await this.forward(tunnelProperties, attributes); } return mapHasAddressLocalhostOrAllInterfaces(this.remoteTunnels, tunnelProperties.remote.host, tunnelProperties.remote.port); } } async name(host: string, port: number, name: string) { const existingForwarded = mapHasAddressLocalhostOrAllInterfaces(this.forwarded, host, port); const key = makeAddress(host, port); if (existingForwarded) { existingForwarded.name = name; await this.storeForwarded(); this._onPortName.fire({ host, port }); return; } else if (this.detected.has(key)) { this.detected.get(key)!.name = name; this._onPortName.fire({ host, port }); } } async close(host: string, port: number): Promise<void> { await this.tunnelService.closeTunnel(host, port); return this.onTunnelClosed({ host, port }); } address(host: string, port: number): string | undefined { const key = makeAddress(host, port); return (this.forwarded.get(key) || this.detected.get(key))?.localAddress; } public get environmentTunnelsSet(): boolean { return this._environmentTunnelsSet; } addEnvironmentTunnels(tunnels: TunnelDescription[] | undefined): void { if (tunnels) { for (const tunnel of tunnels) { const matchingCandidate = mapHasAddressLocalhostOrAllInterfaces(this._candidates ?? new Map(), tunnel.remoteAddress.host, tunnel.remoteAddress.port); const localAddress = typeof tunnel.localAddress === 'string' ? tunnel.localAddress : makeAddress(tunnel.localAddress.host, tunnel.localAddress.port); this.detected.set(makeAddress(tunnel.remoteAddress.host, tunnel.remoteAddress.port), { remoteHost: tunnel.remoteAddress.host, remotePort: tunnel.remoteAddress.port, localAddress: localAddress, protocol: TunnelProtocol.Http, localUri: this.makeLocalUri(localAddress), closeable: false, runningProcess: matchingCandidate?.detail, hasRunningProcess: !!matchingCandidate, pid: matchingCandidate?.pid, privacy: TunnelPrivacyId.ConstantPrivate, source: { source: TunnelSource.Extension, description: nls.localize('tunnel.staticallyForwarded', "Statically Forwarded") } }); } } this._environmentTunnelsSet = true; this._onEnvironmentTunnelsSet.fire(); this._onForwardPort.fire(); } setCandidateFilter(filter: ((candidates: CandidatePort[]) => Promise<CandidatePort[]>) | undefined): void { this._candidateFilter = filter; } async setCandidates(candidates: CandidatePort[]) { let processedCandidates = candidates; if (this._candidateFilter) { // When an extension provides a filter, we do the filtering on the extension host before the candidates are set here. // However, when the filter doesn't come from an extension we filter here. processedCandidates = await this._candidateFilter(candidates); } const removedCandidates = this.updateInResponseToCandidates(processedCandidates); this.logService.trace(`ForwardedPorts: (TunnelModel) removed candidates ${Array.from(removedCandidates.values()).map(candidate => candidate.port).join(', ')}`); this._onCandidatesChanged.fire(removedCandidates); } // Returns removed candidates private updateInResponseToCandidates(candidates: CandidatePort[]): Map<string, { host: string; port: number }> { const removedCandidates = this._candidates ?? new Map(); const candidatesMap = new Map(); this._candidates = candidatesMap; candidates.forEach(value => { const addressKey = makeAddress(value.host, value.port); candidatesMap.set(addressKey, { host: value.host, port: value.port, detail: value.detail, pid: value.pid }); if (removedCandidates.has(addressKey)) { removedCandidates.delete(addressKey); } const forwardedValue = mapHasAddressLocalhostOrAllInterfaces(this.forwarded, value.host, value.port); if (forwardedValue) { forwardedValue.runningProcess = value.detail; forwardedValue.hasRunningProcess = true; forwardedValue.pid = value.pid; } }); removedCandidates.forEach((_value, key) => { const parsedAddress = parseAddress(key); if (!parsedAddress) { return; } const forwardedValue = mapHasAddressLocalhostOrAllInterfaces(this.forwarded, parsedAddress.host, parsedAddress.port); if (forwardedValue) { forwardedValue.runningProcess = undefined; forwardedValue.hasRunningProcess = false; forwardedValue.pid = undefined; } const detectedValue = mapHasAddressLocalhostOrAllInterfaces(this.detected, parsedAddress.host, parsedAddress.port); if (detectedValue) { detectedValue.runningProcess = undefined; detectedValue.hasRunningProcess = false; detectedValue.pid = undefined; } }); return removedCandidates; } get candidates(): CandidatePort[] { return this._candidates ? Array.from(this._candidates.values()) : []; } get candidatesOrUndefined(): CandidatePort[] | undefined { return this._candidates ? this.candidates : undefined; } private async updateAttributes() { // If the label changes in the attributes, we should update it. const tunnels = Array.from(this.forwarded.values()); const allAttributes = await this.getAttributes(tunnels.map(tunnel => { return { port: tunnel.remotePort, host: tunnel.remoteHost }; }), false); if (!allAttributes) { return; } for (const forwarded of tunnels) { const attributes = allAttributes.get(forwarded.remotePort); if ((attributes?.protocol || (forwarded.protocol !== TunnelProtocol.Http)) && (attributes?.protocol !== forwarded.protocol)) { await this.forward({ remote: { host: forwarded.remoteHost, port: forwarded.remotePort }, local: forwarded.localPort, name: forwarded.name, source: forwarded.source }, attributes); } if (!attributes) { continue; } if (attributes.label && attributes.label !== forwarded.name) { await this.name(forwarded.remoteHost, forwarded.remotePort, attributes.label); } } } async getAttributes(forwardedPorts: { host: string; port: number }[], checkProviders: boolean = true): Promise<Map<number, Attributes> | undefined> { const matchingCandidates: Map<number, CandidatePort> = new Map(); const pidToPortsMapping: Map<number | undefined, number[]> = new Map(); forwardedPorts.forEach(forwardedPort => { const matchingCandidate = mapHasAddressLocalhostOrAllInterfaces<CandidatePort>(this._candidates ?? new Map(), LOCALHOST_ADDRESSES[0], forwardedPort.port); if (matchingCandidate) { matchingCandidates.set(forwardedPort.port, matchingCandidate); if (!pidToPortsMapping.has(matchingCandidate.pid)) { pidToPortsMapping.set(matchingCandidate.pid, []); } pidToPortsMapping.get(matchingCandidate.pid)?.push(forwardedPort.port); } }); const configAttributes: Map<number, Attributes> = new Map(); forwardedPorts.forEach(forwardedPort => { const attributes = this.configPortsAttributes.getAttributes(forwardedPort.port, forwardedPort.host, matchingCandidates.get(forwardedPort.port)?.detail); if (attributes) { configAttributes.set(forwardedPort.port, attributes); } }); if ((this.portAttributesProviders.length === 0) || !checkProviders) { return (configAttributes.size > 0) ? configAttributes : undefined; } // Group calls to provide attributes by pid. const allProviderResults = await Promise.all(flatten(this.portAttributesProviders.map(provider => { return Array.from(pidToPortsMapping.entries()).map(entry => { const portGroup = entry[1]; const matchingCandidate = matchingCandidates.get(portGroup[0]); return provider.providePortAttributes(portGroup, matchingCandidate?.pid, matchingCandidate?.detail, new CancellationTokenSource().token); }); }))); const providedAttributes: Map<number, ProvidedPortAttributes> = new Map(); allProviderResults.forEach(attributes => attributes.forEach(attribute => { if (attribute) { providedAttributes.set(attribute.port, attribute); } })); if (!configAttributes && !providedAttributes) { return undefined; } // Merge. The config wins. const mergedAttributes: Map<number, Attributes> = new Map(); forwardedPorts.forEach(forwardedPorts => { const config = configAttributes.get(forwardedPorts.port); const provider = providedAttributes.get(forwardedPorts.port); mergedAttributes.set(forwardedPorts.port, { elevateIfNeeded: config?.elevateIfNeeded, label: config?.label, onAutoForward: config?.onAutoForward ?? PortsAttributes.providedActionToAction(provider?.autoForwardAction), requireLocalPort: config?.requireLocalPort, protocol: config?.protocol }); }); return mergedAttributes; } addAttributesProvider(provider: PortAttributesProvider) { this.portAttributesProviders.push(provider); } } export interface CandidatePort { host: string; port: number; detail?: string; pid?: number; } export interface IRemoteExplorerService { readonly _serviceBrand: undefined; onDidChangeTargetType: Event<string[]>; targetType: string[]; readonly tunnelModel: TunnelModel; onDidChangeEditable: Event<{ tunnel: ITunnelItem; editId: TunnelEditId } | undefined>; setEditable(tunnelItem: ITunnelItem | undefined, editId: TunnelEditId, data: IEditableData | null): void; getEditableData(tunnelItem: ITunnelItem | undefined, editId?: TunnelEditId): IEditableData | undefined; forward(tunnelProperties: TunnelProperties, attributes?: Attributes | null): Promise<RemoteTunnel | void>; close(remote: { host: string; port: number }): Promise<void>; setTunnelInformation(tunnelInformation: TunnelInformation | undefined): void; setCandidateFilter(filter: ((candidates: CandidatePort[]) => Promise<CandidatePort[]>) | undefined): IDisposable; onFoundNewCandidates(candidates: CandidatePort[]): void; restore(): Promise<void>; enablePortsFeatures(): void; onEnabledPortsFeatures: Event<void>; portsFeaturesEnabled: boolean; readonly namedProcesses: Map<number, string>; } class RemoteExplorerService implements IRemoteExplorerService { public _serviceBrand: undefined; private _targetType: string[] = []; private readonly _onDidChangeTargetType: Emitter<string[]> = new Emitter<string[]>(); public readonly onDidChangeTargetType: Event<string[]> = this._onDidChangeTargetType.event; private _tunnelModel: TunnelModel; private _editable: { tunnelItem: ITunnelItem | undefined; editId: TunnelEditId; data: IEditableData } | undefined; private readonly _onDidChangeEditable: Emitter<{ tunnel: ITunnelItem; editId: TunnelEditId } | undefined> = new Emitter(); public readonly onDidChangeEditable: Event<{ tunnel: ITunnelItem; editId: TunnelEditId } | undefined> = this._onDidChangeEditable.event; private readonly _onEnabledPortsFeatures: Emitter<void> = new Emitter(); public readonly onEnabledPortsFeatures: Event<void> = this._onEnabledPortsFeatures.event; private _portsFeaturesEnabled: boolean = false; public readonly namedProcesses = new Map<number, string>(); constructor( @IStorageService private readonly storageService: IStorageService, @ITunnelService private readonly tunnelService: ITunnelService, @IConfigurationService configurationService: IConfigurationService, @IWorkbenchEnvironmentService environmentService: IWorkbenchEnvironmentService, @IRemoteAuthorityResolverService remoteAuthorityResolverService: IRemoteAuthorityResolverService, @IWorkspaceContextService workspaceContextService: IWorkspaceContextService, @ILogService logService: ILogService, @IDialogService dialogService: IDialogService ) { this._tunnelModel = new TunnelModel(tunnelService, storageService, configurationService, environmentService, remoteAuthorityResolverService, workspaceContextService, logService, dialogService); } set targetType(name: string[]) { // Can just compare the first element of the array since there are no target overlaps const current: string = this._targetType.length > 0 ? this._targetType[0] : ''; const newName: string = name.length > 0 ? name[0] : ''; if (current !== newName) { this._targetType = name; this.storageService.store(REMOTE_EXPLORER_TYPE_KEY, this._targetType.toString(), StorageScope.WORKSPACE, StorageTarget.USER); this.storageService.store(REMOTE_EXPLORER_TYPE_KEY, this._targetType.toString(), StorageScope.GLOBAL, StorageTarget.USER); this._onDidChangeTargetType.fire(this._targetType); } } get targetType(): string[] { return this._targetType; } get tunnelModel(): TunnelModel { return this._tunnelModel; } forward(tunnelProperties: TunnelProperties, attributes?: Attributes | null): Promise<RemoteTunnel | void> { return this.tunnelModel.forward(tunnelProperties, attributes); } close(remote: { host: string; port: number }): Promise<void> { return this.tunnelModel.close(remote.host, remote.port); } setTunnelInformation(tunnelInformation: TunnelInformation | undefined): void { if (tunnelInformation?.features) { this.tunnelService.setTunnelFeatures(tunnelInformation.features); } this.tunnelModel.addEnvironmentTunnels(tunnelInformation?.environmentTunnels); } setEditable(tunnelItem: ITunnelItem | undefined, editId: TunnelEditId, data: IEditableData | null): void { if (!data) { this._editable = undefined; } else { this._editable = { tunnelItem, data, editId }; } this._onDidChangeEditable.fire(tunnelItem ? { tunnel: tunnelItem, editId } : undefined); } getEditableData(tunnelItem: ITunnelItem | undefined, editId: TunnelEditId): IEditableData | undefined { return (this._editable && ((!tunnelItem && (tunnelItem === this._editable.tunnelItem)) || (tunnelItem && (this._editable.tunnelItem?.remotePort === tunnelItem.remotePort) && (this._editable.tunnelItem.remoteHost === tunnelItem.remoteHost) && (this._editable.editId === editId)))) ? this._editable.data : undefined; } setCandidateFilter(filter: (candidates: CandidatePort[]) => Promise<CandidatePort[]>): IDisposable { if (!filter) { return { dispose: () => { } }; } this.tunnelModel.setCandidateFilter(filter); return { dispose: () => { this.tunnelModel.setCandidateFilter(undefined); } }; } onFoundNewCandidates(candidates: CandidatePort[]): void { this.tunnelModel.setCandidates(candidates); } restore(): Promise<void> { return this.tunnelModel.restoreForwarded(); } enablePortsFeatures(): void { this._portsFeaturesEnabled = true; this._onEnabledPortsFeatures.fire(); } get portsFeaturesEnabled(): boolean { return this._portsFeaturesEnabled; } } registerSingleton(IRemoteExplorerService, RemoteExplorerService, true);
the_stack
import { PaginatedMessage } from '@sapphire/discord.js-utilities'; import { exec } from 'child_process'; import crypto from 'crypto'; import { Channel, Client, DMChannel, Guild, MessageButton, MessageOptions, TextChannel } from 'discord.js'; import { objectEntries, randArrItem, randInt, round, shuffleArr, Time } from 'e'; import { KlasaClient, KlasaMessage, KlasaUser, SettingsFolder, SettingsUpdateResults, util } from 'klasa'; import murmurHash from 'murmurhash'; import { Bank } from 'oldschooljs'; import { ItemBank } from 'oldschooljs/dist/meta/types'; import Items from 'oldschooljs/dist/structures/Items'; import { bool, integer, nodeCrypto, real } from 'random-js'; import { promisify } from 'util'; import { CENA_CHARS, continuationChars, Events, PerkTier, skillEmoji, SupportServer } from './constants'; import { GearSetupType, GearSetupTypes } from './gear/types'; import { Consumable } from './minions/types'; import { ArrayItemsResolved, Skills } from './types'; import { GroupMonsterActivityTaskOptions, RaidsOptions } from './types/minions'; import getUsersPerkTier from './util/getUsersPerkTier'; import itemID from './util/itemID'; import resolveItems from './util/resolveItems'; // eslint-disable-next-line @typescript-eslint/no-var-requires const emojiRegex = require('emoji-regex'); export { Util } from 'discord.js'; export * from 'oldschooljs/dist/util/index'; const zeroWidthSpace = '\u200b'; export function cleanMentions(guild: Guild | null, input: string, showAt = true) { const at = showAt ? '@' : ''; return input .replace(/@(here|everyone)/g, `@${zeroWidthSpace}$1`) .replace(/<(@[!&]?|#)(\d{17,19})>/g, (match, type, id) => { switch (type) { case '@': case '@!': { const tag = guild?.client.users.cache.get(id); return tag ? `${at}${tag.username}` : `<${type}${zeroWidthSpace}${id}>`; } case '@&': { const role = guild?.roles.cache.get(id); return role ? `${at}${role.name}` : match; } case '#': { const channel = guild?.channels.cache.get(id); return channel ? `#${channel.name}` : `<${type}${zeroWidthSpace}${id}>`; } default: return `<${type}${zeroWidthSpace}${id}>`; } }); } export function generateHexColorForCashStack(coins: number) { if (coins > 9_999_999) { return '#00FF80'; } if (coins > 99_999) { return '#FFFFFF'; } return '#FFFF00'; } export function formatItemStackQuantity(quantity: number) { if (quantity > 9_999_999) { return `${Math.floor(quantity / 1_000_000)}M`; } else if (quantity > 99_999) { return `${Math.floor(quantity / 1000)}K`; } return quantity.toString(); } export function toTitleCase(str: string) { const splitStr = str.toLowerCase().split(' '); for (let i = 0; i < splitStr.length; i++) { splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1); } return splitStr.join(' '); } export function cleanString(str: string) { return str.replace(/[^0-9a-zA-Z+]/gi, '').toUpperCase(); } export function stringMatches(str: string, str2: string) { return cleanString(str) === cleanString(str2); } export function formatDuration(ms: number, short = false) { if (ms < 0) ms = -ms; const time = { day: Math.floor(ms / 86_400_000), hour: Math.floor(ms / 3_600_000) % 24, minute: Math.floor(ms / 60_000) % 60, second: Math.floor(ms / 1000) % 60 }; const shortTime = { d: Math.floor(ms / 86_400_000), h: Math.floor(ms / 3_600_000) % 24, m: Math.floor(ms / 60_000) % 60, s: Math.floor(ms / 1000) % 60 }; let nums = Object.entries(short ? shortTime : time).filter(val => val[1] !== 0); if (nums.length === 0) return '1 second'; return nums .map(([key, val]) => `${val}${short ? '' : ' '}${key}${val === 1 || short ? '' : 's'}`) .join(short ? '' : ', '); } export function inlineCodeblock(input: string) { return `\`${input.replace(/ /g, '\u00A0').replace(/`/g, '`\u200B')}\``; } export function isWeekend() { const currentDate = new Date(Date.now() - Time.Hour * 6); return [6, 0].includes(currentDate.getDay()); } export function saidYes(content: string) { const newContent = content.toLowerCase(); return newContent === 'y' || newContent === 'yes'; } export function convertXPtoLVL(xp: number, cap = 99) { let points = 0; for (let lvl = 1; lvl <= cap; lvl++) { points += Math.floor(lvl + 300 * Math.pow(2, lvl / 7)); if (Math.floor(points / 4) >= xp + 1) { return lvl; } } return cap; } export function determineScaledOreTime(xp: number, respawnTime: number, lvl: number) { const t = xp / (lvl / 4 + 0.5) + ((100 - lvl) / 100 + 0.75); return Math.floor((t + respawnTime) * 1000) * 1.2; } export function determineScaledLogTime(xp: number, respawnTime: number, lvl: number) { const t = xp / (lvl / 4 + 0.5) + ((100 - lvl) / 100 + 0.75); return Math.floor((t + respawnTime) * 1000) * 1.2; } export function rand(min: number, max: number) { return integer(min, max)(nodeCrypto); } export function randFloat(min: number, max: number) { return real(min, max)(nodeCrypto); } export function percentChance(percent: number) { return bool(percent / 100)(nodeCrypto); } export function roll(max: number) { return rand(1, max) === 1; } export function itemNameFromID(itemID: number | string) { return Items.get(itemID)?.name; } export function floatPromise(ctx: { client: Client }, promise: Promise<unknown>) { if (util.isThenable(promise)) promise.catch(error => ctx.client.emit(Events.Wtf, error)); } export async function arrIDToUsers(client: KlasaClient, ids: string[]) { return Promise.all(ids.map(id => client.fetchUser(id))); } const rawEmojiRegex = emojiRegex(); export function stripEmojis(str: string) { return str.replace(rawEmojiRegex, ''); } export const anglerBoosts = [ [itemID('Angler hat'), 0.4], [itemID('Angler top'), 0.8], [itemID('Angler waders'), 0.6], [itemID('Angler boots'), 0.2] ]; export function anglerBoostPercent(user: KlasaUser) { const skillingSetup = user.getGear('skilling'); let amountEquipped = 0; let boostPercent = 0; for (const [id, percent] of anglerBoosts) { if (skillingSetup.hasEquipped([id])) { boostPercent += percent; amountEquipped++; } } if (amountEquipped === 4) { boostPercent += 0.5; } return round(boostPercent, 1); } const rogueOutfit = resolveItems(['Rogue mask', 'Rogue top', 'Rogue trousers', 'Rogue gloves', 'Rogue boots']); export function rogueOutfitPercentBonus(user: KlasaUser): number { const skillingSetup = user.getGear('skilling'); let amountEquipped = 0; for (const id of rogueOutfit) { if (skillingSetup.hasEquipped([id])) { amountEquipped++; } } return amountEquipped * 20; } export function rollRogueOutfitDoubleLoot(user: KlasaUser): boolean { return randInt(1, 100) <= rogueOutfitPercentBonus(user); } export function generateContinuationChar(user: KlasaUser) { const baseChar = user.perkTier > PerkTier.One ? 'y' : Date.now() - user.createdTimestamp < Time.Month * 6 ? shuffleArr(continuationChars).slice(0, randInt(1, 2)).join('') : randArrItem(continuationChars); return `${shuffleArr(CENA_CHARS).slice(0, randInt(1, 2)).join('')}${baseChar}${shuffleArr(CENA_CHARS) .slice(0, randInt(1, 2)) .join('')}`; } export function isValidGearSetup(str: string): str is GearSetupType { return GearSetupTypes.includes(str as any); } /** * Adds random variation to a number. For example, if you pass 10%, it can at most lower the value by 10%, * or increase it by 10%, and everything in between. * @param value The value to add variation too. * @param percentage The max percentage to fluctuate the value by, in both negative/positive. */ export function randomVariation(value: number, percentage: number) { const lowerLimit = value * (1 - percentage / 100); const upperLimit = value * (1 + percentage / 100); return randFloat(lowerLimit, upperLimit); } export function isGroupActivity(data: any): data is GroupMonsterActivityTaskOptions { return 'users' in data; } export function isRaidsActivity(data: any): data is RaidsOptions { return 'challengeMode' in data; } export function sha256Hash(x: string) { return crypto.createHash('sha256').update(x, 'utf8').digest('hex'); } export function countSkillsAtleast99(user: KlasaUser) { const skills = (user.settings.get('skills') as SettingsFolder).toJSON() as Record<string, number>; return Object.values(skills).filter(xp => convertXPtoLVL(xp) >= 99).length; } export function getSupportGuild(client: Client) { const guild = client.guilds.cache.get(SupportServer); if (!guild) throw "Can't find support guild."; return guild; } export function normal(mu = 0, sigma = 1, nsamples = 6) { let run_total = 0; for (let i = 0; i < nsamples; i++) { run_total += Math.random(); } return (sigma * (run_total - nsamples / 2)) / (nsamples / 2) + mu; } /** * Checks if the bot can send a message to a channel object. * @param channel The channel to check if the bot can send a message to. */ export function channelIsSendable(channel: Channel | undefined | null): channel is TextChannel { if (!channel || (!(channel instanceof DMChannel) && !(channel instanceof TextChannel)) || !channel.postable) { return false; } return true; } export function calcCombatLevel(skills: Skills) { const defence = skills.defence ? convertXPtoLVL(skills.defence) : 1; const ranged = skills.ranged ? convertXPtoLVL(skills.ranged) : 1; const hitpoints = skills.hitpoints ? convertXPtoLVL(skills.hitpoints) : 1; const magic = skills.magic ? convertXPtoLVL(skills.magic) : 1; const prayer = skills.prayer ? convertXPtoLVL(skills.prayer) : 1; const attack = skills.attack ? convertXPtoLVL(skills.attack) : 1; const strength = skills.strength ? convertXPtoLVL(skills.strength) : 1; const base = 0.25 * (defence + hitpoints + Math.floor(prayer / 2)); const melee = 0.325 * (attack + strength); const range = 0.325 * (Math.floor(ranged / 2) + ranged); const mage = 0.325 * (Math.floor(magic / 2) + magic); return Math.floor(base + Math.max(melee, range, mage)); } export function skillsMeetRequirements(skills: Skills, requirements: Skills) { for (const [skillName, level] of objectEntries(requirements)) { if ((skillName as string) === 'combat') { if (calcCombatLevel(skills) < level!) return false; } else { const xpHas = skills[skillName]; const levelHas = convertXPtoLVL(xpHas ?? 1); if (levelHas < level!) return false; } } return true; } export function formatItemReqs(items: ArrayItemsResolved) { const str = []; for (const item of items) { if (Array.isArray(item)) { str.push(item.map(itemNameFromID).join(' OR ')); } else { str.push(itemNameFromID(item)); } } return str.join(', '); } export function formatItemCosts(consumable: Consumable, timeToFinish: number) { const str = []; const consumables = [consumable]; if (consumable.alternativeConsumables) { for (const c of consumable.alternativeConsumables) { consumables.push(c); } } for (const c of consumables) { const itemEntries = c.itemCost.items(); const multiple = itemEntries.length > 1; const subStr = []; let multiply = 1; if (c.qtyPerKill) { multiply = c.qtyPerKill; } else if (c.qtyPerMinute) { multiply = c.qtyPerMinute * (timeToFinish / Time.Minute); } for (const [item, quantity] of itemEntries) { subStr.push(`${Number((quantity * multiply).toFixed(3))}x ${item.name}`); } if (multiple) { str.push(subStr.join(', ')); } else { str.push(subStr.join('')); } } if (consumables.length > 1) { return `(${str.join(' OR ')})`; } return str.join(''); } export function formatMissingItems(consumables: Consumable[], timeToFinish: number) { const str = []; for (const consumable of consumables) { str.push(formatItemCosts(consumable, timeToFinish)); } return str.join(', '); } export function formatSkillRequirements(reqs: Record<string, number>, emojis = true) { let arr = []; for (const [name, num] of objectEntries(reqs)) { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore arr.push(`${emojis ? ` ${skillEmoji[name]} ` : ''}**${num}** ${toTitleCase(name)}`); } return arr.join(', '); } export function formatItemBoosts(items: ItemBank[]) { const str = []; for (const itemSet of items) { const itemEntries = Object.entries(itemSet); const multiple = itemEntries.length > 1; const bonusStr = []; for (const [itemID, boostAmount] of itemEntries) { bonusStr.push(`${boostAmount}% for ${itemNameFromID(parseInt(itemID))}`); } if (multiple) { str.push(`(${bonusStr.join(' OR ')})`); } else { str.push(bonusStr.join('')); } } return str.join(', '); } /** * Given a list of items, and a bank, it will return a new bank with all items not * in the filter removed from the bank. * @param itemFilter The array of item IDs to use as the filter. * @param bank The bank to filter items from. */ export function filterBankFromArrayOfItems(itemFilter: number[], bank: ItemBank): ItemBank { const returnBank: ItemBank = {}; const bankKeys = Object.keys(bank); // If there are no items in the filter or bank, just return an empty bank. if (itemFilter.length === 0 || bankKeys.length === 0) return returnBank; // For every item in the filter, if its in the bank, add it to the return bank. for (const itemID of itemFilter) { if (bank[itemID]) returnBank[itemID] = bank[itemID]; } return returnBank; } export function updateBankSetting(client: KlasaClient, setting: string, bankToAdd: Bank | ItemBank) { const current = new Bank(client.settings.get(setting) as ItemBank); const newBank = current.add(bankToAdd); return client.settings.update(setting, newBank.bank); } export function updateGPTrackSetting(client: KlasaClient, setting: string, amount: number) { const current = client.settings.get(setting) as number; const newValue = current + amount; return client.settings.update(setting, newValue); } export function textEffect(str: string, effect: 'none' | 'strikethrough') { let wrap = ''; if (effect === 'strikethrough') { wrap = '~~'; } return `${wrap}${str.replace(/~/g, '')}${wrap}`; } export async function wipeDBArrayByKey(user: KlasaUser, key: string): Promise<SettingsUpdateResults> { const active: any[] = user.settings.get(key) as any[]; return user.settings.update(key, active); } export function isValidNickname(str?: string) { return ( str && typeof str === 'string' && str.length >= 2 && str.length <= 30 && ['\n', '`', '@', '<', ':'].every(char => !str.includes(char)) && stripEmojis(str).length === str.length ); } export function patronMaxTripCalc(user: KlasaUser) { const perkTier = getUsersPerkTier(user); if (perkTier === PerkTier.Two) return Time.Minute * 3; else if (perkTier === PerkTier.Three) return Time.Minute * 6; else if (perkTier >= PerkTier.Four) return Time.Minute * 10; return 0; } export async function makePaginatedMessage(message: KlasaMessage, pages: MessageOptions[]) { const display = new PaginatedMessage(); // @ts-ignore 2445 display.setUpReactions = () => null; for (const page of pages) { display.addPage({ ...page, components: pages.length > 1 ? [ PaginatedMessage.defaultActions .slice(1, -1) .map(a => new MessageButton() .setLabel('') .setStyle('SECONDARY') .setCustomID(a.id) .setEmoji(a.id) ) ] : [] }); } await display.run(message); if (pages.length > 1) { const collector = display.response!.createMessageComponentInteractionCollector({ time: Time.Minute, filter: i => i.user.id === message.author.id }); collector.on('collect', async interaction => { for (const action of PaginatedMessage.defaultActions) { if (interaction.customID === action.id) { const previousIndex = display.index; await action.run({ handler: display, author: message.author, channel: message.channel, response: display.response!, collector: display.collector! }); if (previousIndex !== display.index) { await interaction.update(await display.resolvePage(message.channel, display.index)); return; } } } }); collector.on('end', () => { display.response!.edit({ components: [] }); }); } } export const asyncExec = promisify(exec); export function getUsername(client: KlasaClient, id: string): string { return (client.commands.get('leaderboard') as any)!.getUsername(id); } export function murMurHashChance(input: string, percent: number) { const hash = murmurHash.v3(input) % 1e4; return hash < percent * 100; }
the_stack
import {autorun} from 'mobx'; import {defaultValueByField, IndexedInput, Input, listFieldTypes, ServiceUser, Spec} from '../lib/types'; import {isLitSubtype} from '../lib/utils'; import {LitService} from './lit_service'; /** * Interface for reading/storing app configuration from/to the URL. */ export class UrlConfiguration { selectedTabUpper?: string; selectedTabLower?: string; selectedModels: string[] = []; selectedData: string[] = []; primarySelectedData?: string; /** * For datapoints that are not in the original dataset, the fields * and their values are added directly into the url. * LIT can load multiple examples from the url, but can only share * primary selected example. */ dataFields: {[key: number]: Input} = {}; selectedDataset?: string; hiddenModules: string[] = []; compareExamplesEnabled?: boolean; layoutName?: string; /** Path to load a new dataset from, on pageload. */ newDatasetPath?: string; } /** * Interface describing how AppState is synced to the URL Service */ export interface StateObservedByUrlService { currentModels: string[]; currentDataset: string; setUrlConfiguration: (urlConfiguration: UrlConfiguration) => void; getUrlConfiguration: () => UrlConfiguration; currentDatasetSpec: Spec; compareExamplesEnabled: boolean; layoutName: string; getCurrentInputDataById: (id: string) => IndexedInput | null; annotateNewData: (data: IndexedInput[]) => Promise<IndexedInput[]>; commitNewDatapoints: (datapoints: IndexedInput[]) => void; } /** * Interface describing how the ModulesService is synced to the URL Service */ export interface ModulesObservedByUrlService { hiddenModuleKeys: Set<string>; setUrlConfiguration: (urlConfiguration: UrlConfiguration) => void; selectedTabUpper: string; selectedTabLower: string; } /** * Interface describing how the SelectionService is synced to the URL service */ export interface SelectionObservedByUrlService { readonly primarySelectedId: string|null; readonly primarySelectedInputData: IndexedInput|null; setPrimarySelection: (id: string, user: ServiceUser) => void; readonly selectedIds: string[]; selectIds: (ids: string[], user: ServiceUser) => void; } const SELECTED_TAB_UPPER_KEY = 'upper_tab'; const SELECTED_TAB_LOWER_KEY = 'tab'; const SELECTED_DATA_KEY = 'selection'; const PRIMARY_SELECTED_DATA_KEY = 'primary'; const SELECTED_DATASET_KEY = 'dataset'; const SELECTED_MODELS_KEY = 'models'; const HIDDEN_MODULES_KEY = 'hidden_modules'; const COMPARE_EXAMPLES_ENABLED_KEY = 'compare_data_mode'; const LAYOUT_KEY = 'layout'; const DATA_FIELDS_KEY_SUBSTRING = 'data'; /** Path to load a new dataset from, on pageload. */ const NEW_DATASET_PATH = 'new_dataset_path'; const MAX_IDS_IN_URL_SELECTION = 100; const makeDataFieldKey = (key: string) => `${DATA_FIELDS_KEY_SUBSTRING}_${key}`; const parseDataFieldKey = (key: string) => { // Split string into two from the first underscore, // data{index}_{feature}={val} -> [data{index}, {feature}={val}] const pieces = key.split(/_([^]*)/, 2); const indexStr = pieces[0].replace(DATA_FIELDS_KEY_SUBSTRING, ''); return {fieldKey: pieces[1], dataIndex: +(indexStr || '0')}; }; /** * Singleton service responsible for deserializing / serializing state to / from * a url. */ export class UrlService extends LitService { /** Parse arrays in a url param, filtering out empty strings */ private urlParseArray(encoded: string) { if (encoded == null) { return []; } const array = encoded.split(','); return array.filter(str => str !== ''); } /** Parse a string in a url param, filtering out empty strings */ private urlParseString(encoded: string) { return encoded ? encoded : undefined; } /** Parse a boolean in a url param, if undefined return false */ private urlParseBoolean(encoded: string) { return encoded === 'true'; } /** Parse the data field based on its type */ private parseDataFieldValue(fieldKey: string, encoded: string, spec: Spec) { const fieldSpec = spec[fieldKey]; // If array type, unpack as an array. if (isLitSubtype(fieldSpec, listFieldTypes)) { return this.urlParseArray(encoded); } else { // String-like. return this.urlParseString(encoded) ?? defaultValueByField(fieldKey, spec); } } private getConfigurationFromUrl(): UrlConfiguration { const urlConfiguration = new UrlConfiguration(); const urlSearchParams = new URLSearchParams(window.location.search); for (const [key, value] of urlSearchParams) { if (key === SELECTED_MODELS_KEY) { urlConfiguration.selectedModels = this.urlParseArray(value); } else if (key === SELECTED_DATA_KEY) { urlConfiguration.selectedData = this.urlParseArray(value); } else if (key === PRIMARY_SELECTED_DATA_KEY) { urlConfiguration.primarySelectedData = this.urlParseString(value); } else if (key === SELECTED_DATASET_KEY) { urlConfiguration.selectedDataset = this.urlParseString(value); } else if (key === HIDDEN_MODULES_KEY) { urlConfiguration.hiddenModules = this.urlParseArray(value); } else if (key === COMPARE_EXAMPLES_ENABLED_KEY) { urlConfiguration.compareExamplesEnabled = this.urlParseBoolean(value); } else if (key === SELECTED_TAB_UPPER_KEY) { urlConfiguration.selectedTabUpper = this.urlParseString(value); } else if (key === SELECTED_TAB_LOWER_KEY) { urlConfiguration.selectedTabLower = this.urlParseString(value); } else if (key === LAYOUT_KEY) { urlConfiguration.layoutName = this.urlParseString(value); } else if (key === NEW_DATASET_PATH) { urlConfiguration.newDatasetPath = this.urlParseString(value); } else if (key.startsWith(DATA_FIELDS_KEY_SUBSTRING)) { const {fieldKey, dataIndex}: {fieldKey: string, dataIndex: number} = parseDataFieldKey(key); // TODO(b/179788207) Defer parsing of data keys here as we do not have // access to the input spec of the dataset at the time // this is called. We convert array fields to their proper forms in // syncSelectedDatapointToUrl. if (!(dataIndex in urlConfiguration.dataFields)) { urlConfiguration.dataFields[dataIndex] = {}; } // Warn if an example is overwritten, this only happens if url is // malformed to contain the same index more than once. if (fieldKey in urlConfiguration.dataFields[dataIndex]) { console.log( `Warning, data index ${dataIndex} is set more than once.`); } urlConfiguration.dataFields[dataIndex][fieldKey] = value; } } return urlConfiguration; } /** Set url parameter if it's not empty */ private setUrlParam( params: URLSearchParams, key: string, data: string|string[]) { const value = data instanceof Array ? data.join(',') : data; if (value !== '' && value != null) { params.set(key, value); } } /** * If the datapoint was generated (not in the initial dataset), * set the data values themselves in the url. */ setDataFieldURLParams( params: URLSearchParams, id: string, appState: StateObservedByUrlService) { const data = appState.getCurrentInputDataById(id); if (data !== null && data.meta['added']) { Object.keys(data.data).forEach((key: string) => { this.setUrlParam(params, makeDataFieldKey(key), data.data[key]); }); } } /** * Parse the URL configuration and set it in the services that depend on it * for initializtion. Then, set up an autorun observer to automatically * react to changes of state and sync them to the url query params. */ syncStateToUrl( appState: StateObservedByUrlService, selectionService: SelectionObservedByUrlService, modulesService: ModulesObservedByUrlService) { const urlConfiguration = this.getConfigurationFromUrl(); appState.setUrlConfiguration(urlConfiguration); modulesService.setUrlConfiguration(urlConfiguration); const urlSelectedIds = urlConfiguration.selectedData || []; selectionService.selectIds(urlSelectedIds, this); // TODO(lit-dev) Add compared examples to URL parameters. // Only enable compare example mode if both selections and compare mode // exist in URL. if (selectionService.selectedIds.length > 0 && urlConfiguration.compareExamplesEnabled) { appState.compareExamplesEnabled = true; } autorun(() => { const urlParams = new URLSearchParams(); // Syncing app state this.setUrlParam(urlParams, SELECTED_MODELS_KEY, appState.currentModels); if (selectionService.selectedIds.length <= MAX_IDS_IN_URL_SELECTION) { this.setUrlParam( urlParams, SELECTED_DATA_KEY, selectionService.selectedIds); const id = selectionService.primarySelectedId; if (id != null) { this.setUrlParam(urlParams, PRIMARY_SELECTED_DATA_KEY, id); this.setDataFieldURLParams(urlParams, id, appState); } } this.setUrlParam( urlParams, SELECTED_DATASET_KEY, appState.currentDataset); this.setUrlParam( urlParams, COMPARE_EXAMPLES_ENABLED_KEY, appState.compareExamplesEnabled ? 'true' : 'false'); // Syncing hidden modules this.setUrlParam( urlParams, HIDDEN_MODULES_KEY, [...modulesService.hiddenModuleKeys]); this.setUrlParam(urlParams, LAYOUT_KEY, appState.layoutName); this.setUrlParam( urlParams, SELECTED_TAB_UPPER_KEY, modulesService.selectedTabUpper); this.setUrlParam( urlParams, SELECTED_TAB_LOWER_KEY, modulesService.selectedTabLower); if (urlParams.toString() !== '') { const newUrl = `${window.location.pathname}?${urlParams.toString()}`; window.history.replaceState({}, '', newUrl); } }); } /** * Syncing the selected datapoint in the URL is done separately from * the rest of the URL params. This is for when the selected * datapoint was not part of the original dataset: in this case, we * have to first load the dataset, and then create a new datapoint * from the fields stored in the url, and then select it. */ async syncSelectedDatapointToUrl( appState: StateObservedByUrlService, selectionService: SelectionObservedByUrlService, ) { const urlConfiguration = appState.getUrlConfiguration(); const dataFields = urlConfiguration.dataFields; const dataToAdd = Object.values(dataFields).map((fields: Input) => { // Create a new dict and do not modify the urlConfiguration. This makes // sure that this call works even if initialize app is called multiple // times. const outputFields: Input = {}; const spec = appState.currentDatasetSpec; Object.keys(spec).forEach(key => { outputFields[key] = this.parseDataFieldValue(key, fields[key], spec); }); const datum: IndexedInput = { data: outputFields, id: '', // will be overwritten meta: {source: 'url', added: true}, }; return datum; }); // If there are data fields set in the url, make new datapoints // from them and select all passed data points. // TODO(b/185155960) Allow specifying selection for passed examples in url. if (dataToAdd.length > 0) { const data = await appState.annotateNewData(dataToAdd); appState.commitNewDatapoints(data); selectionService.selectIds(data.map((d) => d.id), this); } // Otherwise, use the primary selected datapoint url param directly. else { const id = urlConfiguration.primarySelectedData; if (id !== undefined) { selectionService.setPrimarySelection(id, this); } } } }
the_stack
import { Injectable } from '@angular/core'; import XRegExp from 'xregexp'; import { AbstractControl, FormGroup, ValidationErrors } from '@angular/forms'; import { Netmask } from 'netmask'; import isIp from 'is-ip'; /** * App imports */ import * as validationMethods from './validation.methods'; import { SimpleValidator, ValidatorEnum } from '../constants/validation.constants'; import { RxwebValidators } from "@rxweb/reactive-form-validators"; /** * @class ValidationService * Base class for shared form validators */ @Injectable() export class ValidationService { simpleValidatorMap: Map<SimpleValidator, (control: AbstractControl) => ValidationErrors>; constructor() { this.simpleValidatorMap = new Map<SimpleValidator, (control: AbstractControl) => any>([ [SimpleValidator.IS_COMMA_SEPARATED_LIST, this.isCommaSeperatedList()], [SimpleValidator.IS_HTTP_OR_HTTPS, this.isHttpOrHttps()], [SimpleValidator.IS_NUMBER_POSITIVE, this.isNumberGreaterThanZero()], [SimpleValidator.IS_NUMERIC_ONLY, this.isNumericOnly()], [SimpleValidator.IS_STRING_WITHOUT_QUERY_PARAMS, this.isStringWithoutQueryParams()], [SimpleValidator.IS_STRING_WITHOUT_URL_FRAGMENT, this.isStringWithoutUrlFragment()], [SimpleValidator.IS_TRUE, this.isTrue()], [SimpleValidator.IS_VALID_CLUSTER_NAME, this.isValidClusterName()], [SimpleValidator.IS_VALID_FQDN, this.isValidFqdn()], [SimpleValidator.IS_VALID_FQDN_OR_IP, this.isValidIpOrFqdn()], [SimpleValidator.IS_VALID_FQDN_OR_IP_HTTPS, this.isValidIpOrFqdnWithHttpsProtocol()], [SimpleValidator.IS_VALID_FQDN_OR_IP_LIST, this.isCommaSeparatedIpsOrFqdn()], [SimpleValidator.IS_VALID_FQDN_OR_IPV6, this.isValidIpv6OrFqdn()], [SimpleValidator.IS_VALID_FQDN_OR_IPV6_HTTPS, this.isValidIpv6OrFqdnWithHttpsProtocol()], [SimpleValidator.IS_VALID_IP, this.isValidIp()], [SimpleValidator.IS_VALID_IP_LIST, this.isValidIps()], [SimpleValidator.IS_VALID_IP_NETWORK_SEGMENT, this.isValidIpNetworkSegment()], [SimpleValidator.IS_VALID_IPV6_NETWORK_SEGMENT, this.isValidIpv6NetworkSegment()], [SimpleValidator.IS_VALID_LABEL_OR_ANNOTATION, this.isValidLabelOrAnnotation()], [SimpleValidator.IS_VALID_PORT, this.isValidPort()], [SimpleValidator.IS_VALID_RESOURCE_GROUP_NAME, this.isValidResourceGroupName()], [SimpleValidator.NO_WHITE_SPACE, this.noWhitespaceOnEnds()], [SimpleValidator.NO_TRAILING_SLASH, this.noTrailingSlash()], [SimpleValidator.RX_UNIQUE, RxwebValidators.unique()], [ SimpleValidator.RX_REQUIRED_IF_VALUE, RxwebValidators.required({conditionalExpression: (x, _) => !!x.value}) ], [SimpleValidator.RX_REQUIRED_IF_KEY, RxwebValidators.required({conditionalExpression: (x, _) => !!x.key})] ]); } getSimpleValidator(requested: SimpleValidator): (control: AbstractControl) => any { return this.simpleValidatorMap.get(requested); } /** * @method isValidIp * NOTE: if string is empty, does not yield error */ isValidIp(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { return validationMethods.isValidIp(ctrlValue) ? null : {[ValidatorEnum.VALID_IP]: true}; } return null; } } /** * @method noWhitespaceOnEnds check if string has leading/trailing whitespsaces */ noWhitespaceOnEnds(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { if (ctrlValue.length !== ctrlValue.toString().trim().length) { return { [ValidatorEnum.WHITESPACE]: true }; } } return null; } } /** * @method noTrailingSlash check if string has trailing slash (IE https://test.net/) */ noTrailingSlash(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { if (ctrlValue.substr(ctrlValue.length - 1) === '/') { return { [ValidatorEnum.TRAILING_SLASH]: true }; } } return null; } } /** * @method isValidIps * NOTE: if string is empty, does not yield error */ isValidIps(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { const ips: Array<string> = ctrlValue.split(','); return ips .map(ipStr => validationMethods.isValidIp(ipStr)) .reduce((a, b) => a && b, true) ? null : {[ValidatorEnum.VALID_IP]: true}; } return null; } } /** * @method isValidFqdn * NOTE: if string is empty, does not yield error */ isValidFqdn(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { return validationMethods.isValidFqdn(ctrlValue) ? null : {[ValidatorEnum.VALID_FQDN]: true}; } return null; } } /** * @method isValidIpOrFqdn validator to check if input is valid IP or FQDN */ isValidIpOrFqdn(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { if (validationMethods.isValidIp(ctrlValue) || validationMethods.isValidFqdn(ctrlValue)) { return null; } return { [ValidatorEnum.VALID_IP_OR_FQDN]: true }; } } } /** * @method isValidIpOrFqdn validator to check if input is valid IP or FQDN */ isValidIpv6OrFqdn(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { if (isIp.v6(ctrlValue) || validationMethods.isValidFqdn(ctrlValue)) { return null; } return { [ValidatorEnum.VALID_IP_OR_FQDN]: true }; } } } /** * @method isValidIpOrFqdnWithProtocol validator to check if input is valid IP or FQDN * with protocol prefix */ isValidIpOrFqdnWithHttpsProtocol(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { if (validationMethods.isValidIpWithHttpsProtocol(ctrlValue) || validationMethods.isValidFqdnWithHttpsProtocol(ctrlValue)) { return null; } return { [ValidatorEnum.VALID_IP_OR_FQDN]: true }; } } } /** * @method isValidIpv6OrFqdnWithHttpsProtocol validator to check if input is valid IP or FQDN * with protocol prefix */ isValidIpv6OrFqdnWithHttpsProtocol(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { if (validationMethods.isValidIpv6WithHttpsProtocol(ctrlValue) || validationMethods.isValidFqdnWithHttpsProtocol(ctrlValue)) { return null; } return { [ValidatorEnum.VALID_IP_OR_FQDN]: true }; } } } /** * @method isStringWithoutUrlFragment validator to check if input includes URL fragment */ isStringWithoutUrlFragment(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { if (validationMethods.isStringWithoutUrlFragment(ctrlValue)) { return { [ValidatorEnum.INCLUDES_URL_FRAGMENT]: true }; } return null; } } } /** * @method isStringWithoutQueryParams validator to check if input includes URL query params */ isStringWithoutQueryParams(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { if (validationMethods.isStringWithoutQueryParams(ctrlValue)) { return { [ValidatorEnum.INCLUDES_QUERY_PARAMS]: true }; } return null; } } } /** * @method isValidPort validator to check if input is valid port */ isValidPort(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { if (validationMethods.isNumericOnly(ctrlValue)) { return null; } return { [ValidatorEnum.VALID_PORT]: true }; } return null; } } /** * @method isValidSubnet validator to check if input subnet is valid * - valid ip * - within subnet mask range */ isValidSubnet(subnetMaskCtrl: AbstractControl): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { if (validationMethods.isValidIp(ctrlValue)) { const ipLong = validationMethods.ipAddrToLong(ctrlValue); const subnetMask = subnetMaskCtrl.value; if (validationMethods.isValidIp(subnetMask)) { const subnetMaskLong = validationMethods.ipAddrToLong(subnetMask); if (validationMethods.subnetMaskInRange(ipLong, subnetMaskLong)) { return null; } return { [ValidatorEnum.SUBNET_IN_RANGE]: true }; } return null; } return { [ValidatorEnum.VALID_IP]: true }; } return null; } } /** * @method isValidClusterName * NOTE: if string start and end with a letter, and can contain only * lowercase letters, numbers, and hyphens. */ isValidClusterName(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { if (ctrlValue.length !== ctrlValue.toString().trim().length) { return { [ValidatorEnum.WHITESPACE]: true }; } return validationMethods.isValidClustername(ctrlValue) ? null : {[ValidatorEnum.VALID_CLUSTER_NAME]: true}; } return null; } } /** * @method isValidLabelOrAnnotation * NOTE: if string start and end with a letter, and can contain only * lowercase letters, numbers, hyphens, underscores, dots, and have * max length of 63. */ isValidLabelOrAnnotation(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { if (ctrlValue.length !== ctrlValue.toString().trim().length) { return { [ValidatorEnum.WHITESPACE]: true }; } if (ctrlValue.length > 63) { return { [ValidatorEnum.MAX_LEN]: true } } return validationMethods.isValidLabelOrAnnotation(ctrlValue) ? null : {[ValidatorEnum.VALID_CLUSTER_NAME]: true}; } return null; } } /** * @method isIpInSubnet validator to check if input is within subnet range * - non-empty * - valid ip * - within subnet range */ isIpInSubnet(subnetCtrl: AbstractControl, subnetMaskCtrl: AbstractControl): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { if (validationMethods.isValidIp(ctrlValue)) { const ipLong = validationMethods.ipAddrToLong(ctrlValue); const subnetMask = subnetMaskCtrl.value; const subnet = subnetCtrl.value; if (validationMethods.isValidIp(subnet) && validationMethods.isValidIp(subnetMask)) { const subnetLong = validationMethods.ipAddrToLong(subnet); const subnetMaskLong = validationMethods.ipAddrToLong(subnetMask); if (validationMethods.isIpInSubnet(ipLong, subnetLong, subnetMaskLong)) { return null; } return { [ValidatorEnum.IP_IN_SUBNET_RANGE]: true }; } return null; } return { [ValidatorEnum.VALID_IP]: true }; } return null; } } /** * @method isIpInSubnet2 validator to check if input is within subnet range * @param cidrControlName the name of the CIDR, assumming format IPv4/length, e.g: 192.167.0.0/16 */ isIpInSubnet2(cidr: string): any { return (control: AbstractControl) => { const ipv4: string = control.value; if (ipv4) { if (validationMethods.isValidIp(ipv4)) { let netmask = null; try { netmask = new Netmask(cidr); } catch (e) { // the netmask may not have been initialized yet, we don't validate return null; } if (!netmask.contains(ipv4)) { return { [ValidatorEnum.IP_IN_SUBNET_RANGE]: true }; } return null; } return { [ValidatorEnum.VALID_IP]: true }; } return null; } } /** * @method ipOverlapSubnet validator to check if input is overlapping with subnet * - non-empty * - valid ip * - not overlapping with subnet * * NOTE: non-exhaustive check */ ipOverlapSubnet(subnetCtrl: AbstractControl, subnetMaskCtrl: AbstractControl): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { if (validationMethods.isValidIp(ctrlValue)) { const ipLong = validationMethods.ipAddrToLong(ctrlValue); const subnetMask = subnetMaskCtrl.value; const subnet = subnetCtrl.value; if (validationMethods.isValidIp(subnet) && validationMethods.isValidIp(subnetMask)) { const subnetLong = validationMethods.ipAddrToLong(subnet); const subnetMaskLong = validationMethods.ipAddrToLong(subnetMask); if (validationMethods.ipOverlapSubnet(ipLong, subnetLong, subnetMaskLong)) { return { [ValidatorEnum.IP_NOT_IN_SUBNET_RANGE]: true }; } } return null; } return { [ValidatorEnum.VALID_IP]: true }; } return null; } } /** * @method cidrOverlapCidr validator to check if input is overlapping with another cidr */ cidrOverlapCidr(compareCidrCtrl: AbstractControl): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; const compareValue: string = compareCidrCtrl.value; if (ctrlValue) { if (validationMethods.isValidCidr(ctrlValue) && validationMethods.isValidCidr(compareValue)) { if (validationMethods.isCidrOverlapCidr(ctrlValue, compareValue)) { return { [ValidatorEnum.CIDR_OVERLAP_CIDR]: true }; } return null; } } return null; } } /** * @method cidrWithinCidr validator to check if input is within another cidr range */ cidrWithinCidr(compareCidrCtrl: AbstractControl): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; const compareValue: string = compareCidrCtrl.value; if (ctrlValue) { if (validationMethods.isValidCidr(ctrlValue) && validationMethods.isValidCidr(compareValue)) { if (!validationMethods.isCidrWithinCidr(ctrlValue, compareValue)) { return { [ValidatorEnum.CIDR_WITHIN_CIDR]: true }; } return null; } } return null; } } /** * @method isValidIpNetworkSegment * xxx.xxx.xxx.xx/xx */ isValidIpNetworkSegment(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { const ctrlValueList = ctrlValue.split('/'); if (ctrlValueList.length === 2) { if (!validationMethods.isValidIp(ctrlValueList[0])) { return { [ValidatorEnum.VALID_IP]: true } } return ctrlValueList[1] && +ctrlValueList[1] >= 0 && +ctrlValueList[1] < 32 ? null : { [ValidatorEnum.VALID_IP]: true } } else { return { [ValidatorEnum.VALID_IP]: true }; } } return null; } } /** * @method isValidIpv6NetworkSegment * xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/xxx */ isValidIpv6NetworkSegment(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { const ctrlValueList = ctrlValue.split('/'); if (ctrlValueList.length === 2) { if (!isIp.v6(ctrlValueList[0])) { return { [ValidatorEnum.VALID_IP]: true } } return ctrlValueList[1] && +ctrlValueList[1] >= 0 && +ctrlValueList[1] < 128 ? null : { [ValidatorEnum.VALID_IP]: true } } else { return { [ValidatorEnum.VALID_IP]: true }; } } return null; } } /** * @method isIpUnique * @param otherControls - array of IP controls to pass in; checks all IP's to confirm they are unique * @returns {function(AbstractControl): {}} */ isIpUnique(otherControls: Array<AbstractControl>) { return (control: AbstractControl) => { if (control.value) { const currentControlIp = control.value; for (const ipAddr of otherControls) { if (currentControlIp === ipAddr.value) { return {[ValidatorEnum.NETWORKING_IP_UNIQUE]: true}; } } } } } /** * @method confirmPassword check if password and confirm password match */ confirmPassword(passwordCtrl: AbstractControl): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; const passwordValue = passwordCtrl.value; if (passwordCtrl) { if (ctrlValue) { if (ctrlValue !== passwordValue) { return { [ValidatorEnum.CONFIRM_PASSWORD]: true }; } else { return null; } } else { return { [ValidatorEnum.REQUIRED]: true }; } } return null; } } /** * @method isNumericOnly to check if input is numeric only */ isNumericOnly(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { if (validationMethods.isNumericOnly(ctrlValue)) { return null; } return {[ValidatorEnum.NUMERIC_ONLY]: true}; } return null; } } /** * @method commaSeparatedIpOrFqdn * @param {string} arg input string * @return {boolean} */ commaSeparatedIpOrFqdn(arg: string): any { const ips = arg.split(','); return ips.map(ip => validationMethods.isValidIp(ip) || validationMethods.isValidFqdn(ip)).reduce((a, b) => a && b, true); } /** * @method isCommaSeparatedIpsOrFqdn */ isCommaSeparatedIpsOrFqdn(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { if (!this.commaSeparatedIpOrFqdn(ctrlValue)) { return {[ValidatorEnum.VALID_IP_OR_FQDN]: true}; } } return null; } } /** * @method isNumberGreaterThanZero */ isNumberGreaterThanZero(): any { return (control: AbstractControl) => { const ctrlValue: number = control.value; if (ctrlValue === null) { return null; } if (typeof ctrlValue !== 'number' || ctrlValue < 1) { return {[ValidatorEnum.GREATER_THAN_ZERO]: true}; } return null; } } isUniqueAz(otherControls: Array<AbstractControl>): any { return (control: AbstractControl) => { if (control.value) { const currentAz = control.value; for (const az of otherControls) { if (currentAz === az.value) { return {[ValidatorEnum.AVAILABILITY_ZONE_UNIQUE]: true}; } } } } } isValidResourceGroupName(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue && !XRegExp('^[\\pL-_.()\\w]+$').test(ctrlValue)) { return {[ValidatorEnum.VALID_RESOURCE_GROUP_NAME]: true}; } return null; } } isUniqueResourceGroupName(resourceGroups): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue && resourceGroups.find(x => x.name === ctrlValue) != null) { return {[ValidatorEnum.UNIQUE_RESOURCE_GROUP_NAME]: true}; } return null; } } /** * @method isCommaSeperatedList */ isCommaSeperatedList(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue) { if (!XRegExp('^(((\\w+)(,\\w+)+)|(\\w+))$').test(ctrlValue)) { return { [ValidatorEnum.COMMA_SEPARATED_WORDS]: true }; } } } } isHttpOrHttps(): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (ctrlValue && !XRegExp('^https?:\/\/').test(ctrlValue)) { return {[ValidatorEnum.HTTP_OR_HTTPS]: true}; } return null; } } /** * @method isValidLdap * - non-empty * - valid IP or FQDN * - valid port * * @param {AbstractControl} ipCtrl */ isValidLdap(ipCtrl: AbstractControl): any { return (control: AbstractControl) => { const inputVal = ipCtrl.value; if (inputVal) { if (!validationMethods.isValidIp(inputVal) && !(validationMethods.isValidFqdn(inputVal))) { return {[ValidatorEnum.VALID_IP_OR_FQDN]: true}; } } else { return {[ValidatorEnum.REQUIRED]: true}; } if (control.value) { if (!validationMethods.isNumericOnly(control.value)) { return {[ValidatorEnum.VALID_PORT]: true}; } return null; } return {[ValidatorEnum.REQUIRED]: true}; } } /** * @method isValidIpv6Ldap * - non-empty * - valid IP or FQDN * - valid port * * @param {AbstractControl} ipCtrl */ isValidIpv6Ldap(ipCtrl: AbstractControl): any { return (control: AbstractControl) => { const inputVal = ipCtrl.value; if (inputVal) { if (!isIp.v6(inputVal) && !(validationMethods.isValidFqdn(inputVal))) { return {[ValidatorEnum.VALID_IP_OR_FQDN]: true}; } } else { return {[ValidatorEnum.REQUIRED]: true}; } if (control.value) { if (!validationMethods.isNumericOnly(control.value)) { return {[ValidatorEnum.VALID_PORT]: true}; } return null; } return {[ValidatorEnum.REQUIRED]: true}; } } isValidNameInList(list: Array<String>): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; if (list.indexOf(ctrlValue) === -1) { return {[ValidatorEnum.NOT_IN_DATALIST]: true}; } return null; } } isTrue(): any { return (control: AbstractControl) => { const ctrlValue: boolean = control.value; if (ctrlValue === true) { return {[ValidatorEnum.TRUE]: true}; } return null; } } isUniqueLabel(formGroup: FormGroup, keys: Set<string>, name: string): any { return (control: AbstractControl) => { const ctrlValue: string = control.value; for (const key of keys) { if (ctrlValue !== '' && ctrlValue === formGroup.value[key] && key !== name) { return {[ValidatorEnum.LABEL_UNIQUE]: true} } } return null; } } }
the_stack
import React from 'react'; import * as pc from 'playcanvas/build/playcanvas.js'; import Example from '../../app/example'; import { AssetLoader } from '../../app/helpers/loader'; class RenderCubemapExample extends Example { static CATEGORY = 'Graphics'; static NAME = 'Render Cubemap'; load() { return <> <AssetLoader name='helipad.dds' type='cubemap' url='static/assets/cubemaps/helipad.dds' data={{ type: pc.TEXTURETYPE_RGBM }}/> <AssetLoader name='script' type='script' url='static/scripts/utils/cubemap-renderer.js' /> </>; } // @ts-ignore: override class function example(canvas: HTMLCanvasElement, assets: { 'helipad.dds': pc.Asset, script: pc.Asset }): void { // Create the app const app = new pc.Application(canvas, {}); // start the update loop app.start(); // Set the canvas to fill the window and automatically change resolution to be the same as the canvas size app.setCanvasFillMode(pc.FILLMODE_FILL_WINDOW); app.setCanvasResolution(pc.RESOLUTION_AUTO); // set up some general scene rendering properties app.scene.gammaCorrection = pc.GAMMA_SRGB; app.scene.toneMapping = pc.TONEMAP_ACES; // setup skydome app.scene.skyboxMip = 0; // use top mipmap level of cubemap (full resolution) app.scene.skyboxIntensity = 2; // make it brighter app.scene.setSkybox(assets['helipad.dds'].resources); // helper function to create high polygon version of a sphere and sets up an entity to allow it to be added to the scene const createHighQualitySphere = function (material: pc.Material, layer: number[]) { // create hight resolution sphere // @ts-ignore engine-tsd const mesh = pc.createSphere(app.graphicsDevice, { latitudeBands: 200, longitudeBands: 200 }); // Create the mesh instance const node = new pc.GraphNode(); this.meshInstance = new pc.MeshInstance(mesh, material, node); // Create a model and add the mesh instance to it const model = new pc.Model(); model.graph = node; model.meshInstances = [this.meshInstance]; // Create Entity and add it to the scene const entity = new pc.Entity("ShinyBall"); app.root.addChild(entity); // Add a model compoonent entity.addComponent('model', { type: 'asset', layers: layer }); entity.model.model = model; return entity; }; // helper function to create a primitive with shape type, position, scale, color and layer function createPrimitive(primitiveType: string, position: number | pc.Vec3, scale: number | pc.Vec3, color: pc.Color, layer: number[]) { // create material of specified color const material = new pc.StandardMaterial(); material.diffuse = color; material.shininess = 60; material.metalness = 0.7; material.useMetalness = true; material.update(); // create primitive const primitive = new pc.Entity(); primitive.addComponent('model', { type: primitiveType, layers: layer }); primitive.model.material = material; // set position and scale and add it to scene primitive.setLocalPosition(position); primitive.setLocalScale(scale); app.root.addChild(primitive); return primitive; } // create a layer for object that do not render into texture const excludedLayer = new pc.Layer({ name: "Excluded" }); app.scene.layers.push(excludedLayer); // create material for the shiny ball const shinyMat = new pc.StandardMaterial(); // create shiny ball mesh - this is on excluded layer as it does not render to cubemap const shinyBall = createHighQualitySphere(shinyMat, [excludedLayer.id]); shinyBall.setLocalPosition(0, 0, 0); shinyBall.setLocalScale(10, 10, 10); // get world and skybox layers const worldLayer = app.scene.layers.getLayerByName("World"); const skyboxLayer = app.scene.layers.getLayerByName("Skybox"); const immediateLayer = app.scene.layers.getLayerByName("Immediate"); // add camera component to shiny ball - this defines camera properties for cubemap rendering shinyBall.addComponent('camera', { // optimization - no need to clear as all pixels get overwritten clearColorBuffer: false, // cubemap camera will render objects on world layer and also skybox layers: [worldLayer.id, skyboxLayer.id], // priority - render before world camera priority: -1, // disable as this is not a camera that renders cube map but only a container for properties for cube map rendering enabled: false }); // add cubemapRenderer script component which takes care of rendering dynamic cubemap shinyBall.addComponent('script'); shinyBall.script.create('cubemapRenderer', { attributes: { resolution: 256, mipmaps: true, depth: true } }); // finish set up of shiny material - make reflection a bit darker shinyMat.diffuse = new pc.Color(0.6, 0.6, 0.6); // use cubemap which is generated by cubemapRenderer instead of global skybox cubemap shinyMat.useSkybox = false; // @ts-ignore engine-tsd shinyMat.cubeMap = shinyBall.script.cubemapRenderer.cubeMap; // make it shiny without diffuse component shinyMat.metalness = 1; shinyMat.useMetalness = true; shinyMat.update(); // create few random primitives in the world layer const entities: pc.Entity[] = []; const shapes = ["box", "cone", "cylinder", "sphere", "capsule"]; for (let i = 0; i < 6; i++) { const shapeName = shapes[Math.floor(Math.random() * shapes.length)]; const color = new pc.Color(Math.random(), Math.random(), Math.random()); entities.push(createPrimitive(shapeName, pc.Vec3.ZERO, new pc.Vec3(3, 3, 3), color, [worldLayer.id])); } // create green plane as a base to cast shadows on createPrimitive("plane", new pc.Vec3(0, -8, 0), new pc.Vec3(20, 20, 20), new pc.Color(0.3, 0.5, 0.3), [worldLayer.id]); // Create main camera, which renders entities in world, excluded and skybox layers const camera = new pc.Entity("MainCamera"); camera.addComponent("camera", { fov: 60, layers: [worldLayer.id, excludedLayer.id, skyboxLayer.id, immediateLayer.id] }); app.root.addChild(camera); // Create an Entity with a directional light component const light = new pc.Entity(); light.addComponent("light", { type: "directional", color: pc.Color.YELLOW, range: 40, castShadows: true, layers: [worldLayer.id], shadowBias: 0.2, shadowResolution: 1024, normalOffsetBias: 0.05, shadowDistance: 40 }); app.root.addChild(light); // helper function to create a texture that can be used to project cubemap to function createReprojectionTexture(projection: string, size: number) { return new pc.Texture(this.app.graphicsDevice, { width: size, height: size, format: pc.PIXELFORMAT_R8_G8_B8, mipmaps: false, minFilter: pc.FILTER_LINEAR, magFilter: pc.FILTER_LINEAR, addressU: pc.ADDRESS_CLAMP_TO_EDGE, addressV: pc.ADDRESS_CLAMP_TO_EDGE, projection: projection }); } // create 2 uqirect and 2 octahedral textures const textureEqui = createReprojectionTexture(pc.TEXTUREPROJECTION_EQUIRECT, 256); const textureEqui2 = createReprojectionTexture(pc.TEXTUREPROJECTION_EQUIRECT, 256); const textureOcta = createReprojectionTexture(pc.TEXTUREPROJECTION_OCTAHEDRAL, 64); const textureOcta2 = createReprojectionTexture(pc.TEXTUREPROJECTION_OCTAHEDRAL, 32); // update things each frame let time = 0; const device = app.graphicsDevice; app.on("update", function (dt) { time += dt; // rotate primitives around their center and also orbit them around the shiny sphere for (let e = 0; e < entities.length; e++) { const scale = (e + 1) / entities.length; const offset = time + e * 200; // @ts-ignore engine-tsd entities[e].setLocalPosition(7 * Math.sin(offset), 2 * (e - 3), 7 * Math.cos(offset)); entities[e].rotate(1 * scale, 2 * scale, 3 * scale); } // slowly orbit camera around camera.setLocalPosition(20 * Math.cos(time * 0.2), 2, 20 * Math.sin(time * 0.2)); camera.lookAt(pc.Vec3.ZERO); // project textures, and display them on the screen // @ts-ignore engine-tsd const srcCube = shinyBall.script.cubemapRenderer.cubeMap; // cube -> equi1 pc.reprojectTexture(srcCube, textureEqui, { numSamples: 1 }); // @ts-ignore engine-tsd app.drawTexture(-0.6, 0.7, 0.6, 0.3, textureEqui); // cube -> octa1 pc.reprojectTexture(srcCube, textureOcta, { numSamples: 1 }); // @ts-ignore engine-tsd app.drawTexture(0.7, 0.7, 0.4, 0.4, textureOcta); // equi1 -> octa2 pc.reprojectTexture(textureEqui, textureOcta2, { specularPower: 32, numSamples: 1024 }); // @ts-ignore engine-tsd app.drawTexture(-0.7, -0.7, 0.4, 0.4, textureOcta2); // octa1 -> equi2 pc.reprojectTexture(textureOcta, textureEqui2, { specularPower: 16, numSamples: 512 }); // @ts-ignore engine-tsd app.drawTexture(0.6, -0.7, 0.6, 0.3, textureEqui2); }); } } export default RenderCubemapExample;
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormInvoiceDetail_Information { interface tab_address_Sections { ship_to_address: DevKit.Controls.Section; } interface tab_delivery_Sections { delivery_information: DevKit.Controls.Section; fulfillment: DevKit.Controls.Section; } interface tab_editproductpropertiesinlinetab_Sections { productpropertiessection: DevKit.Controls.Section; } interface tab_FieldService_Sections { tab_4_section_2: DevKit.Controls.Section; } interface tab_general_Sections { invoice_detail_information: DevKit.Controls.Section; pricing: DevKit.Controls.Section; } interface tab_address extends DevKit.Controls.ITab { Section: tab_address_Sections; } interface tab_delivery extends DevKit.Controls.ITab { Section: tab_delivery_Sections; } interface tab_editproductpropertiesinlinetab extends DevKit.Controls.ITab { Section: tab_editproductpropertiesinlinetab_Sections; } interface tab_FieldService extends DevKit.Controls.ITab { Section: tab_FieldService_Sections; } interface tab_general extends DevKit.Controls.ITab { Section: tab_general_Sections; } interface Tabs { address: tab_address; delivery: tab_delivery; editproductpropertiesinlinetab: tab_editproductpropertiesinlinetab; FieldService: tab_FieldService; general: tab_general; } interface Body { Tab: Tabs; /** Enter the date when the invoiced product was delivered to the customer. */ ActualDeliveryOn: DevKit.Controls.Date; /** Shows the total price of the invoice product, based on the price per unit, volume discount, and quantity. */ BaseAmount: DevKit.Controls.Money; /** Type additional information to describe the product line item of the invoice. */ Description: DevKit.Controls.String; /** Shows the total amount due for the invoice product, based on the sum of the unit price, quantity, discounts, and tax. */ ExtendedAmount: DevKit.Controls.Money; /** Select whether the price per unit is fixed at the value in the specified price list or can be overridden by users who have edit rights to the invoice product. */ IsPriceOverridden: DevKit.Controls.Boolean; /** Select whether the product exists in the Microsoft Dynamics 365 product catalog or is a write-in product specific to the parent invoice. */ IsProductOverridden: DevKit.Controls.Boolean; /** Type the manual discount amount for the invoice product to deduct any negotiated or other savings from the product total. */ ManualDiscountAmount: DevKit.Controls.Money; /** Unique identifier for Agreement associated with Invoice Product. */ msdyn_Agreement: DevKit.Controls.Lookup; /** Unique identifier for Agreement Invoice Product associated with Invoice Product. */ msdyn_AgreementInvoiceProduct: DevKit.Controls.Lookup; /** Shows the order of this invoice product within the invoice. */ msdyn_LineOrder: DevKit.Controls.Integer; /** Unique identifier for Work Order associated with Invoice Product. */ msdyn_WorkOrderId: DevKit.Controls.Lookup; /** Unique identifier for Work Order Product associated with Invoice Product. */ msdyn_WorkOrderProductId: DevKit.Controls.Lookup; /** Unique identifier for Work Order Service associated with Invoice Product. */ msdyn_WorkOrderServiceId: DevKit.Controls.Lookup; /** Type the price per unit of the invoice product. The default is the value in the price list specified on the parent invoice for existing products. */ PricePerUnit: DevKit.Controls.Money; /** Type a name or description to identify the type of write-in product included in the invoice. */ ProductDescription: DevKit.Controls.String; /** Choose the product to include on the invoice. */ ProductId: DevKit.Controls.Lookup; editpropertiescontrol: DevKit.Controls.ActionCards; /** Type the amount or quantity of the product included in the invoice's total amount due. */ Quantity: DevKit.Controls.Decimal; /** Type the amount or quantity of the product that is back ordered for the invoice. */ QuantityBackordered: DevKit.Controls.Decimal; /** Type the amount or quantity of the product that was canceled for the invoice line item. */ QuantityCancelled: DevKit.Controls.Decimal; /** Type the amount or quantity of the product that was shipped. */ QuantityShipped: DevKit.Controls.Decimal; /** Choose the user responsible for the sale of the invoice product. */ SalesRepId: DevKit.Controls.Lookup; /** Type the city for the customer's shipping address. */ ShipTo_City: DevKit.Controls.String; /** Type the country or region for the customer's shipping address. */ ShipTo_Country: DevKit.Controls.String; /** Type the fax number for the customer's shipping address. */ ShipTo_Fax: DevKit.Controls.String; /** Select the freight terms to make sure shipping orders are processed correctly. */ ShipTo_FreightTermsCode: DevKit.Controls.OptionSet; /** Type the first line of the customer's shipping address. */ ShipTo_Line1: DevKit.Controls.String; /** Type the second line of the customer's shipping address. */ ShipTo_Line2: DevKit.Controls.String; /** Type the third line of the shipping address. */ ShipTo_Line3: DevKit.Controls.String; /** Type a name for the customer's shipping address, such as "Headquarters" or "Field office", to identify the address. */ ShipTo_Name: DevKit.Controls.String; /** Type the ZIP Code or postal code for the shipping address. */ ShipTo_PostalCode: DevKit.Controls.String; /** Type the state or province for the shipping address. */ ShipTo_StateOrProvince: DevKit.Controls.String; /** Type the phone number for the customer's shipping address. */ ShipTo_Telephone: DevKit.Controls.String; /** Type the tax amount for the invoice product. */ Tax: DevKit.Controls.Money; /** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */ UoMId: DevKit.Controls.Lookup; /** Shows the discount amount per unit if a specified volume is purchased. Configure volume discounts in the Product Catalog in the Settings area. */ VolumeDiscountAmount: DevKit.Controls.Money; /** Select whether the invoice product should be shipped to the specified address or held until the customer calls with further pick up or delivery instructions. */ WillCall: DevKit.Controls.Boolean; } } class FormInvoiceDetail_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form InvoiceDetail_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form InvoiceDetail_Information */ Body: DevKit.FormInvoiceDetail_Information.Body; } namespace FormProject { interface tab_address_Sections { ship_to_address: DevKit.Controls.Section; } interface tab_ChargeableTransactionsTab_Sections { TransactionsSection: DevKit.Controls.Section; } interface tab_ComplimentaryTransactionsTab_Sections { tab_6_section_1: DevKit.Controls.Section; } interface tab_delivery_Sections { delivery_information: DevKit.Controls.Section; fulfillment: DevKit.Controls.Section; } interface tab_HiddenFields_Sections { tab_8_section_1: DevKit.Controls.Section; } interface tab_HiddenTab_Deprecated_Sections { HiddenTab_section_1: DevKit.Controls.Section; } interface tab_MilestonesTab_Sections { tab_9_section_1: DevKit.Controls.Section; } interface tab_NonChargeableTransactionsTab_Sections { tab_7_section_1: DevKit.Controls.Section; } interface tab_ProductTab_Sections { invoice_detail_information: DevKit.Controls.Section; pricing: DevKit.Controls.Section; } interface tab_ProjectTab_Sections { tab_4_section_1: DevKit.Controls.Section; } interface tab_address extends DevKit.Controls.ITab { Section: tab_address_Sections; } interface tab_ChargeableTransactionsTab extends DevKit.Controls.ITab { Section: tab_ChargeableTransactionsTab_Sections; } interface tab_ComplimentaryTransactionsTab extends DevKit.Controls.ITab { Section: tab_ComplimentaryTransactionsTab_Sections; } interface tab_delivery extends DevKit.Controls.ITab { Section: tab_delivery_Sections; } interface tab_HiddenFields extends DevKit.Controls.ITab { Section: tab_HiddenFields_Sections; } interface tab_HiddenTab_Deprecated extends DevKit.Controls.ITab { Section: tab_HiddenTab_Deprecated_Sections; } interface tab_MilestonesTab extends DevKit.Controls.ITab { Section: tab_MilestonesTab_Sections; } interface tab_NonChargeableTransactionsTab extends DevKit.Controls.ITab { Section: tab_NonChargeableTransactionsTab_Sections; } interface tab_ProductTab extends DevKit.Controls.ITab { Section: tab_ProductTab_Sections; } interface tab_ProjectTab extends DevKit.Controls.ITab { Section: tab_ProjectTab_Sections; } interface Tabs { address: tab_address; ChargeableTransactionsTab: tab_ChargeableTransactionsTab; ComplimentaryTransactionsTab: tab_ComplimentaryTransactionsTab; delivery: tab_delivery; HiddenFields: tab_HiddenFields; HiddenTab_Deprecated: tab_HiddenTab_Deprecated; MilestonesTab: tab_MilestonesTab; NonChargeableTransactionsTab: tab_NonChargeableTransactionsTab; ProductTab: tab_ProductTab; ProjectTab: tab_ProjectTab; } interface Body { Tab: Tabs; /** Enter the date when the invoiced product was delivered to the customer. */ ActualDeliveryOn: DevKit.Controls.Date; /** Shows the total price of the invoice product, based on the price per unit, volume discount, and quantity. */ BaseAmount: DevKit.Controls.Money; /** Shows the total price of the invoice product, based on the price per unit, volume discount, and quantity. */ BaseAmount_1: DevKit.Controls.Money; /** Shows the total amount due for the invoice product, based on the sum of the unit price, quantity, discounts, and tax. */ ExtendedAmount: DevKit.Controls.Money; /** Unique identifier of the invoice associated with the invoice product line item. */ InvoiceId: DevKit.Controls.Lookup; /** Select whether the price per unit is fixed at the value in the specified price list or can be overridden by users who have edit rights to the invoice product. */ IsPriceOverridden: DevKit.Controls.Boolean; /** Select whether the product exists in the Microsoft Dynamics 365 product catalog or is a write-in product specific to the parent invoice. */ IsProductOverridden: DevKit.Controls.Boolean; /** Type the manual discount amount for the invoice product to deduct any negotiated or other savings from the product total. */ ManualDiscountAmount: DevKit.Controls.Money; /** Billing method for the project invoice line. Valid values are Time and Material and Fixed Price */ msdyn_BillingMethod: DevKit.Controls.OptionSet; /** The amount from included line details that is chargeable. */ msdyn_chargeableamount: DevKit.Controls.Money; /** The amount from included line details that is complimentary and won't be charged. */ msdyn_complimentaryamount: DevKit.Controls.Money; /** Amount from the related project contract line if present. */ msdyn_contractlineamount: DevKit.Controls.Money; /** Amount already invoiced to customer for the same project contract line. */ msdyn_invoicedtilldate: DevKit.Controls.Money; /** The amount from included line details that is non-chargeable. */ msdyn_nonchargeableamount: DevKit.Controls.Money; /** Shows the project for this invoice line. */ msdyn_Project: DevKit.Controls.Lookup; /** Type the price per unit of the invoice product. The default is the value in the price list specified on the parent invoice for existing products. */ PricePerUnit: DevKit.Controls.Money; /** Type a name or description to identify the type of write-in product included in the invoice. */ ProductDescription: DevKit.Controls.String; /** Type a name or description to identify the type of write-in product included in the invoice. */ ProductDescription_1: DevKit.Controls.String; /** Choose the product to include on the invoice. */ ProductId: DevKit.Controls.Lookup; /** Product Type */ ProductTypeCode: DevKit.Controls.OptionSet; /** Type the amount or quantity of the product included in the invoice's total amount due. */ Quantity: DevKit.Controls.Decimal; /** Type the amount or quantity of the product that is back ordered for the invoice. */ QuantityBackordered: DevKit.Controls.Decimal; /** Type the amount or quantity of the product that was canceled for the invoice line item. */ QuantityCancelled: DevKit.Controls.Decimal; /** Type the amount or quantity of the product that was shipped. */ QuantityShipped: DevKit.Controls.Decimal; /** Unique identifier for Order Line associated with Invoice Line. */ SalesOrderDetailId: DevKit.Controls.Lookup; /** Choose the user responsible for the sale of the invoice product. */ SalesRepId: DevKit.Controls.Lookup; /** Type the city for the customer's shipping address. */ ShipTo_City: DevKit.Controls.String; /** Type the country or region for the customer's shipping address. */ ShipTo_Country: DevKit.Controls.String; /** Type the fax number for the customer's shipping address. */ ShipTo_Fax: DevKit.Controls.String; /** Select the freight terms to make sure shipping orders are processed correctly. */ ShipTo_FreightTermsCode: DevKit.Controls.OptionSet; /** Type the first line of the customer's shipping address. */ ShipTo_Line1: DevKit.Controls.String; /** Type the second line of the customer's shipping address. */ ShipTo_Line2: DevKit.Controls.String; /** Type the third line of the shipping address. */ ShipTo_Line3: DevKit.Controls.String; /** Type a name for the customer's shipping address, such as "Headquarters" or "Field office", to identify the address. */ ShipTo_Name: DevKit.Controls.String; /** Type the ZIP Code or postal code for the shipping address. */ ShipTo_PostalCode: DevKit.Controls.String; /** Type the state or province for the shipping address. */ ShipTo_StateOrProvince: DevKit.Controls.String; /** Type the phone number for the customer's shipping address. */ ShipTo_Telephone: DevKit.Controls.String; /** Type the tax amount for the invoice product. */ Tax: DevKit.Controls.Money; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.Controls.Lookup; /** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */ UoMId: DevKit.Controls.Lookup; /** Shows the discount amount per unit if a specified volume is purchased. Configure volume discounts in the Product Catalog in the Settings area. */ VolumeDiscountAmount: DevKit.Controls.Money; /** Select whether the invoice product should be shipped to the specified address or held until the customer calls with further pick up or delivery instructions. */ WillCall: DevKit.Controls.Boolean; } interface Grid { MilestonesGrid: DevKit.Controls.Grid; ChargeableTransactionsGrid: DevKit.Controls.Grid; ComplimentaryTransactionsGrid: DevKit.Controls.Grid; NonChargeableTransactionsGrid: DevKit.Controls.Grid; } } class FormProject extends DevKit.IForm { /** * DynamicsCrm.DevKit form Project * @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 Project */ Body: DevKit.FormProject.Body; /** The Grid of form Project */ Grid: DevKit.FormProject.Grid; } namespace FormInvoiceDetail { interface tab_general_Sections { delivery_information: DevKit.Controls.Section; invoice_detail_information: DevKit.Controls.Section; pricing: DevKit.Controls.Section; } interface tab_general extends DevKit.Controls.ITab { Section: tab_general_Sections; } interface Tabs { general: tab_general; } interface Body { Tab: Tabs; /** Enter the date when the invoiced product was delivered to the customer. */ ActualDeliveryOn: DevKit.Controls.Date; /** Unique identifier of the invoice associated with the invoice product line item. */ InvoiceId: DevKit.Controls.Lookup; /** Select whether the price per unit is fixed at the value in the specified price list or can be overridden by users who have edit rights to the invoice product. */ IsPriceOverridden: DevKit.Controls.Boolean; /** Select whether the product exists in the Microsoft Dynamics 365 product catalog or is a write-in product specific to the parent invoice. */ IsProductOverridden: DevKit.Controls.Boolean; /** Type the manual discount amount for the invoice product to deduct any negotiated or other savings from the product total. */ ManualDiscountAmount: DevKit.Controls.Money; /** Type the price per unit of the invoice product. The default is the value in the price list specified on the parent invoice for existing products. */ PricePerUnit: DevKit.Controls.Money; /** Type a name or description to identify the type of write-in product included in the invoice. */ ProductDescription: DevKit.Controls.String; /** Choose the product to include on the invoice. */ ProductId: DevKit.Controls.Lookup; /** Type the amount or quantity of the product included in the invoice's total amount due. */ Quantity: DevKit.Controls.Decimal; /** Type the amount or quantity of the product that is back ordered for the invoice. */ QuantityBackordered: DevKit.Controls.Decimal; /** Type the amount or quantity of the product that was canceled for the invoice line item. */ QuantityCancelled: DevKit.Controls.Decimal; /** Type the amount or quantity of the product that was shipped. */ QuantityShipped: DevKit.Controls.Decimal; /** Choose the user responsible for the sale of the invoice product. */ SalesRepId: DevKit.Controls.Lookup; /** Type the city for the customer's shipping address. */ ShipTo_City: DevKit.Controls.String; /** Type the country or region for the customer's shipping address. */ ShipTo_Country: DevKit.Controls.String; /** Type the fax number for the customer's shipping address. */ ShipTo_Fax: DevKit.Controls.String; /** Select the freight terms to make sure shipping orders are processed correctly. */ ShipTo_FreightTermsCode: DevKit.Controls.OptionSet; /** Type the first line of the customer's shipping address. */ ShipTo_Line1: DevKit.Controls.String; /** Type a name for the customer's shipping address, such as "Headquarters" or "Field office", to identify the address. */ ShipTo_Name: DevKit.Controls.String; /** Type the ZIP Code or postal code for the shipping address. */ ShipTo_PostalCode: DevKit.Controls.String; /** Type the state or province for the shipping address. */ ShipTo_StateOrProvince: DevKit.Controls.String; /** Type the phone number for the customer's shipping address. */ ShipTo_Telephone: DevKit.Controls.String; /** Type the tax amount for the invoice product. */ Tax: DevKit.Controls.Money; /** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */ UoMId: DevKit.Controls.Lookup; /** Select whether the invoice product should be shipped to the specified address or held until the customer calls with further pick up or delivery instructions. */ WillCall: DevKit.Controls.Boolean; } } class FormInvoiceDetail extends DevKit.IForm { /** * DynamicsCrm.DevKit form InvoiceDetail * @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 InvoiceDetail */ Body: DevKit.FormInvoiceDetail.Body; } class InvoiceDetailApi { /** * DynamicsCrm.DevKit InvoiceDetailApi * @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; /** Enter the date when the invoiced product was delivered to the customer. */ ActualDeliveryOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Shows the total price of the invoice product, based on the price per unit, volume discount, and quantity. */ BaseAmount: DevKit.WebApi.MoneyValue; /** Value of the Amount in base currency. */ BaseAmount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ 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 product line item of the invoice. */ Description: DevKit.WebApi.StringValue; /** 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; /** Shows the total amount due for the invoice product, based on the sum of the unit price, quantity, discounts, and tax. */ ExtendedAmount: DevKit.WebApi.MoneyValue; /** Value of the Extended Amount in base currency. */ ExtendedAmount_Base: DevKit.WebApi.MoneyValueReadonly; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the invoice product line item. */ InvoiceDetailId: DevKit.WebApi.GuidValue; /** Invoice Detail Name. Added for 1:n referential relationship (internal purposes only) */ InvoiceDetailName: DevKit.WebApi.StringValue; /** Unique identifier of the invoice associated with the invoice product line item. */ InvoiceId: DevKit.WebApi.LookupValue; /** Information about whether invoice product pricing is locked. */ InvoiceIsPriceLocked: DevKit.WebApi.BooleanValueReadonly; /** Status of the invoice product. */ InvoiceStateCode: DevKit.WebApi.OptionSetValueReadonly; /** Select whether the invoice product is copied from another item or data source. */ IsCopied: DevKit.WebApi.BooleanValue; /** Select whether the price per unit is fixed at the value in the specified price list or can be overridden by users who have edit rights to the invoice product. */ IsPriceOverridden: DevKit.WebApi.BooleanValue; /** Select whether the product exists in the Microsoft Dynamics 365 product catalog or is a write-in product specific to the parent invoice. */ IsProductOverridden: DevKit.WebApi.BooleanValue; /** Type the line item number for the invoice product to easily identify the product in the invoice and make sure it's listed in the correct order. */ LineItemNumber: DevKit.WebApi.IntegerValue; /** Type the manual discount amount for the invoice product to deduct any negotiated or other savings from the product total. */ ManualDiscountAmount: DevKit.WebApi.MoneyValue; /** Value of the Manual Discount in base currency. */ ManualDiscountAmount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows who last updated the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for Agreement associated with Invoice Product. */ msdyn_Agreement: DevKit.WebApi.LookupValue; /** Unique identifier for Agreement Invoice Product associated with Invoice Product. */ msdyn_AgreementInvoiceProduct: DevKit.WebApi.LookupValue; /** Billing method for the project invoice line. Valid values are Time and Material and Fixed Price */ msdyn_BillingMethod: DevKit.WebApi.OptionSetValue; /** The amount from included line details that is chargeable. */ msdyn_chargeableamount: DevKit.WebApi.MoneyValue; /** Value of the Chargeable Amount in base currency. */ msdyn_chargeableamount_Base: DevKit.WebApi.MoneyValueReadonly; /** The amount from included line details that is complimentary and won't be charged. */ msdyn_complimentaryamount: DevKit.WebApi.MoneyValue; /** Value of the Complimentary Amount in base currency. */ msdyn_complimentaryamount_Base: DevKit.WebApi.MoneyValueReadonly; /** (Deprecated) Shows the project contract line for this invoice line. */ msdyn_ContractLine: DevKit.WebApi.StringValue; /** Amount from the related project contract line if present. */ msdyn_contractlineamount: DevKit.WebApi.MoneyValue; /** Value of the project contract line amount in base currency. */ msdyn_contractlineamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Unique identifier for Currency associated with Invoice Product. */ msdyn_Currency: DevKit.WebApi.LookupValue; /** Amount already invoiced to customer for the same project contract line. */ msdyn_invoicedtilldate: DevKit.WebApi.MoneyValue; /** Value of the Amount Previously Invoiced in base currency. */ msdyn_invoicedtilldate_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the order of this invoice product within the invoice. */ msdyn_LineOrder: DevKit.WebApi.IntegerValue; /** The field to distinguish the Invoice lines to be of project service or field service */ msdyn_LineType: DevKit.WebApi.OptionSetValue; /** The amount from included line details that is non-chargeable. */ msdyn_nonchargeableamount: DevKit.WebApi.MoneyValue; /** Value of the Non Chargeable Amount in base currency. */ msdyn_nonchargeableamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Unique identifier for Order Invoicing Product associated with Invoice Product. */ msdyn_OrderInvoicingProduct: DevKit.WebApi.LookupValue; /** Shows the project for this invoice line. */ msdyn_Project: DevKit.WebApi.LookupValue; /** Unique identifier for Work Order associated with Invoice Product. */ msdyn_WorkOrderId: DevKit.WebApi.LookupValue; /** Unique identifier for Work Order Product associated with Invoice Product. */ msdyn_WorkOrderProductId: DevKit.WebApi.LookupValue; /** Unique identifier for Work Order Service associated with Invoice Product. */ msdyn_WorkOrderServiceId: DevKit.WebApi.LookupValue; /** 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.LookupValueReadonly; /** 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.LookupValueReadonly; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Choose the parent bundle associated with this product */ ParentBundleId: DevKit.WebApi.GuidValue; /** Choose the parent bundle associated with this product */ ParentBundleIdRef: DevKit.WebApi.LookupValue; /** Type the price per unit of the invoice product. The default is the value in the price list specified on the parent invoice for existing products. */ PricePerUnit: DevKit.WebApi.MoneyValue; /** Value of the Price Per Unit in base currency. */ PricePerUnit_Base: DevKit.WebApi.MoneyValueReadonly; /** Pricing error for the invoice product line item. */ PricingErrorCode: DevKit.WebApi.OptionSetValue; /** Unique identifier of the product line item association with bundle in the invoice */ ProductAssociationId: DevKit.WebApi.GuidValue; /** Type a name or description to identify the type of write-in product included in the invoice. */ ProductDescription: DevKit.WebApi.StringValue; /** Choose the product to include on the invoice. */ ProductId: DevKit.WebApi.LookupValue; /** Calculated field that will be populated by name and description of the product. */ ProductName: DevKit.WebApi.StringValue; /** User-defined product ID. */ ProductNumber: DevKit.WebApi.StringValueReadonly; /** Product Type */ ProductTypeCode: DevKit.WebApi.OptionSetValue; /** Status of the property configuration. */ PropertyConfigurationStatus: DevKit.WebApi.OptionSetValue; /** Type the amount or quantity of the product included in the invoice's total amount due. */ Quantity: DevKit.WebApi.DecimalValue; /** Type the amount or quantity of the product that is back ordered for the invoice. */ QuantityBackordered: DevKit.WebApi.DecimalValue; /** Type the amount or quantity of the product that was canceled for the invoice line item. */ QuantityCancelled: DevKit.WebApi.DecimalValue; /** Type the amount or quantity of the product that was shipped. */ QuantityShipped: DevKit.WebApi.DecimalValue; /** Unique identifier for Order Line associated with Invoice Line. */ SalesOrderDetailId: DevKit.WebApi.LookupValue; /** Choose the user responsible for the sale of the invoice product. */ SalesRepId: DevKit.WebApi.LookupValue; /** Shows the ID of the data that maintains the sequence. */ SequenceNumber: DevKit.WebApi.IntegerValue; /** Type a tracking number for shipment of the invoiced product. */ ShippingTrackingNumber: DevKit.WebApi.StringValue; /** Type the city for the customer's shipping address. */ ShipTo_City: DevKit.WebApi.StringValue; /** Type the country or region for the customer's shipping address. */ ShipTo_Country: DevKit.WebApi.StringValue; /** Type the fax number for the customer's shipping address. */ ShipTo_Fax: DevKit.WebApi.StringValue; /** Select the freight terms to make sure shipping orders are processed correctly. */ ShipTo_FreightTermsCode: DevKit.WebApi.OptionSetValue; /** Type the first line of the customer's shipping address. */ ShipTo_Line1: DevKit.WebApi.StringValue; /** Type the second line of the customer's shipping address. */ ShipTo_Line2: DevKit.WebApi.StringValue; /** Type the third line of the shipping address. */ ShipTo_Line3: DevKit.WebApi.StringValue; /** Type a name for the customer's shipping address, such as "Headquarters" or "Field office", to identify the address. */ ShipTo_Name: DevKit.WebApi.StringValue; /** Type the ZIP Code or postal code for the shipping address. */ ShipTo_PostalCode: DevKit.WebApi.StringValue; /** Type the state or province for the shipping address. */ ShipTo_StateOrProvince: DevKit.WebApi.StringValue; /** Type the phone number for the customer's shipping address. */ ShipTo_Telephone: DevKit.WebApi.StringValue; /** Skip Price Calculation */ SkipPriceCalculation: DevKit.WebApi.OptionSetValue; /** Type the tax amount for the invoice product. */ Tax: DevKit.WebApi.MoneyValue; /** Value of the Tax in base currency. */ Tax_Base: DevKit.WebApi.MoneyValueReadonly; /** 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; /** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */ UoMId: DevKit.WebApi.LookupValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; /** Shows the discount amount per unit if a specified volume is purchased. Configure volume discounts in the Product Catalog in the Settings area. */ VolumeDiscountAmount: DevKit.WebApi.MoneyValueReadonly; /** Value of the Volume Discount in base currency. */ VolumeDiscountAmount_Base: DevKit.WebApi.MoneyValueReadonly; /** Select whether the invoice product should be shipped to the specified address or held until the customer calls with further pick up or delivery instructions. */ WillCall: DevKit.WebApi.BooleanValue; } } declare namespace OptionSet { namespace InvoiceDetail { enum InvoiceStateCode { } enum msdyn_BillingMethod { /** 192350001 */ Fixed_Price, /** 192350000 */ Time_and_Material } enum msdyn_LineType { /** 690970001 */ Field_Service_Line, /** 690970000 */ Project_Service_Line } enum PricingErrorCode { /** 36 */ Base_Currency_Attribute_Overflow, /** 37 */ Base_Currency_Attribute_Underflow, /** 1 */ Detail_Error, /** 27 */ Discount_Type_Invalid_State, /** 33 */ Inactive_Discount_Type, /** 3 */ Inactive_Price_Level, /** 20 */ Invalid_Current_Cost, /** 28 */ Invalid_Discount, /** 26 */ Invalid_Discount_Type, /** 19 */ Invalid_Price, /** 17 */ Invalid_Price_Level_Amount, /** 34 */ Invalid_Price_Level_Currency, /** 18 */ Invalid_Price_Level_Percentage, /** 9 */ Invalid_Pricing_Code, /** 30 */ Invalid_Pricing_Precision, /** 7 */ Invalid_Product, /** 29 */ Invalid_Quantity, /** 24 */ Invalid_Rounding_Amount, /** 23 */ Invalid_Rounding_Option, /** 22 */ Invalid_Rounding_Policy, /** 21 */ Invalid_Standard_Cost, /** 15 */ Missing_Current_Cost, /** 14 */ Missing_Price, /** 2 */ Missing_Price_Level, /** 12 */ Missing_Price_Level_Amount, /** 13 */ Missing_Price_Level_Percentage, /** 8 */ Missing_Pricing_Code, /** 6 */ Missing_Product, /** 31 */ Missing_Product_Default_UOM, /** 32 */ Missing_Product_UOM_Schedule_, /** 4 */ Missing_Quantity, /** 16 */ Missing_Standard_Cost, /** 5 */ Missing_Unit_Price, /** 10 */ Missing_UOM, /** 0 */ None, /** 35 */ Price_Attribute_Out_Of_Range, /** 25 */ Price_Calculation_Error, /** 11 */ Product_Not_In_Price_Level, /** 38 */ Transaction_currency_is_not_set_for_the_product_price_list_item } enum ProductTypeCode { /** 2 */ Bundle, /** 4 */ Optional_Bundle_Product, /** 1 */ Product, /** 5 */ Project_based_Service, /** 3 */ Required_Bundle_Product } enum PropertyConfigurationStatus { /** 0 */ Edit, /** 2 */ Not_Configured, /** 1 */ Rectify } enum ShipTo_FreightTermsCode { /** 1 */ FOB, /** 2 */ No_Charge } enum SkipPriceCalculation { /** 0 */ DoPriceCalcAlways, /** 1 */ SkipPriceCalcOnCreate, /** 2 */ SkipPriceCalcOnUpdate, /** 3 */ SkipPriceCalcOnUpSert } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information','InvoiceDetail','Project'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { Equatable } from "@siteimprove/alfa-equatable"; import { Hash, Hashable } from "@siteimprove/alfa-hash"; import { Serializable } from "@siteimprove/alfa-json"; import { Option, None } from "@siteimprove/alfa-option"; import { Parser } from "@siteimprove/alfa-parser"; import { Result, Err } from "@siteimprove/alfa-result"; import { Slice } from "@siteimprove/alfa-slice"; import * as json from "@siteimprove/alfa-json"; import { Token } from "../../syntax/token"; import { Value } from "../../value"; import { Length } from "../length"; import { Percentage } from "../percentage"; import { Position } from "../position"; import { Gradient } from "../gradient"; import { Keyword } from "../keyword"; const { map, either, pair, option, left, right, delimited, take } = Parser; /** * {@link https://drafts.csswg.org/css-images/#radial-gradients} * * @public */ export class Radial< I extends Gradient.Item = Gradient.Item, S extends Radial.Shape = Radial.Shape, P extends Position = Position > extends Value<"gradient"> { public static of< I extends Gradient.Item = Gradient.Item, S extends Radial.Shape = Radial.Shape, P extends Position = Position >( shape: S, position: P, items: Iterable<I>, repeats: boolean ): Radial<I, S, P> { return new Radial(shape, position, Array.from(items), repeats); } private readonly _shape: S; private readonly _position: P; private readonly _items: Array<I>; private readonly _repeats: boolean; private constructor( shape: S, position: P, items: Iterable<I>, repeats: boolean ) { super(); this._shape = shape; this._position = position; this._items = [...items]; this._repeats = repeats; } public get type(): "gradient" { return "gradient"; } public get kind(): "radial" { return "radial"; } public get shape(): S { return this._shape; } public get position(): P { return this._position; } public get items(): Iterable<I> { return this._items; } public get repeats(): boolean { return this._repeats; } public equals(value: Radial): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return ( value instanceof Radial && value._shape.equals(this._shape) && value._position.equals(this._position) && value._items.length === this._items.length && value._items.every((item, i) => item.equals(this._items[i])) && value._repeats === this._repeats ); } public hash(hash: Hash): void { hash.writeHashable(this._shape).writeHashable(this._position); for (const item of this._items) { hash.writeHashable(item); } hash.writeUint32(this._items.length).writeBoolean(this._repeats); } public toJSON(): Radial.JSON { return { type: "gradient", kind: "radial", shape: this._shape.toJSON(), position: this._position.toJSON(), items: this._items.map((item) => item.toJSON()), repeats: this._repeats, }; } public toString(): string { const args = [`${this._shape} at ${this._position}`, ...this._items].join( ", " ); return `${this._repeats ? "repeating-" : ""}radial-gradient(${args})`; } } /** * @public */ export namespace Radial { export interface JSON extends Value.JSON<"gradient"> { kind: "radial"; shape: Shape.JSON; position: Position.JSON; items: Array<Gradient.Item.JSON>; repeats: boolean; } export type Shape = Circle | Ellipse | Extent; export namespace Shape { export type JSON = Circle.JSON | Ellipse.JSON | Extent.JSON; } /** * {@link https://drafts.csswg.org/css-images/#valdef-ending-shape-circle} */ export class Circle<R extends Length = Length> implements Equatable, Hashable, Serializable<Circle.JSON> { public static of<R extends Length>(radius: R): Circle<R> { return new Circle(radius); } private readonly _radius: R; private constructor(radius: R) { this._radius = radius; } public get type(): "circle" { return "circle"; } public get radius(): R { return this._radius; } public equals(value: Circle): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return value instanceof Circle && value._radius.equals(this._radius); } public hash(hash: Hash): void { hash.writeHashable(this._radius); } public toJSON(): Circle.JSON { return { type: "circle", radius: this._radius.toJSON(), }; } public toString(): string { return `circle ${this._radius}`; } } export namespace Circle { export interface JSON { [key: string]: json.JSON; type: "circle"; radius: Length.JSON; } } /** * {@link https://drafts.csswg.org/css-images/#valdef-ending-shape-ellipse} */ export class Ellipse<R extends Length | Percentage = Length | Percentage> implements Equatable, Hashable, Serializable<Ellipse.JSON> { public static of<R extends Length | Percentage>( horizontal: R, vertical: R ): Ellipse<R> { return new Ellipse(horizontal, vertical); } private readonly _horizontal: R; private readonly _vertical: R; private constructor(horizontal: R, vertical: R) { this._horizontal = horizontal; this._vertical = vertical; } public get type(): "ellipse" { return "ellipse"; } public get horizontal(): R { return this._horizontal; } public get vertical(): R { return this._vertical; } public equals(value: Ellipse): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return ( value instanceof Ellipse && value._horizontal.equals(this._horizontal) && value._vertical.equals(this._vertical) ); } public hash(hash: Hash): void { hash.writeHashable(this._horizontal).writeHashable(this._vertical); } public toJSON(): Ellipse.JSON { return { type: "ellipse", horizontal: this._horizontal.toJSON(), vertical: this._vertical.toJSON(), }; } public toString(): string { return `ellipse ${this._horizontal} ${this._vertical}`; } } export namespace Ellipse { export interface JSON { [key: string]: json.JSON; type: "ellipse"; horizontal: Length.JSON | Percentage.JSON; vertical: Length.JSON | Percentage.JSON; } } export class Extent implements Equatable, Hashable, Serializable<Extent.JSON> { public static of( shape: Extent.Shape = Extent.Shape.Circle, size: Extent.Size = Extent.Size.FarthestCorner ): Extent { return new Extent(shape, size); } private readonly _shape: Extent.Shape; private readonly _size: Extent.Size; private constructor(shape: Extent.Shape, size: Extent.Size) { this._shape = shape; this._size = size; } public get type(): "extent" { return "extent"; } public get shape(): Extent.Shape { return this._shape; } public get size(): Extent.Size { return this._size; } public equals(value: Extent): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return ( value instanceof Extent && value._shape === this._shape && value._size === this._size ); } public hash(hash: Hash): void { hash.writeString(this._shape).writeString(this._size); } public toJSON(): Extent.JSON { return { type: "extent", shape: this._shape, size: this._size, }; } public toString(): string { return `${this._shape} ${this._size}`; } } export namespace Extent { export enum Shape { Circle = "circle", Ellipse = "ellipse", } export enum Size { ClosestSide = "closest-side", FarthestSide = "farthest-side", ClosestCorner = "closest-corner", FarthestCorner = "farthest-corner", } export interface JSON { [key: string]: json.JSON; type: "extent"; shape: `${Shape}`; size: `${Size}`; } } const parsePosition = right( delimited(option(Token.parseWhitespace), Keyword.parse("at")), Position.parse(false /* legacySyntax */) ); const parseCircleShape = Keyword.parse("circle"); const parseCircleRadius = Length.parse; const parseCircle: Parser<Slice<Token>, Circle, string> = (input) => { let shape: Keyword<"circle"> | undefined; let radius: Length | undefined; while (true) { for ([input] of Token.parseWhitespace(input)) { } if (shape === undefined) { const result = parseCircleShape(input); if (result.isOk()) { [input, shape] = result.get(); continue; } } if (radius === undefined) { const result = parseCircleRadius(input); if (result.isOk()) { [input, radius] = result.get(); continue; } } break; } if (radius === undefined) { return Err.of(`Expected circle radius`); } return Result.of([input, Circle.of(radius)]); }; const parseEllipseShape = Keyword.parse("ellipse"); const parseEllipseSize = take( delimited( option(Token.parseWhitespace), either(Length.parse, Percentage.parse) ), 2 ); const parseEllipse: Parser<Slice<Token>, Ellipse, string> = (input) => { let shape: Keyword<"ellipse"> | undefined; let horizontal: Length | Percentage | undefined; let vertical: Length | Percentage | undefined; while (true) { for ([input] of Token.parseWhitespace(input)) { } if (shape === undefined) { const result = parseEllipseShape(input); if (result.isOk()) { [input, shape] = result.get(); continue; } } if (horizontal === undefined || vertical === undefined) { const result = parseEllipseSize(input); if (result.isOk()) { [input, [horizontal, vertical]] = result.get(); continue; } } break; } if (horizontal === undefined || vertical === undefined) { return Err.of(`Expected ellipse size`); } return Result.of([input, Ellipse.of(horizontal, vertical)]); }; const parseExtentShape = map( Keyword.parse("circle", "ellipse"), (keyword) => keyword.value as Extent.Shape ); const parseExtentSize = map( Keyword.parse( "closest-side", "farthest-side", "closest-corner", "farthest-corner" ), (keyword) => keyword.value as Extent.Size ); const parseExtent: Parser<Slice<Token>, Radial.Extent, string> = (input) => { let shape: Extent.Shape | undefined; let size: Extent.Size | undefined; while (true) { for ([input] of Token.parseWhitespace(input)) { } if (shape === undefined) { const result = parseExtentShape(input); if (result.isOk()) { [input, shape] = result.get(); continue; } } if (size === undefined) { const result = parseExtentSize(input); if (result.isOk()) { [input, size] = result.get(); continue; } } break; } if (shape === undefined && size === undefined) { return Err.of(`Expected either an extent shape or size`); } return Result.of([input, Extent.of(shape, size)]); }; const parseShape = either(either(parseEllipse, parseCircle), parseExtent); /** * {@link https://drafts.csswg.org/css-images/#funcdef-radial-gradient} */ export const parse: Parser<Slice<Token>, Radial, string> = map( pair( Token.parseFunction( (fn) => fn.value === "radial-gradient" || fn.value === "repeating-radial-gradient" ), left( delimited( option(Token.parseWhitespace), pair( option( left( either( pair( map(parseShape, (shape) => Option.of(shape)), option( delimited(option(Token.parseWhitespace), parsePosition) ) ), map( parsePosition, (position) => [None, Option.of(position)] as const ) ), delimited(option(Token.parseWhitespace), Token.parseComma) ) ), Gradient.parseItemList ) ), Token.parseCloseParenthesis ) ), (result) => { const [fn, [shapeAndPosition, items]] = result; const shape = shapeAndPosition .flatMap(([shape]) => shape) .getOrElse(() => Extent.of()); const position = shapeAndPosition .flatMap(([, position]) => position) .getOrElse(() => Position.of(Keyword.of("center"), Keyword.of("center")) ); return Radial.of( shape, position, items, fn.value.startsWith("repeating") ); } ); }
the_stack
import { Component, State, Element, h } from '@stencil/core'; import '@visa/visa-charts-data-table'; import '@visa/keyboard-instructions'; @Component({ tag: 'app-line-chart', styleUrl: 'app-line-chart.scss' }) export class AppLineChart { @State() data: any; @State() secondData: any; @State() stateTrigger: any = 1; @State() hoverElement: any = ''; @State() secondaryHoverElement: any = ''; @State() secondaryHover: any = ''; @State() clickElement: any = [ // { // date: new Date('2017-01-01'), // otherOrd: '13', // otherCat: 'ABC', // otherVal: 100, // category: 'Card A', // value: 7670994739 // } ]; @State() secondaryClick: any = []; @State() yAxis: any = { visible: true, gridVisible: true, label: 'Score', format: '0[.][0]' }; @State() ordinalAccessor: any = 'date'; @State() valueAccessor: any = 'value'; @State() seriesAccessor: any = 'category'; @State() seriesLabel: any = { visible: true, placement: 'auto' }; @State() dataLabel: any = { visible: true, placement: 'auto', labelAccessor: this.valueAccessor, format: '0.0[a]' }; @State() height: any = 300; @State() interactionKeys: any = [this.ordinalAccessor]; @State() secondaryKey: any = 'Card B'; @State() secondaryOpacity: any = 1; @State() secondaryDataLabel: any = true; @State() secondarySeriesLabel: any = true; @State() unit: any = 'month'; @State() animations: any = { disabled: true }; @State() annotations: any = [ { note: { label: '2018', bgPadding: 0, align: 'middle', wrap: 210 }, accessibilityDescription: '2018 High Spend band total is 5,596', x: '8%', y: '40%', disable: ['connector', 'subject'], // dy: '-1%', color: '#000000', className: 'testing1 testing2 testing3', collisionHideOnly: true }, { note: { label: 'oasijfoiajsf', bgPadding: 0, align: 'middle', wrap: 210 }, accessibilityDescription: '2018 High Spend band total is 5,596', x: '8%', y: '40%', disable: ['connector', 'subject'], // dy: '-1%', color: '#000000', className: 'testing1 testing2 testing3', collisionHideOnly: false } ]; @State() tooltipLabel: any = { format: '', labelAccessor: [this.ordinalAccessor], labelTitle: [this.ordinalAccessor] }; // @State() colors: any = [ // '#2e2e2e', // '#434343', // '#595959', // '#717171', // '#898989', // '#a3a3a3', // '#bdbdbd', // '#d7d7d7', // '#f2f2f2'] // colorsBase: any = ['#2e2e2e', // '#434343', // '#595959', // '#717171', // '#898989', // '#a3a3a3', // '#bdbdbd', // '#d7d7d7', // '#f2f2f2'] @State() colors: any = [ '#f2f2f2', '#d7d7d7', '#bdbdbd', '#a3a3a3', '#898989', '#717171', '#595959', '#434343', '#2e2e2e' ]; @State() accessibility: any = { longDescription: 'This is a chart template that was made to showcase the Visa Chart Components line plot', contextExplanation: 'This chart exists in a demo app created to let you quickly change props and see results', executiveSummary: 'Within the category peer subset, we see the largest difference between high spend and millennials', purpose: 'The purpose of this chart template is to provide an example of a line plot', structureNotes: 'The percentage of each high spenders, millennials, and all groups are shown as points in each of the four categories. These points of each group are connected by lines.', statisticalNotes: 'This chart is using dummy data', onChangeFunc: d => { this.onChangeFunc(d); }, elementsAreInterface: false, disableValidation: true, keyboardNavConfig: { disabled: false } }; @State() suppressEvents: boolean = false; @State() theWorstDataEver: any; smashIt: boolean = true; seriesLimit: number = 10; dataPoints: number = 24; hoverStyle: any = { color: '#d7d7d7', strokeWidth: 2 }; clickStyle: any = { color: '#FFC4C4', strokeWidth: 5 }; simpleColors: any = ['#FFC4C4', '#C4DAFF']; colorsBase: any = ['#f2f2f2', '#d7d7d7', '#bdbdbd', '#a3a3a3', '#898989', '#717171', '#595959', '#434343', '#2e2e2e']; selectedColor: string = '#00CF81'; hoveredColor: string = '#0068FF'; colorIndexes: any = {}; breakTestData: any = [ { ordinal: 'a', value: null, series: '1' }, { ordinal: 'a', value: 1, series: '1' }, { ordinal: 'b', value: 1, series: '1' }, { ordinal: 'c', value: 1, series: '1' }, { ordinal: 'd', value: 1, series: '1' }, { ordinal: 'e', value: 1, series: '1' }, { ordinal: 'f', value: 1, series: '1' }, { ordinal: 'g', value: null, series: '1' }, { ordinal: 'a', value: 2, series: '2' }, { ordinal: 'b', value: 2, series: '2' }, { ordinal: 'c', value: null, series: '2' }, { ordinal: 'd', value: null, series: '2' }, { ordinal: 'e', value: 2, series: '2' }, { ordinal: 'f', value: null, series: '2' }, { ordinal: 'g', value: 2, series: '2' } ]; dashTestData: any = [ { ordinal: 'a', value: 1, series: '1' }, { ordinal: 'b', value: 1, series: '1' }, { ordinal: 'a', value: 2, series: '2' }, { ordinal: 'b', value: 2, series: '2' }, { ordinal: 'a', value: 3, series: '3' }, { ordinal: 'b', value: 3, series: '3' }, { ordinal: 'a', value: 4, series: '4' }, { ordinal: 'b', value: 4, series: '4' }, { ordinal: 'a', value: 5, series: '5' }, { ordinal: 'b', value: 5, series: '5' }, { ordinal: 'a', value: 6, series: 'secondary' }, { ordinal: 'b', value: 6, series: 'secondary' } ]; collisionTestData: any = [ { ordinal: new Date('2016-01-01'), value: 100000, series: '1' }, { ordinal: new Date('2016-01-01'), value: 110000, series: '1' }, { ordinal: new Date('2016-01-01'), value: 120000, series: '1' }, { ordinal: new Date('2016-01-01'), value: 130000, series: '1' }, { ordinal: new Date('2016-01-01'), value: 100004, series: '1' }, { ordinal: new Date('2016-01-01'), value: 100005, series: '1' }, { ordinal: new Date('2016-01-01'), value: 100006, series: '1' }, { ordinal: new Date('2016-01-01'), value: 100007, series: '1' }, { ordinal: new Date('2016-01-01'), value: 100008, series: '1' }, { ordinal: new Date('2016-01-01'), value: 100009, series: '1' }, { ordinal: new Date('2016-01-01'), value: 100010, series: '1' }, { ordinal: new Date('2016-01-01'), value: 200010, series: '2' }, { ordinal: new Date('2016-01-01'), value: 500010, series: '3' }, { ordinal: new Date('2016-02-01'), value: 990000, series: '1' }, { ordinal: new Date('2016-02-01'), value: 965000, series: '2' }, { ordinal: new Date('2016-02-01'), value: 945000, series: '3' } ]; startData: any = [ { date: new Date('2016-01-01'), otherOrd: '1', otherCat: 'ABC', otherVal: 100, category: 'Card A', value: null }, { date: new Date('2016-02-01'), otherOrd: '2', otherCat: 'ABC', otherVal: 220, category: 'Card A', value: null }, { date: new Date('2016-03-01'), otherOrd: '3', otherCat: 'ABC', otherVal: 680, category: 'Card A', value: 8358837379 }, { date: new Date('2016-04-01'), otherOrd: '4', otherCat: 'ABC', otherVal: 923, category: 'Card A', value: 8334842966 }, { date: new Date('2016-05-01'), otherOrd: '5', otherCat: 'ABC', otherVal: 542, category: 'Card A', value: 8588600035 }, { date: new Date('2016-06-01'), otherOrd: '6', otherCat: 'ABC', otherVal: 452, category: 'Card A', value: 8484192554 }, { date: new Date('2016-07-01'), otherOrd: '7', otherCat: 'ABC', otherVal: 300, category: 'Card A', value: 8778636197 }, { date: new Date('2016-08-01'), otherOrd: '8', otherCat: 'ABC', otherVal: 200, category: 'Card A', value: 8811163096 }, { date: new Date('2016-09-01'), otherOrd: '9', otherCat: 'ABC', otherVal: 100, category: 'Card A', value: 8462148898 }, { date: new Date('2016-10-01'), otherOrd: '10', otherCat: 'ABC', otherVal: 100, category: 'Card A', value: 9051933407 }, { date: new Date('2016-11-01'), otherOrd: '11', otherCat: 'ABC', otherVal: 150, category: 'Card A', value: 8872849978 }, { date: new Date('2016-12-01'), otherOrd: '12', otherCat: 'ABC', otherVal: 150, category: 'Card A', value: 9709829820 }, { date: new Date('2017-01-01'), otherOrd: '13', otherCat: 'ABC', otherVal: 100, category: 'Card A', value: 7670994739 }, { date: new Date('2017-02-01'), otherOrd: '14', otherCat: 'ABC', otherVal: 100, category: 'Card A', value: 5670994739 }, { date: new Date('2016-01-01'), otherOrd: '1', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 6570994739 }, { date: new Date('2016-02-01'), otherOrd: '2', otherCat: 'DEF', otherVal: 250, category: 'Card B', value: 4628909842 }, { date: new Date('2016-03-01'), otherOrd: '3', otherCat: 'DEF', otherVal: 400, category: 'Card B', value: 4358837379 }, { date: new Date('2016-04-01'), otherOrd: '4', otherCat: 'DEF', otherVal: 500, category: 'Card B', value: 5534842966 }, { date: new Date('2016-05-01'), otherOrd: '5', otherCat: 'DEF', otherVal: 700, category: 'Card B', value: 4388600035 }, { date: new Date('2016-06-01'), otherOrd: '6', otherCat: 'DEF', otherVal: 800, category: 'Card B', value: 3484192554 }, { date: new Date('2016-07-01'), otherOrd: '7', otherCat: 'DEF', otherVal: 800, category: 'Card B', value: 3578636197 }, { date: new Date('2016-08-01'), otherOrd: '8', otherCat: 'DEF', otherVal: 500, category: 'Card B', value: 6411163096 }, { date: new Date('2016-09-01'), otherOrd: '9', otherCat: 'DEF', otherVal: 670, category: 'Card B', value: 5262148898 }, { date: new Date('2016-10-01'), otherOrd: '10', otherCat: 'DEF', otherVal: 850, category: 'Card B', value: 4651933407 }, { date: new Date('2016-11-01'), otherOrd: '11', otherCat: 'DEF', otherVal: 850, category: 'Card B', value: null }, { date: new Date('2016-12-01'), otherOrd: '12', otherCat: 'DEF', otherVal: 940, category: 'Card B', value: 5609829820 }, { date: new Date('2017-01-01'), otherOrd: '13', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 6570994739 }, { date: new Date('2017-02-01'), otherOrd: '14', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 5570994739 } ]; dataStorage: any = [ [ { date: new Date('2017-01-01'), otherOrd: '13', otherCat: 'ABC', otherVal: 100, category: 'Card A', value: 7670994739 }, { date: new Date('2017-02-01'), otherOrd: '14', otherCat: 'ABC', otherVal: 100, category: 'Card A', value: 5670994739 }, { date: new Date('2017-01-01'), otherOrd: '13', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 6570994739 }, { date: new Date('2017-02-01'), otherOrd: '14', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 5570994739 } ], this.startData, [ { date: new Date('2016-01-01'), otherOrd: '1', otherCat: 'ABC', otherVal: 800, category: 'Card A', value: 7670994739 }, { date: new Date('2016-02-01'), otherOrd: '2', otherCat: 'ABC', otherVal: 500, category: 'Card A', value: 7628909842 }, { date: new Date('2016-03-01'), otherOrd: '3', otherCat: 'ABC', otherVal: 670, category: 'Card A', value: 8358837379 }, { date: new Date('2016-04-01'), otherOrd: '4', otherCat: 'ABC', otherVal: 100, category: 'Card A', value: 8334842966 }, { date: new Date('2016-05-01'), otherOrd: '5', otherCat: 'ABC', otherVal: 220, category: 'Card A', value: 8588600035 }, { date: new Date('2016-06-01'), otherOrd: '6', otherCat: 'ABC', otherVal: 680, category: 'Card A', value: 8484192554 }, { date: new Date('2016-07-01'), otherOrd: '7', otherCat: 'ABC', otherVal: 923, category: 'Card A', value: 8778636197 }, { date: new Date('2016-08-01'), otherOrd: '8', otherCat: 'ABC', otherVal: 542, category: 'Card A', value: 8811163096 }, { date: new Date('2016-09-01'), otherOrd: '9', otherCat: 'ABC', otherVal: 452, category: 'Card A', value: 8462148898 }, { date: new Date('2016-10-01'), otherOrd: '10', otherCat: 'ABC', otherVal: 300, category: 'Card A', value: 9051933407 }, { date: new Date('2016-11-01'), otherOrd: '11', otherCat: 'ABC', otherVal: 200, category: 'Card A', value: null }, { date: new Date('2016-12-01'), otherOrd: '12', otherCat: 'ABC', otherVal: 100, category: 'Card A', value: 9709829820 }, { date: new Date('2016-01-01'), otherOrd: '1', otherCat: 'DEF', otherVal: 850, category: 'Card B', value: 6570994739 }, { date: new Date('2016-02-01'), otherOrd: '2', otherCat: 'DEF', otherVal: 850, category: 'Card B', value: 4628909842 }, { date: new Date('2016-03-01'), otherOrd: '3', otherCat: 'DEF', otherVal: 940, category: 'Card B', value: 4358837379 }, { date: new Date('2016-04-01'), otherOrd: '4', otherCat: 'DEF', otherVal: 100, category: 'Card B', value: 5534842966 }, { date: new Date('2016-05-01'), otherOrd: '5', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 4388600035 }, { date: new Date('2016-06-01'), otherOrd: '6', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 3484192554 }, { date: new Date('2016-07-01'), otherOrd: '7', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 3578636197 }, { date: new Date('2016-08-01'), otherOrd: '8', otherCat: 'DEF', otherVal: 250, category: 'Card B', value: 6411163096 }, { date: new Date('2016-09-01'), otherOrd: '9', otherCat: 'DEF', otherVal: 400, category: 'Card B', value: 5262148898 }, { date: new Date('2016-10-01'), otherOrd: '10', otherCat: 'DEF', otherVal: 500, category: 'Card B', value: 4651933407 }, { date: new Date('2016-11-01'), otherOrd: '11', otherCat: 'DEF', otherVal: 700, category: 'Card B', value: 6772849978 }, { date: new Date('2016-12-01'), otherOrd: '12', otherCat: 'DEF', otherVal: 800, category: 'Card B', value: 5609829820 } ], [ { date: new Date('2016-01-01'), otherOrd: '1', otherCat: 'ABC', otherVal: 800, category: 'Card A', value: 7670994739 }, { date: new Date('2016-02-01'), otherOrd: '2', otherCat: 'ABC', otherVal: 500, category: 'Card A', value: 7628909842 }, { date: new Date('2016-03-01'), otherOrd: '3', otherCat: 'ABC', otherVal: 670, category: 'Card A', value: 8358837379 }, { date: new Date('2016-04-01'), otherOrd: '4', otherCat: 'ABC', otherVal: 100, category: 'Card A', value: 8334842966 }, { date: new Date('2016-05-01'), otherOrd: '5', otherCat: 'ABC', otherVal: 220, category: 'Card A', value: 8588600035 }, { date: new Date('2016-06-01'), otherOrd: '6', otherCat: 'ABC', otherVal: 680, category: 'Card A', value: 8484192554 }, { date: new Date('2016-07-01'), otherOrd: '7', otherCat: 'ABC', otherVal: 923, category: 'Card A', value: 8778636197 }, { date: new Date('2016-08-01'), otherOrd: '8', otherCat: 'ABC', otherVal: 542, category: 'Card A', value: 8811163096 }, { date: new Date('2016-09-01'), otherOrd: '9', otherCat: 'ABC', otherVal: 452, category: 'Card A', value: 8462148898 }, { date: new Date('2016-10-01'), otherOrd: '10', otherCat: 'ABC', otherVal: 300, category: 'Card A', value: 9051933407 }, { date: new Date('2016-11-01'), otherOrd: '11', otherCat: 'ABC', otherVal: 200, category: 'Card A', value: 8872849978 }, { date: new Date('2016-12-01'), otherOrd: '12', otherCat: 'ABC', otherVal: 100, category: 'Card A', value: 9709829820 }, { date: new Date('2016-01-01'), otherOrd: '1', otherCat: 'DEF', otherVal: 850, category: 'Card B', value: 6570994739 }, { date: new Date('2016-02-01'), otherOrd: '2', otherCat: 'DEF', otherVal: 850, category: 'Card B', value: 4628909842 }, { date: new Date('2016-03-01'), otherOrd: '3', otherCat: 'DEF', otherVal: 940, category: 'Card B', value: 4358837379 }, { date: new Date('2016-04-01'), otherOrd: '4', otherCat: 'DEF', otherVal: 100, category: 'Card B', value: null }, { date: new Date('2016-05-01'), otherOrd: '5', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 4388600035 }, { date: new Date('2016-06-01'), otherOrd: '6', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 3484192554 }, { date: new Date('2016-07-01'), otherOrd: '7', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 3578636197 }, { date: new Date('2016-08-01'), otherOrd: '8', otherCat: 'DEF', otherVal: 250, category: 'Card B', value: 6411163096 }, { date: new Date('2016-09-01'), otherOrd: '9', otherCat: 'DEF', otherVal: 400, category: 'Card B', value: 5262148898 }, { date: new Date('2016-10-01'), otherOrd: '10', otherCat: 'DEF', otherVal: 500, category: 'Card B', value: 4651933407 }, { date: new Date('2016-12-01'), otherOrd: '12', otherCat: 'DEF', otherVal: 800, category: 'Card B', value: 5609829820 } ], [ { date: new Date('2016-01-01'), otherOrd: '1', otherCat: 'DEF', otherVal: 850, category: 'Card B', value: 6570994739 }, { date: new Date('2016-02-01'), otherOrd: '2', otherCat: 'DEF', otherVal: 850, category: 'Card B', value: 4628909842 }, { date: new Date('2016-03-01'), otherOrd: '3', otherCat: 'DEF', otherVal: 940, category: 'Card B', value: 4358837379 }, { date: new Date('2016-04-01'), otherOrd: '4', otherCat: 'DEF', otherVal: 100, category: 'Card B', value: 5534842966 }, { date: new Date('2016-05-01'), otherOrd: '5', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 4388600035 }, { date: new Date('2016-06-01'), otherOrd: '6', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 3484192554 }, { date: new Date('2016-07-01'), otherOrd: '7', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 3578636197 }, { date: new Date('2016-08-01'), otherOrd: '8', otherCat: 'DEF', otherVal: 250, category: 'Card B', value: 6411163096 }, { date: new Date('2016-09-01'), otherOrd: '9', otherCat: 'DEF', otherVal: 400, category: 'Card B', value: 5262148898 }, { date: new Date('2016-10-01'), otherOrd: '10', otherCat: 'DEF', otherVal: 500, category: 'Card B', value: 4651933407 }, { date: new Date('2016-11-01'), otherOrd: '11', otherCat: 'DEF', otherVal: 700, category: 'Card B', value: 6772849978 } ], [ { date: new Date('2016-01-01'), otherOrd: '1', otherCat: 'ABC', otherVal: 800, category: 'Card A', value: 7670994739 }, { date: new Date('2016-02-01'), otherOrd: '2', otherCat: 'ABC', otherVal: 500, category: 'Card A', value: 7628909842 }, { date: new Date('2016-03-01'), otherOrd: '3', otherCat: 'ABC', otherVal: 670, category: 'Card A', value: 8358837379 }, { date: new Date('2016-04-01'), otherOrd: '4', otherCat: 'ABC', otherVal: 100, category: 'Card A', value: 8334842966 }, { date: new Date('2016-05-01'), otherOrd: '5', otherCat: 'ABC', otherVal: 220, category: 'Card A', value: 8588600035 }, { date: new Date('2016-06-01'), otherOrd: '6', otherCat: 'ABC', otherVal: 680, category: 'Card A', value: 8484192554 }, { date: new Date('2016-07-01'), otherOrd: '7', otherCat: 'ABC', otherVal: 923, category: 'Card A', value: 8778636197 }, { date: new Date('2016-08-01'), otherOrd: '8', otherCat: 'ABC', otherVal: 542, category: 'Card A', value: 8811163096 }, { date: new Date('2016-09-01'), otherOrd: '9', otherCat: 'ABC', otherVal: 452, category: 'Card A', value: 8462148898 }, { date: new Date('2016-10-01'), otherOrd: '10', otherCat: 'ABC', otherVal: 300, category: 'Card A', value: 9051933407 }, { date: new Date('2016-11-01'), otherOrd: '11', otherCat: 'ABC', otherVal: 200, category: 'Card A', value: 8872849978 }, { date: new Date('2016-12-01'), otherOrd: '12', otherCat: 'ABC', otherVal: 100, category: 'Card A', value: 9709829820 }, { date: new Date('2016-01-01'), otherOrd: '1', otherCat: 'DEF', otherVal: 850, category: 'Card B', value: 6570994739 }, { date: new Date('2016-02-01'), otherOrd: '2', otherCat: 'DEF', otherVal: 850, category: 'Card B', value: 4628909842 }, { date: new Date('2016-03-01'), otherOrd: '3', otherCat: 'DEF', otherVal: 940, category: 'Card B', value: 4358837379 }, { date: new Date('2016-04-01'), otherOrd: '4', otherCat: 'DEF', otherVal: 100, category: 'Card B', value: 5534842966 }, { date: new Date('2016-05-01'), otherOrd: '5', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 4388600035 }, { date: new Date('2016-06-01'), otherOrd: '6', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 3484192554 }, { date: new Date('2016-07-01'), otherOrd: '7', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 3578636197 }, { date: new Date('2016-08-01'), otherOrd: '8', otherCat: 'DEF', otherVal: 250, category: 'Card B', value: 6411163096 }, { date: new Date('2016-09-01'), otherOrd: '9', otherCat: 'DEF', otherVal: 400, category: 'Card B', value: 5262148898 }, { date: new Date('2016-10-01'), otherOrd: '10', otherCat: 'DEF', otherVal: 500, category: 'Card B', value: 4651933407 }, { date: new Date('2016-11-01'), otherOrd: '11', otherCat: 'DEF', otherVal: 700, category: 'Card B', value: 6772849978 }, { date: new Date('2016-12-01'), otherOrd: '12', otherCat: 'DEF', otherVal: 800, category: 'Card B', value: 5609829820 } ], this.startData, [ { date: new Date('2016-01-01'), otherOrd: '1', otherCat: 'ABC', otherVal: 100, category: 'Card A', value: 7670994739 }, { date: new Date('2016-02-01'), otherOrd: '2', otherCat: 'ABC', otherVal: 220, category: 'Card A', value: 7628909842 }, { date: new Date('2016-03-01'), otherOrd: '3', otherCat: 'ABC', otherVal: 680, category: 'Card A', value: 8358837379 }, { date: new Date('2016-04-01'), otherOrd: '4', otherCat: 'ABC', otherVal: 923, category: 'Card A', value: 8334842966 }, { date: new Date('2016-05-01'), otherOrd: '5', otherCat: 'ABC', otherVal: 542, category: 'Card A', value: 8588600035 }, { date: new Date('2016-06-01'), otherOrd: '6', otherCat: 'ABC', otherVal: 452, category: 'Card A', value: 8484192554 }, { date: new Date('2016-07-01'), otherOrd: '7', otherCat: 'ABC', otherVal: 300, category: 'Card A', value: 8778636197 }, { date: new Date('2016-08-01'), otherOrd: '8', otherCat: 'ABC', otherVal: 200, category: 'Card A', value: 8811163096 }, { date: new Date('2016-09-01'), otherOrd: '9', otherCat: 'ABC', otherVal: 100, category: 'Card A', value: 8462148898 }, { date: new Date('2016-10-01'), otherOrd: '10', otherCat: 'ABC', otherVal: 100, category: 'Card A', value: 9051933407 }, { date: new Date('2016-11-01'), otherOrd: '11', otherCat: 'ABC', otherVal: 150, category: 'Card A', value: 8872849978 }, { date: new Date('2016-12-01'), otherOrd: '12', otherCat: 'ABC', otherVal: 150, category: 'Card A', value: 9709829820 }, { date: new Date('2017-01-01'), otherOrd: '13', otherCat: 'ABC', otherVal: 100, category: 'Card A', value: 7670994739 }, { date: new Date('2017-02-01'), otherOrd: '14', otherCat: 'ABC', otherVal: 100, category: 'Card A', value: 6670994739 }, { date: new Date('2016-01-01'), otherOrd: '1', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 6570994739 }, { date: new Date('2016-02-01'), otherOrd: '2', otherCat: 'DEF', otherVal: 250, category: 'Card B', value: 4628909842 }, { date: new Date('2016-03-01'), otherOrd: '3', otherCat: 'DEF', otherVal: 400, category: 'Card B', value: 4358837379 }, { date: new Date('2016-04-01'), otherOrd: '4', otherCat: 'DEF', otherVal: 500, category: 'Card B', value: 5534842966 }, { date: new Date('2016-05-01'), otherOrd: '5', otherCat: 'DEF', otherVal: 700, category: 'Card B', value: 4388600035 }, { date: new Date('2016-06-01'), otherOrd: '6', otherCat: 'DEF', otherVal: 800, category: 'Card B', value: 3484192554 }, { date: new Date('2016-07-01'), otherOrd: '7', otherCat: 'DEF', otherVal: 800, category: 'Card B', value: 3578636197 }, { date: new Date('2016-08-01'), otherOrd: '8', otherCat: 'DEF', otherVal: 500, category: 'Card B', value: 6411163096 }, { date: new Date('2016-09-01'), otherOrd: '9', otherCat: 'DEF', otherVal: 670, category: 'Card B', value: 5262148898 }, { date: new Date('2016-10-01'), otherOrd: '10', otherCat: 'DEF', otherVal: 850, category: 'Card B', value: 4651933407 }, { date: new Date('2016-11-01'), otherOrd: '11', otherCat: 'DEF', otherVal: 850, category: 'Card B', value: 6772849978 }, { date: new Date('2016-12-01'), otherOrd: '12', otherCat: 'DEF', otherVal: 940, category: 'Card B', value: 5609829820 }, { date: new Date('2017-01-01'), otherOrd: '13', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 6570994739 }, { date: new Date('2017-02-01'), otherOrd: '14', otherCat: 'DEF', otherVal: 150, category: 'Card B', value: 2570994739 } ] ]; secondStorage: any; clickedIndex: number = -1; hoveredIndex: number = -1; @Element() appEl: HTMLElement; componentWillLoad() { this.theWorstDataEver = this.generateTheWorstDataEver(); } componentWillUpdate() { // console.log("will update", this.clickElement); } generateTheWorstDataEver() { const newNightmare = []; const startTime = new Date().getTime(); let s = 0; for (s = 0; s < this.seriesLimit; s++) { let i = 0; for (i = 0; i < this.dataPoints; i++) { const ordinal = i && i !== this.dataPoints - 1 ? new Date(startTime + Math.random() * 10000000000) : i ? new Date(startTime + 10000000000) : new Date(startTime); newNightmare.push({ ordinal, series: s, value: !(this.smashIt && !i && !s) ? Math.random() : 10 }); } } return newNightmare; } prepareColor(d, e) { // first check if array already has click color... if so then we remove! const colorArray = [...this.colors]; const index = this.colorIndexes[d.category]; if (e === 'selectedColor') { if (this.clickedIndex === index) { colorArray[index] = index === this.hoveredIndex ? this.hoveredColor : this.colorsBase[index]; this.clickedIndex = -1; } else { colorArray[this.clickedIndex] = this.colorsBase[this.clickedIndex]; this.clickedIndex = index; colorArray[index] = this[e]; } } else if (this.hoveredIndex === index) { colorArray[index] = this.colorsBase[index]; this.hoveredIndex = -1; } else { this.hoveredIndex = index; colorArray[index] = this[e]; } this.colors = colorArray; } onClickFunc = ev => { const d = ev.detail; if (d) { const newClicks = [...this.clickElement]; const keys = Object.keys(d); const index = this.clickElement.findIndex(o => { let conditionsMet = 0; keys.forEach(key => { conditionsMet += o[key] === d[key] ? 1 : 0; }); return conditionsMet && conditionsMet === keys.length; }); if (index > -1) { newClicks.splice(index, 1); } else { newClicks.push(d); } this.clickElement = newClicks; } }; onHoverFunc = ev => { this.hoverElement = ev.detail; }; onMouseOut = () => { this.hoverElement = ''; }; secondaryHoverFunc(ev) { const d = ev.detail; this.seriesLabel = { visible: true, placement: 'right' }; this.secondaryHover = d; this.prepareColor(d, 'hoveredColor'); } secondaryMouseOut() { const duplicate = { ...this.secondaryHover }; this.secondaryHover = ''; this.secondaryHoverElement = ''; this.seriesLabel = { visible: false, placement: 'right' }; // const colorArray = [...this.colors]; // const index = colorArray.indexOf(this.hoveredColor); // colorArray.splice(index, 1, this.colorsBase[index]); this.prepareColor(duplicate, 'hoveredColor'); // this.colors = colorArray; } onChangeFunc(d) { console.log(d); } changeData() { this.stateTrigger = this.stateTrigger < this.dataStorage.length - 1 ? this.stateTrigger + 1 : 0; } backData() { this.stateTrigger = this.stateTrigger > 0 ? this.stateTrigger - 1 : this.dataStorage.length - 1; } changeAccessElements() { this.accessibility = { ...this.accessibility, elementsAreInterface: !this.accessibility.elementsAreInterface }; } changeKeyNav() { const keyboardNavConfig = { disabled: !this.accessibility.keyboardNavConfig.disabled }; this.accessibility = { ...this.accessibility, keyboardNavConfig }; } toggleSuppress() { this.suppressEvents = !this.suppressEvents; } changeOrdinalAccessor() { this.ordinalAccessor = this.ordinalAccessor !== 'date' ? 'date' : 'otherOrd'; } changeValueAccessor() { this.valueAccessor = this.valueAccessor !== 'value' ? 'value' : 'otherVal'; } changeSeriesAccessor() { this.seriesAccessor = this.seriesAccessor !== 'category' ? 'category' : 'otherCat'; } changeHeight() { this.height = this.height !== 600 ? 600 : 300; } changeInteractionKeys() { this.interactionKeys = this.interactionKeys[0] !== this.seriesAccessor ? [this.seriesAccessor] : [this.ordinalAccessor]; } changeSecondaryLine() { this.secondaryKey = this.secondaryKey !== 'Card B' ? 'Card B' : 'Card A'; } changeSecondaryLineOpacity() { this.secondaryOpacity = this.secondaryOpacity !== 1 ? 1 : 0.5; } changeSecondaryLineDL() { this.secondaryDataLabel = this.secondaryDataLabel !== true ? true : false; } changeSecondaryLineSL() { this.secondarySeriesLabel = this.secondarySeriesLabel !== true ? true : false; } changeTooltipLabel() { this.tooltipLabel = this.tooltipLabel.labelAccessor[0] !== this.ordinalAccessor ? { format: ['%b'], labelAccessor: [this.ordinalAccessor], labelTitle: [this.ordinalAccessor] } : { format: '', labelAccessor: [this.seriesAccessor], labelTitle: [this.seriesAccessor] }; // @State() colors: any = [ : 'otherGroup'; } changeUnit() { this.unit = this.unit !== 'month' ? 'month' : 'year'; } toggleAnimations() { this.animations = { disabled: !this.animations.disabled }; } render() { this.data = this.dataStorage[this.stateTrigger]; let nightmareColors = []; this.theWorstDataEver.forEach(_ => nightmareColors.push('#222222')); return ( <div> {/* <line-chart mainTitle={'Dash Patterns'} subTitle={'5 Dash Patterns + Secondary Line Pattern'} data={this.dashTestData} ordinalAccessor="ordinal" seriesAccessor="series" valueAccessor="value" uniqueID="dash-test" colors={['#222222', '#222222', '#222222', '#222222', '#222222', '#222222']} dataLabel={{ visible: false }} secondaryLines={{ keys: ['secondary'], opacity: 1, showDataLabel: true, showSeriesLabel: true }} margin={{ top: 5, left: 0, bottom: 36, right: 5 }} padding={{ top: 5, left: 36, bottom: 36, right: 5 }} showBaselineX={false} yAxis={{ visible: false, gridVisible: false }} xAxis={{ visible: false, gridVisible: false }} /> */} {/* <line-chart mainTitle={'Broken Lines'} subTitle={'Testing broken lines with non-date ordinal data'} data={this.breakTestData} ordinalAccessor="ordinal" seriesAccessor="series" valueAccessor="value" uniqueID="broken-line-test" colors={['#222222', '#222222', '#222222', '#222222', '#222222', '#222222']} dataLabel={{ visible: true, placement: 'middle', labelAccessor: 'value', format: '0,0.[00]a' }} // dataLabel={{ visible: true }} showBaselineX={false} yAxis={{ visible: false, gridVisible: true }} xAxis={{ visible: false, gridVisible: false }} /> */} {/* <line-chart mainTitle={'Collision Testing'} subTitle={'testing collision use cases'} data={this.collisionTestData} ordinalAccessor="ordinal" seriesAccessor="series" valueAccessor="value" uniqueID="collision-test" dataLabel={{ visible: true, placement: 'middle', labelAccessor: 'value', format: '0,0.[00]a' }} width={600} height={350} colors={['#222222', '#222222', '#222222', '#222222', '#222222', '#222222']} margin={{ top: 5, left: 5, bottom: 5, right: 5 }} padding={{ top: 20, left: 40, bottom: 20, right: 40 }} dotRadius={3} showBaselineX={false} yAxis={{ visible: false, gridVisible: false }} xAxis={{ visible: false, gridVisible: false }} /> <line-chart mainTitle={'XTREME Collision Testing'} subTitle={'use the state/variables in the app tsx to make it a nightmare'} data={this.theWorstDataEver} ordinalAccessor="ordinal" seriesAccessor="series" valueAccessor="value" uniqueID="horrific" width={800} height={400} colors={nightmareColors} dataLabel={{ visible: true, placement: 'middle', labelAccessor: 'value', format: '0,0.[00]a' }} margin={{ top: 5, left: 0, bottom: 36, right: 50 }} padding={{ top: 20, left: 36, bottom: 36, right: 20 }} showBaselineX={false} yAxis={{ visible: false, gridVisible: false }} xAxis={{ visible: false, gridVisible: false }} /> */} <button onClick={() => { this.changeAccessElements(); }} > change elementsAreInterface </button> <button onClick={() => { this.toggleSuppress(); }} > toggle event suppression </button> <button onClick={() => { this.changeKeyNav(); }} > toggle keyboard nav </button> <button onClick={() => { this.backData(); }} > back data </button> <button onClick={() => { this.changeData(); }} > change data </button> <button onClick={() => { this.changeOrdinalAccessor(); }} > change ordinalAccessor </button> <button onClick={() => { this.changeValueAccessor(); }} > change valueAccessor </button> <button onClick={() => { this.changeSeriesAccessor(); }} > change seriesAccessor </button> <button onClick={() => { this.changeHeight(); }} > change height </button> <button onClick={() => { this.changeInteractionKeys(); }} > change interaction keys </button> <button onClick={() => { this.changeSecondaryLine(); }} > change secondary line </button> <button onClick={() => { this.changeSecondaryLineOpacity(); }} > change secondary line opacity </button> <button onClick={() => { this.changeSecondaryLineDL(); }} > toggle secondary line labels </button> <button onClick={() => { this.changeSecondaryLineSL(); }} > toggle secondary series labels </button> <button onClick={() => { this.changeTooltipLabel(); }} > change tooltip </button> <button onClick={() => { this.changeUnit(); }} > change unit </button> <button onClick={() => { this.toggleAnimations(); }} > toggle animations </button> <line-chart // Chart Attributes (1/7) mainTitle={'Line Chart in app'} // animationConfig={this.animations} subTitle={'example'} height={this.height} width={600} // xAxis={{ visible: true, gridVisible: true, label: 'Quarter', unit: this.unit, format: '%b' }} // yAxis={{ visible: true, gridVisible: true, label: 'Volume', format: '0[.][0][0]a' }} // minValueOverride={-2000000} // padding={{ // top: 20, // left: 60, // right: 80, // bottom: 50 // }} data={this.data} ordinalAccessor={this.ordinalAccessor} valueAccessor={this.valueAccessor} seriesAccessor={this.seriesAccessor} dataLabel={this.dataLabel} seriesLabel={this.seriesLabel} // legend={{ visible: false, labels: [], interactive: true }} // colorPalette={'sequential_grey'} cursor={'pointer'} strokeWidth={2} colors={this.simpleColors} // colors={['sec_orange', 'sec_blue', 'sec_orange', 'supp_green', 'sec_blue']} hoverOpacity={0.2} hoverStyle={this.hoverStyle} clickStyle={this.clickStyle} clickHighlight={this.clickElement} hoverHighlight={this.hoverElement} interactionKeys={this.interactionKeys} // referenceLines= {[{label:'Average',labelPlacementHorizontal:'right',labelPlacementVertical:'bottom',value:7300000000}]} secondaryLines={{ keys: [this.secondaryKey], opacity: this.secondaryOpacity, showDataLabel: this.secondaryDataLabel, showSeriesLabel: this.secondarySeriesLabel }} onHoverFunc={this.onHoverFunc} onClickFunc={this.onClickFunc} onMouseOutFunc={this.onMouseOut} showTooltip={false} tooltipLabel={this.tooltipLabel} // annotations={this.annotations} accessibility={this.accessibility} suppressEvents={this.suppressEvents} dotRadius={5} /> </div> ); } }
the_stack
import debounce from 'lodash/debounce'; import { action, observable } from 'mobx'; import { Injectable, Autowired } from '@opensumi/di'; import { View, CommandRegistry, ViewContextKeyRegistry, IContextKeyService, localize, IContextKey, OnEvent, WithEventBus, ResizeEvent, DisposableCollection, ContextKeyChangeEvent, Event, Emitter, IScopedContextKeyService, } from '@opensumi/ide-core-browser'; import { RESIZE_LOCK } from '@opensumi/ide-core-browser/lib/components'; import { SplitPanelManager, SplitPanelService, } from '@opensumi/ide-core-browser/lib/components/layout/split-panel.service'; import { LayoutState, LAYOUT_STATE } from '@opensumi/ide-core-browser/lib/layout/layout-state'; import { AbstractContextMenuService, AbstractMenuService, IMenu, IMenuRegistry, ICtxMenuRenderer, MenuId, } from '@opensumi/ide-core-browser/lib/menu/next'; import { IProgressService } from '@opensumi/ide-core-browser/lib/progress'; import { ViewCollapseChangedEvent } from '../../common'; export interface SectionState { collapsed: boolean; hidden: boolean; size?: number; nextSize?: number; } @Injectable({ multiple: true }) export class AccordionService extends WithEventBus { @Autowired() protected splitPanelManager: SplitPanelManager; @Autowired(AbstractMenuService) protected menuService: AbstractMenuService; @Autowired(AbstractContextMenuService) protected ctxMenuService: AbstractContextMenuService; @Autowired(IMenuRegistry) protected menuRegistry: IMenuRegistry; @Autowired(CommandRegistry) private commandRegistry: CommandRegistry; @Autowired(ICtxMenuRenderer) private readonly contextMenuRenderer: ICtxMenuRenderer; @Autowired() private viewContextKeyRegistry: ViewContextKeyRegistry; @Autowired(IContextKeyService) private contextKeyService: IContextKeyService; @Autowired() private layoutState: LayoutState; @Autowired(IProgressService) private progressService: IProgressService; protected splitPanelService: SplitPanelService; // 用于强制显示功能的contextKey private forceRevealContextKeys = new Map<string, { when: string; key: IContextKey<boolean> }>(); // 所有View的when条件集合 private viewWhenContextkeys = new Set<string>(); // 带contextKey且已渲染的视图 private appendedViewSet = new Set<string>(); // 所有带contextKey视图 private viewsWithContextKey = new Set<View>(); @observable.shallow views: View[] = []; @observable state: { [viewId: string]: SectionState } = {}; // 提供给Mobx强刷,有没有更好的办法? @observable forceUpdate = 0; rendered = false; private headerSize: number; private minSize: number; private menuId = `accordion/${this.containerId}`; private toDispose: Map<string, DisposableCollection> = new Map(); private topViewKey: IContextKey<string>; private scopedCtxKeyService: IScopedContextKeyService; private beforeAppendViewEmitter = new Emitter<string>(); public onBeforeAppendViewEvent = this.beforeAppendViewEmitter.event; private afterAppendViewEmitter = new Emitter<string>(); public onAfterAppendViewEvent = this.afterAppendViewEmitter.event; private afterDisposeViewEmitter = new Emitter<string>(); public onAfterDisposeViewEvent = this.afterDisposeViewEmitter.event; constructor(public containerId: string, private noRestore?: boolean) { super(); this.splitPanelService = this.splitPanelManager.getService(containerId); this.scopedCtxKeyService = this.contextKeyService.createScoped(); this.scopedCtxKeyService.createKey('triggerWithSection', true); this.menuRegistry.registerMenuItem(this.menuId, { command: { id: this.registerGlobalToggleCommand(), label: localize('layout.view.hide', '隐藏'), }, group: '0_global', when: 'triggerWithSection == true', }); this.viewContextKeyRegistry.afterContextKeyServiceRegistered(this.containerId, (contextKeyService) => { this.topViewKey = contextKeyService!.createKey('view', containerId); setTimeout(() => { // 由于tabbar.service会立刻设置view,这边要等下一个event loop this.popViewKeyIfOnlyOneViewVisible(); }); }); this.addDispose( Event.debounce<ContextKeyChangeEvent, boolean>( this.contextKeyService.onDidChangeContext, (last, event) => last || event.payload.affectsSome(this.viewWhenContextkeys), 50, )((e) => e && this.handleContextKeyChange(), this), ); this.listenWindowResize(); } tryUpdateResize() { this.doUpdateResize(); } restoreState() { if (this.noRestore) { return; } const defaultState: { [containerId: string]: SectionState } = {}; this.visibleViews.forEach((view) => (defaultState[view.id] = { collapsed: false, hidden: false })); const restoredState = this.layoutState.getState(LAYOUT_STATE.getContainerSpace(this.containerId), defaultState); if (restoredState !== defaultState) { this.state = restoredState; } this.popViewKeyIfOnlyOneViewVisible(); this.restoreSize(); this.rendered = true; } // 调用时需要保证dom可见 restoreSize() { // 计算存储总高度与当前窗口总高度差,加到最后一个展开的面板 let availableSize = this.splitPanelService.rootNode?.clientHeight || 0; let finalUncollapsedIndex: number | undefined; this.visibleViews.forEach((view, index) => { const savedState = this.state[view.id]; if (savedState.collapsed) { this.setSize(index, 0, false, true); availableSize -= this.headerSize; } else if (!savedState.collapsed && savedState.size) { this.setSize(index, savedState.size, false, true); availableSize -= savedState.size; finalUncollapsedIndex = index; } }); if (finalUncollapsedIndex) { this.setSize( finalUncollapsedIndex, this.state[this.visibleViews[finalUncollapsedIndex].id].size! + availableSize, ); } } initConfig(config: { headerSize: number; minSize: number }) { const { headerSize, minSize } = config; this.headerSize = headerSize; this.minSize = minSize; } private registerContextService(viewId: string) { let scopedCtxKey = this.viewContextKeyRegistry.getContextKeyService(viewId); if (!scopedCtxKey) { scopedCtxKey = this.contextKeyService.createScoped(); scopedCtxKey.createKey('view', viewId); this.viewContextKeyRegistry.registerContextKeyService(viewId, scopedCtxKey); } return scopedCtxKey; } getSectionToolbarMenu(viewId: string): IMenu { // 确保在较早获取菜单时已经注册了 ScopedContextKeyService const scopedCtxKey = this.registerContextService(viewId); const menu = this.menuService.createMenu(MenuId.ViewTitle, scopedCtxKey); const existingView = this.views.find((view) => view.id === viewId); if (existingView) { existingView.titleMenu = menu; } return menu; } appendView(view: View, replace?: boolean) { if (this.appendedViewSet.has(view.id) && !replace) { return; } const disposables = new DisposableCollection(); disposables.push(this.progressService.registerProgressIndicator(view.id)); // 已存在的viewId直接替换 const existIndex = this.views.findIndex((item) => item.id === view.id); if (existIndex !== -1) { this.views[existIndex] = Object.assign({}, this.views[existIndex], view); return; } // 带contextKey视图需要先判断下 if (view.when) { this.viewsWithContextKey.add(view); // 强制显示的contextKey const forceRevealExpr = this.createRevealContextKey(view.id); this.fillKeysInWhenExpr(this.viewWhenContextkeys, view.when); // 如果不匹配则跳过 if (!this.contextKeyService.match(view.when) && !this.contextKeyService.match(forceRevealExpr)) { return; } this.appendedViewSet.add(view.id); } this.beforeAppendViewEmitter.fire(view.id); const index = this.views.findIndex((value) => (value.priority || 0) < (view.priority || 0)); this.views.splice(index === -1 ? this.views.length : index, 0, view); // 创建 scopedContextKeyService this.registerContextService(view.id); disposables.push( this.menuRegistry.registerMenuItem(this.menuId, { command: { id: this.registerVisibleToggleCommand(view.id, disposables), label: view.name || view.id, }, group: '1_widgets', // TODO order计算 }), ); this.toDispose.set(view.id, disposables); this.popViewKeyIfOnlyOneViewVisible(); this.afterAppendViewEmitter.fire(view.id); } disposeView(viewId: string) { const existIndex = this.views.findIndex((item) => item.id === viewId); if (existIndex > -1) { this.views.splice(existIndex, 1); } const disposable = this.toDispose.get(viewId); if (disposable) { disposable.dispose(); } this.appendedViewSet.delete(viewId); this.popViewKeyIfOnlyOneViewVisible(); this.afterDisposeViewEmitter.fire(viewId); } revealView(viewId: string) { const target = this.forceRevealContextKeys.get(viewId); if (target) { target.key.set(true); } } disposeAll() { this.views = []; this.toDispose.forEach((disposable) => { disposable.dispose(); }); } @OnEvent(ResizeEvent) protected onResize(e: ResizeEvent) { // 监听来自resize组件的事件 if (e.payload.slotLocation) { if (this.state[e.payload.slotLocation]) { const id = e.payload.slotLocation; // get dom of viewId const sectionDom = document.getElementById(id); if (sectionDom) { this.state[id].size = sectionDom.clientHeight; this.storeState(); } } } } private doUpdateResize = debounce(() => { let largestViewId: string | undefined; Object.keys(this.state).forEach((id) => { if (!(this.state[id].hidden || this.state[id].collapsed)) { if (!largestViewId) { largestViewId = id; } else { if ((this.state[id].size || 0) > (this.state[largestViewId].size || 0)) { largestViewId = id; } } } }); if (largestViewId && this.splitPanelService.isVisible && this.expandedViews.length > 1) { // 需要过滤掉没有实际注册的视图 const diffSize = this.splitPanelService.rootNode!.clientHeight - this.getPanelFullHeight(); if (diffSize) { this.state[largestViewId].size! += diffSize; this.toggleOpen(largestViewId!, false); } } }, 16); private getPanelFullHeight(ignoreViewId?: string) { return Object.keys(this.state) .filter((viewId) => this.views.find((item) => item.id === viewId) && viewId !== ignoreViewId) .reduce( (acc, id) => acc + (this.state[id].collapsed ? this.headerSize : this.state[id].hidden ? 0 : this.state[id].size!), 0, ); } protected listenWindowResize() { window.addEventListener('resize', this.doUpdateResize); this.addDispose({ dispose: () => window.removeEventListener('resize', this.doUpdateResize) }); } private createRevealContextKey(viewId: string) { const forceRevealKey = `forceShow.${viewId}`; this.forceRevealContextKeys.set(viewId, { when: `${forceRevealKey} == true`, key: this.contextKeyService.createKey(forceRevealKey, false), }); this.viewWhenContextkeys.add(forceRevealKey); return `${forceRevealKey} == true`; } protected storeState = debounce(() => { if (this.noRestore || !this.rendered) { return; } this.layoutState.setState(LAYOUT_STATE.getContainerSpace(this.containerId), this.state); }, 200); private registerGlobalToggleCommand() { const commandId = `view-container.hide.${this.containerId}`; this.commandRegistry.registerCommand( { id: commandId, }, { execute: ({ viewId }: { viewId: string }) => { this.doToggleView(viewId); }, isEnabled: () => this.visibleViews.length > 1, }, ); return commandId; } private registerVisibleToggleCommand(viewId: string, disposables: DisposableCollection): string { const commandId = `view-container.hide.${viewId}`; disposables.push( this.commandRegistry.registerCommand( { id: commandId, }, { execute: ({ forceShow }: { forceShow?: boolean } = {}) => { this.doToggleView(viewId, forceShow); }, isToggled: () => { const state = this.getViewState(viewId); return !state.hidden; }, isEnabled: () => { const state = this.getViewState(viewId); return state.hidden || this.visibleViews.length > 1; }, }, ), ); return commandId; } protected doToggleView(viewId: string, forceShow?: boolean) { const state = this.getViewState(viewId); let nextState: boolean; if (forceShow === undefined) { nextState = !state.hidden; } else { nextState = !forceShow; } state.hidden = nextState; this.popViewKeyIfOnlyOneViewVisible(); this.storeState(); } popViewKeyIfOnlyOneViewVisible() { if (!this.topViewKey) { // 可能还没初始化 return; } const visibleViews = this.visibleViews; if (visibleViews.length === 1) { this.topViewKey.set(visibleViews[0].id); } else { this.topViewKey.reset(); } } toggleViewVisibility(viewId: string, show?: boolean) { this.doToggleView(viewId, show); } get visibleViews(): View[] { return this.views.filter((view) => { const viewState = this.getViewState(view.id); return !viewState.hidden; }); } get expandedViews(): View[] { return this.views.filter((view) => { const viewState = this.state[view.id]; return !viewState || (viewState && !viewState.hidden && !viewState.collapsed); }); } @action toggleOpen(viewId: string, collapsed: boolean) { const index = this.visibleViews.findIndex((view) => view.id === viewId); if (index > -1) { this.doToggleOpen(viewId, collapsed, index, true); } } @action.bound handleSectionClick(viewId: string, collapsed: boolean, index: number) { this.doToggleOpen(viewId, collapsed, index); } @action.bound handleContextMenu(event: React.MouseEvent, viewId?: string) { event.preventDefault(); const menus = this.ctxMenuService.createMenu({ id: this.menuId, config: { args: [{ viewId }] }, contextKeyService: viewId ? this.viewContextKeyRegistry.getContextKeyService(viewId) : undefined, }); const menuNodes = menus.getGroupedMenuNodes(); menus.dispose(); this.contextMenuRenderer.show({ menuNodes: menuNodes[1], anchor: { x: event.clientX, y: event.clientY, }, }); } public getViewState(viewId: string) { let viewState = this.state[viewId]; const view = this.views.find((item) => item.id === viewId); if (!viewState) { this.state[viewId] = { collapsed: view?.collapsed || false, hidden: view?.hidden || false }; viewState = this.state[viewId]!; } return viewState; } protected doToggleOpen(viewId: string, collapsed: boolean, index: number, noAnimation?: boolean) { const viewState = this.getViewState(viewId); viewState.collapsed = collapsed; let sizeIncrement: number; if (collapsed) { sizeIncrement = this.setSize(index, 0, false, noAnimation); } else { // 仅有一个视图展开时独占 sizeIncrement = this.setSize( index, this.expandedViews.length === 1 ? this.getAvailableSize() : viewState.size || this.minSize, false, noAnimation, ); } // 下方视图被影响的情况下,上方视图不会同时变化,该情况会在sizeIncrement=0上体现 // 从视图下方最后一个展开的视图起依次减去对应的高度 for (let i = this.visibleViews.length - 1; i > index; i--) { if (this.getViewState(this.visibleViews[i].id).collapsed !== true) { sizeIncrement = this.setSize(i, sizeIncrement, true, noAnimation); } else { this.setSize(i, 0, false, noAnimation); } } // 找到视图上方首个展开的视图减去对应的高度 for (let i = index - 1; i >= 0; i--) { if ((this.state[this.visibleViews[i].id] || {}).collapsed !== true) { sizeIncrement = this.setSize(i, sizeIncrement, true, noAnimation); } else { this.setSize(i, 0, false, noAnimation); } } this.eventBus.fire( new ViewCollapseChangedEvent({ viewId, collapsed: viewState.collapsed, }), ); } protected setSize(index: number, targetSize: number, isIncrement?: boolean, noAnimation?: boolean): number { const fullHeight = this.splitPanelService.rootNode!.clientHeight; const panel = this.splitPanelService.panels[index]; if (!noAnimation) { panel.classList.add('resize-ease'); } if (!targetSize && !isIncrement) { targetSize = this.headerSize; panel.classList.add(RESIZE_LOCK); } else { panel.classList.remove(RESIZE_LOCK); } // clientHeight会被上次展开的元素挤掉 const prevSize = panel.clientHeight; const viewState = this.getViewState(this.visibleViews[index].id); let calcTargetSize: number = targetSize; // 视图即将折叠时、受其他视图影响尺寸变化时、主动展开时、resize时均需要存储尺寸信息 if (isIncrement) { calcTargetSize = Math.max(prevSize - targetSize, this.minSize); } if (index === this.expandedViews.length - 1) { // 最后一个视图需要兼容最大高度超出总视图高度及最大高度不足总视图高度的情况 if (calcTargetSize + index * this.minSize > fullHeight) { calcTargetSize -= calcTargetSize + index * this.minSize - fullHeight; } else { const restSize = this.getPanelFullHeight(this.visibleViews[index].id); if (calcTargetSize + restSize < fullHeight) { calcTargetSize += fullHeight - (calcTargetSize + restSize); } } } if (this.rendered) { let toSaveSize: number; if (targetSize === this.headerSize) { // 当前视图即将折叠且不是唯一展开的视图时,存储当前高度 toSaveSize = prevSize; } else { toSaveSize = calcTargetSize; } if (toSaveSize !== this.headerSize) { // 视图折叠高度不做存储 viewState.size = toSaveSize; } } this.storeState(); viewState.nextSize = calcTargetSize; if (!noAnimation) { setTimeout(() => { // 动画 0.1s,保证结束后移除 panel.classList.remove('resize-ease'); }, 200); } return isIncrement ? calcTargetSize - (prevSize - targetSize) : targetSize - prevSize; } protected getAvailableSize() { const fullHeight = this.splitPanelService.rootNode!.clientHeight; return fullHeight - (this.visibleViews.length - 1) * this.headerSize; } private handleContextKeyChange() { Array.from(this.viewsWithContextKey.values()).forEach((view) => { if ( this.contextKeyService.match(view.when) || this.contextKeyService.match(this.forceRevealContextKeys.get(view.id)!.when) ) { this.appendView(view); } else { this.disposeView(view.id); } }); } private fillKeysInWhenExpr(set: Set<string>, when?: string) { const keys = this.contextKeyService.getKeysInWhen(when); keys.forEach((key) => { set.add(key); }); } } export const AccordionServiceFactory = Symbol('AccordionServiceFactory');
the_stack
"use strict"; import { StatusBarItem, window } from "vscode"; import { QueryHierarchyItem, WorkItemType } from "vso-node-api/interfaces/WorkItemTrackingInterfaces"; import { Logger } from "../helpers/logger"; import { SimpleWorkItem, WorkItemTrackingService } from "../services/workitemtracking"; import { Telemetry } from "../services/telemetry"; import { TeamServerContext} from "../contexts/servercontext"; import { BaseQuickPickItem, VsCodeUtils, WorkItemQueryQuickPickItem } from "../helpers/vscodeutils"; import { TelemetryEvents, WitQueries, WitTypes } from "../helpers/constants"; import { Strings } from "../helpers/strings"; import { Utils } from "../helpers/utils"; import { IPinnedQuery } from "../helpers/settings"; import { BaseClient } from "./baseclient"; export class WitClient extends BaseClient { private _pinnedQuery: IPinnedQuery; private _myQueriesFolder: string; constructor(context: TeamServerContext, pinnedQuery: IPinnedQuery, statusBarItem: StatusBarItem) { super(context, statusBarItem); this._pinnedQuery = pinnedQuery; } //Opens a browser to a new work item given the item type, title and assigned to public CreateNewItem(itemType: string, taskTitle: string): void { this.logTelemetryForWorkItem(itemType); Logger.LogInfo("Work item type is " + itemType); const newItemUrl: string = WorkItemTrackingService.GetNewWorkItemUrl(this._serverContext.RepoInfo.TeamProjectUrl, itemType, taskTitle, this.getUserName(this._serverContext)); Logger.LogInfo("New Work Item Url: " + newItemUrl); Utils.OpenUrl(newItemUrl); } //Creates a new work item based on a single line of selected text public async CreateNewWorkItem(taskTitle: string): Promise<void> { try { Telemetry.SendEvent(TelemetryEvents.OpenNewWorkItem); const selectedType: BaseQuickPickItem = await window.showQuickPick(this.getWorkItemTypes(), { matchOnDescription: true, placeHolder: Strings.ChooseWorkItemType }); if (selectedType) { Telemetry.SendEvent(TelemetryEvents.OpenNewWorkItem); Logger.LogInfo("Selected work item type is " + selectedType.label); const newItemUrl: string = WorkItemTrackingService.GetNewWorkItemUrl(this._serverContext.RepoInfo.TeamProjectUrl, selectedType.label, taskTitle, this.getUserName(this._serverContext)); Logger.LogInfo("New Work Item Url: " + newItemUrl); Utils.OpenUrl(newItemUrl); } } catch (err) { this.handleWitError(err, WitClient.GetOfflinePinnedQueryStatusText(), false, "Error creating new work item"); } } //Navigates to a work item chosen from the results of a user-selected "My Queries" work item query //This method first displays the queries under "My Queries" and, when one is chosen, displays the associated work items. //If a work item is chosen, it is opened in the web browser. public async ShowMyWorkItemQueries(): Promise<void> { try { Telemetry.SendEvent(TelemetryEvents.ShowMyWorkItemQueries); const query: WorkItemQueryQuickPickItem = await window.showQuickPick(this.getMyWorkItemQueries(), { matchOnDescription: false, placeHolder: Strings.ChooseWorkItemQuery }); if (query) { Telemetry.SendEvent(TelemetryEvents.ViewWorkItems); Logger.LogInfo("Selected query is " + query.label); Logger.LogInfo("Getting work items for query..."); const workItem: BaseQuickPickItem = await window.showQuickPick(this.getMyWorkItems(this._serverContext.RepoInfo.TeamProject, query.wiql), { matchOnDescription: true, placeHolder: Strings.ChooseWorkItem }); if (workItem) { let url: string = undefined; if (workItem.id === undefined) { Telemetry.SendEvent(TelemetryEvents.OpenAdditionalQueryResults); url = WorkItemTrackingService.GetMyQueryResultsUrl(this._serverContext.RepoInfo.TeamProjectUrl, this._myQueriesFolder, query.label); } else { Telemetry.SendEvent(TelemetryEvents.ViewWorkItem); url = WorkItemTrackingService.GetEditWorkItemUrl(this._serverContext.RepoInfo.TeamProjectUrl, workItem.id); } Logger.LogInfo("Work Item Url: " + url); Utils.OpenUrl(url); } } } catch (err) { this.handleWitError(err, WitClient.GetOfflinePinnedQueryStatusText(), false, "Error showing work item queries"); } } public async ShowPinnedQueryWorkItems(): Promise<void> { Telemetry.SendEvent(TelemetryEvents.ViewPinnedQueryWorkItems); try { const queryText: string = await this.getPinnedQueryText(); await this.showWorkItems(queryText); } catch (err) { this.handleWitError(err, WitClient.GetOfflinePinnedQueryStatusText(), false, "Error showing pinned query work items"); } } public async ShowMyWorkItems(): Promise<void> { Telemetry.SendEvent(TelemetryEvents.ViewMyWorkItems); try { await this.showWorkItems(WitQueries.MyWorkItems); } catch (err) { this.handleWitError(err, WitClient.GetOfflinePinnedQueryStatusText(), false, "Error showing my work items"); } } public async ChooseWorkItems(): Promise<string[]> { Logger.LogInfo("Getting work items to choose from..."); try { const query: string = await this.getPinnedQueryText(); //gets either MyWorkItems, queryText or wiql of queryPath of PinnedQuery // TODO: There isn't a way to do a multi select pick list right now, but when there is we should change this to use it. const workItem: BaseQuickPickItem = await window.showQuickPick(this.getMyWorkItems(this._serverContext.RepoInfo.TeamProject, query), { matchOnDescription: true, placeHolder: Strings.ChooseWorkItem }); if (workItem) { return ["#" + workItem.id + " - " + workItem.description]; } else { return []; } } catch (err) { this.handleWitError(err, WitClient.GetOfflinePinnedQueryStatusText(), false, "Error showing my work items in order to choose (associate)"); return []; } } private async showWorkItems(wiql: string): Promise<void> { Logger.LogInfo("Getting work items..."); const workItem: BaseQuickPickItem = await window.showQuickPick(this.getMyWorkItems(this._serverContext.RepoInfo.TeamProject, wiql), { matchOnDescription: true, placeHolder: Strings.ChooseWorkItem }); if (workItem) { let url: string = undefined; if (workItem.id === undefined) { Telemetry.SendEvent(TelemetryEvents.OpenAdditionalQueryResults); url = WorkItemTrackingService.GetWorkItemsBaseUrl(this._serverContext.RepoInfo.TeamProjectUrl); } else { Telemetry.SendEvent(TelemetryEvents.ViewWorkItem); url = WorkItemTrackingService.GetEditWorkItemUrl(this._serverContext.RepoInfo.TeamProjectUrl, workItem.id); } Logger.LogInfo("Work Item Url: " + url); Utils.OpenUrl(url); } } public async GetPinnedQueryResultCount(): Promise<number> { try { Logger.LogInfo("Running pinned work item query to get count (" + this._serverContext.RepoInfo.TeamProject + ")..."); const queryText: string = await this.getPinnedQueryText(); const svc: WorkItemTrackingService = new WorkItemTrackingService(this._serverContext); return svc.GetQueryResultCount(this._serverContext.RepoInfo.TeamProject, queryText); } catch (err) { this.handleWitError(err, WitClient.GetOfflinePinnedQueryStatusText(), false, "Error getting pinned query result count"); } } private async getPinnedQueryText(): Promise<string> { const promise: Promise<string> = new Promise<string>(async (resolve, reject) => { try { if (this._pinnedQuery.queryText && this._pinnedQuery.queryText.length > 0) { resolve(this._pinnedQuery.queryText); } else if (this._pinnedQuery.queryPath && this._pinnedQuery.queryPath.length > 0) { Logger.LogInfo("Getting my work item query (" + this._serverContext.RepoInfo.TeamProject + ")..."); Logger.LogInfo("QueryPath: " + this._pinnedQuery.queryPath); const svc: WorkItemTrackingService = new WorkItemTrackingService(this._serverContext); const queryItem: QueryHierarchyItem = await svc.GetWorkItemQuery(this._serverContext.RepoInfo.TeamProject, this._pinnedQuery.queryPath); resolve(queryItem.wiql); } } catch (err) { reject(err); } }); return promise; } private async getMyWorkItemQueries(): Promise<WorkItemQueryQuickPickItem[]> { const queries: WorkItemQueryQuickPickItem[] = []; const svc: WorkItemTrackingService = new WorkItemTrackingService(this._serverContext); Logger.LogInfo("Getting my work item queries (" + this._serverContext.RepoInfo.TeamProject + ")..."); const hierarchyItems: QueryHierarchyItem[] = await svc.GetWorkItemHierarchyItems(this._serverContext.RepoInfo.TeamProject); Logger.LogInfo("Retrieved " + hierarchyItems.length + " hierarchyItems"); hierarchyItems.forEach((folder) => { if (folder && folder.isFolder === true && folder.isPublic === false) { // Because "My Queries" is localized and there is no API to get the name of the localized // folder, we need to save off the localized name when constructing URLs. this._myQueriesFolder = folder.name; if (folder.hasChildren === true) { //Gets all of the queries under "My Queries" and gets their name and wiql for (let index: number = 0; index < folder.children.length; index++) { queries.push({ id: folder.children[index].id, label: folder.children[index].name, description: "", wiql: folder.children[index].wiql }); } } } }); return queries; } private async getMyWorkItems(teamProject: string, wiql: string): Promise<BaseQuickPickItem[]> { const workItems: BaseQuickPickItem[] = []; const svc: WorkItemTrackingService = new WorkItemTrackingService(this._serverContext); Logger.LogInfo("Getting my work items (" + this._serverContext.RepoInfo.TeamProject + ")..."); const simpleWorkItems: SimpleWorkItem[] = await svc.GetWorkItems(teamProject, wiql); Logger.LogInfo("Retrieved " + simpleWorkItems.length + " work items"); simpleWorkItems.forEach((wi) => { workItems.push({ label: wi.label, description: wi.description, id: wi.id}); }); if (simpleWorkItems.length === WorkItemTrackingService.MaxResults) { workItems.push({ id: undefined, label: Strings.BrowseAdditionalWorkItems, description: Strings.BrowseAdditionalWorkItemsDescription }); } return workItems; } private getUserName(context: TeamServerContext): string { let userName: string = undefined; Logger.LogDebug("UserCustomDisplayName: " + context.UserInfo.CustomDisplayName); Logger.LogDebug("UserProviderDisplayName: " + context.UserInfo.ProviderDisplayName); if (context.UserInfo.CustomDisplayName !== undefined) { userName = context.UserInfo.CustomDisplayName; } else { userName = context.UserInfo.ProviderDisplayName; } Logger.LogDebug("User is " + userName); return userName; } private async getWorkItemTypes(): Promise<BaseQuickPickItem[]> { const svc: WorkItemTrackingService = new WorkItemTrackingService(this._serverContext); const types: WorkItemType[] = await svc.GetWorkItemTypes(this._serverContext.RepoInfo.TeamProject); const workItemTypes: BaseQuickPickItem[] = []; types.forEach((type) => { workItemTypes.push({ label: type.name, description: type.description, id: undefined }); }); workItemTypes.sort((t1, t2) => { return (t1.label.localeCompare(t2.label)); }); return workItemTypes; } private handleWitError(err: Error, offlineText: string, polling: boolean, infoMessage?: string): void { if (err.message.includes("Failed to find api location for area: wit id:")) { Telemetry.SendEvent(TelemetryEvents.UnsupportedWitServerVersion); const msg: string = Strings.UnsupportedWitServerVersion; Logger.LogError(msg); if (this._statusBarItem !== undefined) { this._statusBarItem.text = `$(bug) $(x)`; this._statusBarItem.tooltip = msg; this._statusBarItem.command = undefined; //Clear the existing command } if (!polling) { VsCodeUtils.ShowErrorMessage(msg); } } else { this.handleError(err, offlineText, polling, infoMessage); } } private logTelemetryForWorkItem(wit: string): void { switch (wit) { case WitTypes.Bug: Telemetry.SendEvent(TelemetryEvents.OpenNewBug); break; case WitTypes.Task: Telemetry.SendEvent(TelemetryEvents.OpenNewTask); break; default: break; } } public PollPinnedQuery(): void { this.GetPinnedQueryResultCount().then((numberOfItems) => { this._statusBarItem.tooltip = Strings.ViewYourPinnedQuery; this._statusBarItem.text = WitClient.GetPinnedQueryStatusText(numberOfItems.toString()); }).catch((err) => { this.handleWitError(err, WitClient.GetOfflinePinnedQueryStatusText(), true, "Failed to get pinned query count during polling"); }); } public static GetOfflinePinnedQueryStatusText() : string { return `$(bug) ???`; } public static GetPinnedQueryStatusText(total?: string) : string { if (!total) { return `$(bug) $(dash)`; } return `$(bug) ${total.toString()}`; } }
the_stack
/** -2400 to -2499 is webcam error code */ declare enum EnumDWT_ErrorCode { /** All error from directshow sdk */ WCERR_SYSTEM = -2400, /** Create ICreateDevEnum interface failed. */ WCERR_FAIL_ICREATEDEVENUM = -2401, /** Create IEnumMoniker interface failed. */ WCERR_FAIL_IENUMMONIKER = -2402, /** The camera doesn't support IAMVideoProcAmp interface. */ WCERR_NOT_IAMVIDEOPROPERTY = -2403, /** The camera doesn't support IAMCameraControl interface. */ WCERR_NOT_IAMCAMERACONTROL = -2404, /** The property doesn't support auto capability. */ WCERR_NOT_AUTOPROPERTY = -2405, /** No webcam device is found. */ WCERR_NO_DEVICE = -2406, /** Could not get video window interface */ WCERR_FAIL_VIDEOWINDOW = -2407, /** Could not create filter graph. */ WCERR_FAIL_FILTERGRAPH = -2408, /** Could not create SampleGrabber (isqedit.all registered?). */ WCERR_FAIL_SAMPLEGRABBER = -2409, /** Unable to make NULL renderer */ WCERR_NULLRENDER = -2410, /** Can't add the filter to graph */ WCERR_FAIL_ADDFILTER = -2411, /** Can't build the graph */ WCERR_FAIL_BUILDGRAPH = -2412, /** Failed to register filter graph with ROT. */ WCERR_FAIL_REGFILTERGRAPH = -2413, /** Time out */ WCERR_GRAB_TIMEOUT = -2414 } /** Specifies the video rotate mode on a video capture device. */ declare enum EnumDWT_VideoRotateMode { /** Don't rotate */ VRM_NONE = 0, /** 90 deg Clockwise */ VRM_90_DEGREES_CLOCKWISE = 1, /** 180 deg Clockwise */ VRM_180_DEGREES_CLOCKWISE = 2, /** 270 deg Clockwise */ VRM_270_DEGREES_CLOCKWISE = 3, /** Flip */ VRM_FLIP_VERTICAL = 4, /** Mirror */ VRM_FLIP_HORIZONTAL = 5 } /** Specifies video properties on a video capture device. */ declare enum EnumDWT_VideoProperty { /** Specifies the brightness, also called the black level. For NTSC, the value is expressed in IRE units * 100. * For non-NTSC sources, the units are arbitrary, with zero representing blanking and 10,000 representing pure white. * Values range from -10,000 to 10,000. */ VP_BRIGHTNESS = 0, /** Specifies the contrast, expressed as gain factor * 100. Values range from zero to 10,000. */ VP_CONTRAST = 1, /** Specifies the hue, in degrees * 100. Values range from -180,000 to 180,000 (-180 to +180 degrees). */ VP_HUE = 2, /** Specifies the saturation. Values range from 0 to 10,000. */ VP_SATURATION = 3, /** Specifies the sharpness. Values range from 0 to 100. */ VP_SHARPNESS = 4, /** Specifies the gamma, as gamma * 100. Values range from 1 to 500. */ VP_GAMMA = 5, /** Specifies the color enable setting. The possible values are 0 (off) and 1 (on). */ VP_COLORENABLE = 6, /** Specifies the white balance, as a color temperature in degrees Kelvin. The range of values depends on the device. */ VP_WHITEBALANCE = 7, /** Specifies the backlight compensation setting. Possible values are 0 (off) and 1 (on). */ VP_BACKLIGHTCOMPENSATION = 8, /** Specifies the gain adjustment. Zero is normal. Positive values are brighter and negative values are darker. * The range of values depends on the device. */ VP_GAIN = 9 } /** Specifies a setting on a camera. */ declare enum EnumDWT_CameraControlProperty { /** Specifies the camera's pan setting, in degrees. Values range from -180 to +180, with the default set to zero. * Positive values are clockwise from the origin (the camera rotates clockwise when viewed from above), * and negative values are counterclockwise from the origin. */ CCP_PAN = 0, /** Specifies the camera's tilt setting, in degrees. Values range from -180 to +180, with the default set to zero. * Positive values point the imaging plane up, and negative values point the imaging plane down. */ CCP_TILT = 1, /** Specifies the camera's roll setting, in degrees. Values range from -180 to +180, with the default set to zero. * Positive values cause a clockwise rotation of the camera along the image-viewing axis, and negative values cause a counterclockwise rotation of the camera. */ CCP_ROLL = 2, /** Specifies the camera's zoom setting, in millimeters. Values range from 10 to 600, and the default is specific to the device. */ CCP_ZOOM = 3, /** Specifies the exposure setting, in log base 2 seconds. In other words, for values less than zero, the exposure time is 1/2^n seconds, * and for values zero or above, the exposure time is 2^n seconds. For example: * Value Seconds * -3 1/8 * -2 1/4 * -1 1/2 * 0 1 * 1 2 * 2 4 */ CCP_EXPOSURE = 4, /** Specifies the camera's iris setting, in units of fstop* 10. */ CCP_IRIS = 5, /** Specifies the camera's focus setting, as the distance to the optimally focused target, in millimeters. * The range and default value are specific to the device. */ CCP_FOCUS = 6 } interface WebcamMediaType { GetCount(): number; Get(index: number): string; GetCurrent(): string; } interface WebcamResolution { GetCount(): number; Get(index: number): string; GetCurrent(): string; } interface WebcamFrameRate { GetCount(): number; Get(index: number): string; GetCurrent(): string; } interface CameraControlMoreSetting { GetMinValue(): number; GetMaxValue(): number; GetSteppingDelta(): number; GetDefaultValue(): number; GetIfAuto(): boolean; } interface CameraControlSetting { GetValue(): number; GetIfAuto(): boolean; } interface VideoPropertyMoreSetting { GetMinValue(): number; GetMaxValue(): number; GetSteppingDelta(): number; GetDefaultValue(): number; GetIfAuto(): boolean; } interface VideoPropertySetting { GetValue(): number; GetIfAuto(): boolean; } /** * @class */ interface Webcam { IsModuleInstalled(): boolean; GetFramePartURL(): string; GetFrameURL(): string; /** * Download and install webcam add-on on the local system. * @method Dynamsoft.WebTwain#Download * @param {string} remoteFile:string specifies the value of which frame to get. * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. * @return {boolean} */ Download(remoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: () => void): void; /** * Return supported webcam source names. * @method Dynamsoft.WebTwain#GetSourceList * @return {string array} */ GetSourceList(): string[]; /** * Select the source with the specified name. * @method Dynamsoft.WebTwain#SelectSource * @param {string} strSourceName The source name. * @return {boolean} */ SelectSource(strSourceName: string): boolean; /** * Close the selected source and release the webcam. * @method Dynamsoft.WebTwain#CloseSource * @return {boolean} */ CloseSource(): boolean; /** * Show video stream in a specified container * @method Dynamsoft.WebTwain#StopVideo * @param {WebTwain} DWObject Specifies the WebTwain Object. * @param {number} quality Specifies the quality of each frame in the video stream. Only valid for the HTML5 edition. * @param {function} onFrameCaptured callback of the operation to capture * @return {void} */ PlayVideo(DWObject: WebTwain, quality: number, onFrameCaptured: () => void): void; /** * Stop the video stream in the specified container * @method Dynamsoft.WebTwain#StopVideo * @return {boolean} */ StopVideo(): boolean; /** * Capture image from the specified webcam. * @method Dynamsoft.WebTwain#CaptureImage * @param {function} OnCaptureSuccess The function to call when the capture succeeds. Please refer to the function prototype OnCaptureSuccess. * @param {function} OnCaptureError The function to call when the capture fails. Please refer to the function prototype OnCaptureError. * @return {void} */ CaptureImage(OnCaptureSuccess: () => void, OnCaptureError: () => void): void; /** * Returns the media type for a camera. * @method Dynamsoft.WebTwain#GetMediaType * @return {class MediaType} */ GetMediaType(): WebcamMediaType; /** * Returns the count in the media type list. * @method Dynamsoft.WebTwain#GetResolution * @return {class Resolution} */ GetResolution(): WebcamResolution; /** * Returns the frame rate for a camera. * @method Dynamsoft.WebTwain#GetFrameRate * @return {class FrameRate} */ GetFrameRate(): WebcamFrameRate; /** * Set the media type of the current selected source by the value. * @method Dynamsoft.WebTwain#SetMediaType * @param {string} value The new media type value. * @return {boolean} */ SetMediaType(value: string): boolean; /** * Set the resolution of the current camera source. * @method Dynamsoft.WebTwain#SetResolution * @param {string} value The new resolution value. * @return {boolean} */ SetResolution(value: string): boolean; /** * Set current frame rate. * @method Dynamsoft.WebTwain#SetFrameRate * @param {number} value The new frame rate value. * @return {boolean} */ SetFrameRate(value: number): boolean; /** * Gets the current setting of a video property. * @method Dynamsoft.WebTwain#GetVideoPropertySetting * @param {EnumDWT_VideoProperty} property The property. * @return {class VideoPropertySetting} */ GetVideoPropertySetting(property: EnumDWT_VideoProperty): VideoPropertySetting; /** * Gets the range and default value of a specified video property. * @method Dynamsoft.WebTwain#GetVideoPropertyMoreSetting * @param {EnumDWT_VideoProperty} property The property. * @return {class VideoPropertyMoreSetting} */ GetVideoPropertyMoreSetting(property: EnumDWT_VideoProperty): VideoPropertyMoreSetting; /** * Gets the current setting of a camera property. * @method Dynamsoft.WebTwain#GetCameraControlPropertySetting * @param {EnumDWT_CameraControlProperty} property The property. * @return {class CameraControlPropertySetting} */ GetCameraControlPropertySetting(property: EnumDWT_CameraControlProperty): CameraControlSetting; /** * Gets the range and default value of a specified camera property. * @method Dynamsoft.WebTwain#GetVideoPropertyMoreSetting * @param {EnumDWT_CameraControlProperty} property The property. * @return {class CameraControlPropertyMoreSetting} */ GetCameraControlPropertyMoreSetting(property: EnumDWT_CameraControlProperty): CameraControlMoreSetting; /** * Sets video quality for a specified property. * @method Dynamsoft.WebTwain#SetVideoPropertySetting * @param {EnumDWT_VideoProperty} property The property. * @param {number} value The new value of the property. * @param {boolean} auto The desired control setting, whether the setting is controlled manually or automatically. * @return {boolean} */ SetVideoPropertySetting(property: EnumDWT_VideoProperty, value: number, auto: boolean): boolean; /** * Sets video rotate mode. * @method Dynamsoft.WebTwain#SetVideoRotateMode * @param {EnumDWT_VideoRotateMode} enumAngle The rotate angle. * @return {boolean} */ SetVideoRotateMode(enumAngle: EnumDWT_VideoRotateMode): boolean; /** * Sets a specified property on the camera. * @method Dynamsoft.WebTwain#SetCameraControlPropertySetting * @param {EnumDWT_CameraControlProperty} property The property. * @param {number} value The new value of the property. * @param {boolean} auto The desired control setting, whether the setting is controlled manually or automatically. * @return {boolean} */ SetCameraControlPropertySetting(property: EnumDWT_CameraControlProperty, value: number, auto: boolean): boolean; } interface DynamsoftWebTwainAddon { Webcam: Webcam; }
the_stack
import { ChunkedArray } from '../../../mol-data/util'; import { Encoding, EncodedData } from './encoding'; import { classifyIntArray } from './classifier'; import { TypedIntArray, TypedFloatArray } from '../../../mol-util/type-helpers'; export interface ArrayEncoder { and(f: ArrayEncoding.Provider): ArrayEncoder, encode(data: ArrayLike<any>): EncodedData } export class ArrayEncoderImpl implements ArrayEncoder { and(f: ArrayEncoding.Provider) { return new ArrayEncoderImpl(this.providers.concat([f])); } encode(data: ArrayLike<any>): EncodedData { const encoding: Encoding[] = []; for (const p of this.providers) { const t = p(data); if (!t.encodings.length) { throw new Error('Encodings must be non-empty.'); } data = t.data; for (const e of t.encodings) { encoding.push(e); } } if (!(data instanceof Uint8Array)) { throw new Error('The encoding must result in a Uint8Array. Fix your encoding chain.'); } return { encoding, data }; } constructor(private providers: ArrayEncoding.Provider[]) { } } export namespace ArrayEncoder { export function by(f: ArrayEncoding.Provider): ArrayEncoder { return new ArrayEncoderImpl([f]); } export function fromEncoding(encoding: Encoding[]) { let e = by(getProvider(encoding[0])); for (let i = 1; i < encoding.length; i++) e = e.and(getProvider(encoding[i])); return e; } function getProvider(e: Encoding): ArrayEncoding.Provider { switch (e.kind) { case 'ByteArray': return ArrayEncoding.byteArray; case 'FixedPoint': return ArrayEncoding.fixedPoint(e.factor); case 'IntervalQuantization': return ArrayEncoding.intervalQuantizaiton(e.min, e.max, e.numSteps); case 'RunLength': return ArrayEncoding.runLength; case 'Delta': return ArrayEncoding.delta; case 'IntegerPacking': return ArrayEncoding.integerPacking; case 'StringArray': return ArrayEncoding.stringArray; } } } export namespace ArrayEncoding { export type TypedArrayCtor = { new(size: number): ArrayLike<number> & { buffer: ArrayBuffer, byteLength: number, byteOffset: number, BYTES_PER_ELEMENT: number } } export interface Result { encodings: Encoding[], data: any } export type Provider = (data: any) => Result export function by(f: Provider): ArrayEncoder { return new ArrayEncoderImpl([f]); } function uint8(data: Uint8Array): Result { return { encodings: [{ kind: 'ByteArray', type: Encoding.IntDataType.Uint8 }], data }; } function int8(data: Int8Array): Result { return { encodings: [{ kind: 'ByteArray', type: Encoding.IntDataType.Int8 }], data: new Uint8Array(data.buffer, data.byteOffset) }; } const writers = { [Encoding.IntDataType.Int16]: function (v: DataView, i: number, a: number) { v.setInt16(2 * i, a, true); }, [Encoding.IntDataType.Uint16]: function (v: DataView, i: number, a: number) { v.setUint16(2 * i, a, true); }, [Encoding.IntDataType.Int32]: function (v: DataView, i: number, a: number) { v.setInt32(4 * i, a, true); }, [Encoding.IntDataType.Uint32]: function (v: DataView, i: number, a: number) { v.setUint32(4 * i, a, true); }, [Encoding.FloatDataType.Float32]: function (v: DataView, i: number, a: number) { v.setFloat32(4 * i, a, true); }, [Encoding.FloatDataType.Float64]: function (v: DataView, i: number, a: number) { v.setFloat64(8 * i, a, true); } }; const byteSizes = { [Encoding.IntDataType.Int16]: 2, [Encoding.IntDataType.Uint16]: 2, [Encoding.IntDataType.Int32]: 4, [Encoding.IntDataType.Uint32]: 4, [Encoding.FloatDataType.Float32]: 4, [Encoding.FloatDataType.Float64]: 8 }; export function byteArray(data: TypedFloatArray | TypedIntArray) { const type = Encoding.getDataType(data); if (type === Encoding.IntDataType.Int8) return int8(data as Int8Array); else if (type === Encoding.IntDataType.Uint8) return uint8(data as Uint8Array); const result = new Uint8Array(data.length * byteSizes[type]); const w = writers[type]; const view = new DataView(result.buffer); for (let i = 0, n = data.length; i < n; i++) { w(view, i, data[i]); } return { encodings: [<Encoding.ByteArray>{ kind: 'ByteArray', type }], data: result }; } function _fixedPoint(data: TypedFloatArray, factor: number): Result { const srcType = Encoding.getDataType(data) as Encoding.FloatDataType; const result = new Int32Array(data.length); for (let i = 0, n = data.length; i < n; i++) { result[i] = Math.round(data[i] * factor); } return { encodings: [{ kind: 'FixedPoint', factor, srcType }], data: result }; } export function fixedPoint(factor: number): Provider { return data => _fixedPoint(data as TypedFloatArray, factor); } function _intervalQuantizaiton(data: TypedFloatArray, min: number, max: number, numSteps: number, arrayType: new (size: number) => TypedIntArray): Result { const srcType = Encoding.getDataType(data) as Encoding.FloatDataType; if (!data.length) { return { encodings: [{ kind: 'IntervalQuantization', min, max, numSteps, srcType }], data: new Int32Array(0) }; } if (max < min) { const t = min; min = max; max = t; } const delta = (max - min) / (numSteps - 1); const output = new arrayType(data.length); for (let i = 0, n = data.length; i < n; i++) { const v = data[i]; if (v <= min) output[i] = 0; else if (v >= max) output[i] = numSteps - 1; else output[i] = (Math.round((v - min) / delta)) | 0; } return { encodings: [{ kind: 'IntervalQuantization', min, max, numSteps, srcType }], data: output }; } export function intervalQuantizaiton(min: number, max: number, numSteps: number, arrayType: new (size: number) => TypedIntArray = Int32Array): Provider { return data => _intervalQuantizaiton(data as TypedFloatArray, min, max, numSteps, arrayType); } export function runLength(data: TypedIntArray): Result { let srcType = Encoding.getDataType(data) as Encoding.IntDataType; if (srcType === void 0) { data = new Int32Array(data); srcType = Encoding.IntDataType.Int32; } if (!data.length) { return { encodings: [{ kind: 'RunLength', srcType, srcSize: 0 }], data: new Int32Array(0) }; } // calculate output size let fullLength = 2; for (let i = 1, il = data.length; i < il; i++) { if (data[i - 1] !== data[i]) { fullLength += 2; } } const output = new Int32Array(fullLength); let offset = 0; let runLength = 1; for (let i = 1, il = data.length; i < il; i++) { if (data[i - 1] !== data[i]) { output[offset] = data[i - 1]; output[offset + 1] = runLength; runLength = 1; offset += 2; } else { ++runLength; } } output[offset] = data[data.length - 1]; output[offset + 1] = runLength; return { encodings: [{ kind: 'RunLength', srcType, srcSize: data.length }], data: output }; } export function delta(data: Int8Array | Int16Array | Int32Array): Result { if (!Encoding.isSignedIntegerDataType(data)) { throw new Error('Only signed integer types can be encoded using delta encoding.'); } let srcType = Encoding.getDataType(data) as Encoding.IntDataType; if (srcType === void 0) { data = new Int32Array(data); srcType = Encoding.IntDataType.Int32; } if (!data.length) { return { encodings: [{ kind: 'Delta', origin: 0, srcType }], data: new (data as any).constructor(0) }; } const output = new (data as any).constructor(data.length); const origin = data[0]; output[0] = data[0]; for (let i = 1, n = data.length; i < n; i++) { output[i] = data[i] - data[i - 1]; } output[0] = 0; return { encodings: [{ kind: 'Delta', origin, srcType }], data: output }; } function isSigned(data: Int32Array) { for (let i = 0, n = data.length; i < n; i++) { if (data[i] < 0) return true; } return false; } function packingSize(data: Int32Array, upperLimit: number) { const lowerLimit = -upperLimit - 1; let size = 0; for (let i = 0, n = data.length; i < n; i++) { const value = data[i]; if (value === 0) { size += 1; } else if (value > 0) { size += Math.ceil(value / upperLimit); if (value % upperLimit === 0) size += 1; } else { size += Math.ceil(value / lowerLimit); if (value % lowerLimit === 0) size += 1; } } return size; } function determinePacking(data: Int32Array): { isSigned: boolean, size: number, bytesPerElement: number } { const signed = isSigned(data); const size8 = signed ? packingSize(data, 0x7F) : packingSize(data, 0xFF); const size16 = signed ? packingSize(data, 0x7FFF) : packingSize(data, 0xFFFF); if (data.length * 4 < size16 * 2) { // 4 byte packing is the most effective return { isSigned: signed, size: data.length, bytesPerElement: 4 }; } else if (size16 * 2 < size8) { // 2 byte packing is the most effective return { isSigned: signed, size: size16, bytesPerElement: 2 }; } else { // 1 byte packing is the most effective return { isSigned: signed, size: size8, bytesPerElement: 1 }; }; } function _integerPacking(data: Int32Array, packing: { isSigned: boolean, size: number, bytesPerElement: number }): Result { const upperLimit = packing.isSigned ? (packing.bytesPerElement === 1 ? 0x7F : 0x7FFF) : (packing.bytesPerElement === 1 ? 0xFF : 0xFFFF); const lowerLimit = -upperLimit - 1; const n = data.length; const packed = packing.isSigned ? packing.bytesPerElement === 1 ? new Int8Array(packing.size) : new Int16Array(packing.size) : packing.bytesPerElement === 1 ? new Uint8Array(packing.size) : new Uint16Array(packing.size); let j = 0; for (let i = 0; i < n; i++) { let value = data[i]; if (value >= 0) { while (value >= upperLimit) { packed[j] = upperLimit; ++j; value -= upperLimit; } } else { while (value <= lowerLimit) { packed[j] = lowerLimit; ++j; value -= lowerLimit; } } packed[j] = value; ++j; } const result = byteArray(packed); return { encodings: [{ kind: 'IntegerPacking', byteCount: packing.bytesPerElement, isUnsigned: !packing.isSigned, srcSize: n }, result.encodings[0] ], data: result.data }; } /** * Packs Int32 array. The packing level is determined automatically to either 1-, 2-, or 4-byte words. */ export function integerPacking(data: Int32Array): Result { // if (!(data instanceof Int32Array)) { // throw new Error('Integer packing can only be applied to Int32 data.'); // } const packing = determinePacking(data); if (packing.bytesPerElement === 4) { // no packing done, Int32 encoding will be used return byteArray(data); } return _integerPacking(data, packing); } export function stringArray(data: string[]): Result { const map: any = Object.create(null); const strings: string[] = []; const output = new Int32Array(data.length); const offsets = ChunkedArray.create<number>(Int32Array, 1, Math.min(1024, data.length < 32 ? data.length + 1 : Math.round(data.length / 8) + 1)); ChunkedArray.add(offsets, 0); let accLength = 0; let i = 0; for (const s of data) { // handle null strings. if (s === null || s === void 0) { output[i++] = -1; continue; } let index = map[s]; if (index === void 0) { // increment the length accLength += s.length; // store the string and index index = strings.length; strings[index] = s; map[s] = index; // write the offset ChunkedArray.add(offsets, accLength); } output[i++] = index; } const offsetArray = ChunkedArray.compact(offsets); const offsetEncoding = classifyIntArray(offsetArray); const encodedOddsets = offsetEncoding.encode(offsetArray); const dataEncoding = classifyIntArray(output); const encodedData = dataEncoding.encode(output); return { encodings: [{ kind: 'StringArray', dataEncoding: encodedData.encoding, stringData: strings.join(''), offsetEncoding: encodedOddsets.encoding, offsets: encodedOddsets.data }], data: encodedData.data }; } }
the_stack
'use strict'; export * from './config'; import { ConfigurationChangeEvent, ConfigurationScope, ConfigurationTarget, Event, EventEmitter, ExtensionContext, workspace, } from 'vscode'; import { Config } from './config'; import { Objects } from './system'; const configPrefix = 'gitlens'; export interface ConfigurationWillChangeEvent { change: ConfigurationChangeEvent; transform?(e: ConfigurationChangeEvent): ConfigurationChangeEvent; } export class Configuration { static configure(context: ExtensionContext): void { context.subscriptions.push( workspace.onDidChangeConfiguration(configuration.onConfigurationChanged, configuration), ); } private _onDidChange = new EventEmitter<ConfigurationChangeEvent>(); get onDidChange(): Event<ConfigurationChangeEvent> { return this._onDidChange.event; } private _onDidChangeAny = new EventEmitter<ConfigurationChangeEvent>(); get onDidChangeAny(): Event<ConfigurationChangeEvent> { return this._onDidChangeAny.event; } private _onWillChange = new EventEmitter<ConfigurationWillChangeEvent>(); get onWillChange(): Event<ConfigurationWillChangeEvent> { return this._onWillChange.event; } private onConfigurationChanged(e: ConfigurationChangeEvent) { if (!e.affectsConfiguration(configPrefix)) { this._onDidChangeAny.fire(e); return; } const evt: ConfigurationWillChangeEvent = { change: e, }; this._onWillChange.fire(evt); if (evt.transform !== undefined) { e = evt.transform(e); } this._onDidChangeAny.fire(e); this._onDidChange.fire(e); } get(): Config; get<T extends ConfigPath>( section: T, scope?: ConfigurationScope | null, defaultValue?: ConfigPathValue<T>, ): ConfigPathValue<T>; get<T extends ConfigPath>( section?: T, scope?: ConfigurationScope | null, defaultValue?: ConfigPathValue<T>, ): Config | ConfigPathValue<T> { return defaultValue === undefined ? workspace .getConfiguration(section === undefined ? undefined : configPrefix, scope) .get<ConfigPathValue<T>>(section === undefined ? configPrefix : section)! : workspace .getConfiguration(section === undefined ? undefined : configPrefix, scope) .get<ConfigPathValue<T>>(section === undefined ? configPrefix : section, defaultValue)!; } getAny<T>(section: string, scope?: ConfigurationScope | null): T | undefined; getAny<T>(section: string, scope: ConfigurationScope | null | undefined, defaultValue: T): T; getAny<T>(section: string, scope?: ConfigurationScope | null, defaultValue?: T): T | undefined { return defaultValue === undefined ? workspace.getConfiguration(undefined, scope).get<T>(section) : workspace.getConfiguration(undefined, scope).get<T>(section, defaultValue); } changed<T extends ConfigPath>( e: ConfigurationChangeEvent | undefined, section: T, scope?: ConfigurationScope | null | undefined, ): boolean { return e?.affectsConfiguration(`${configPrefix}.${section}`, scope!) ?? true; } inspect<T extends ConfigPath, V extends ConfigPathValue<T>>(section: T, scope?: ConfigurationScope | null) { return workspace .getConfiguration(section === undefined ? undefined : configPrefix, scope) .inspect<V>(section === undefined ? configPrefix : section); } inspectAny<T>(section: string, scope?: ConfigurationScope | null) { return workspace.getConfiguration(undefined, scope).inspect<T>(section); } async migrate<T extends ConfigPath>( from: string, to: T, options: { fallbackValue?: ConfigPathValue<T>; migrationFn?(value: any): ConfigPathValue<T> }, ): Promise<boolean> { const inspection = configuration.inspect(from as any); if (inspection === undefined) return false; let migrated = false; if (inspection.globalValue !== undefined) { await this.update( to, options.migrationFn != null ? options.migrationFn(inspection.globalValue) : inspection.globalValue, ConfigurationTarget.Global, ); migrated = true; // Can't delete the old setting currently because it errors with `Unable to write to User Settings because <setting name> is not a registered configuration` // if (from !== to) { // try { // await this.update(from, undefined, ConfigurationTarget.Global); // } // catch { } // } } if (inspection.workspaceValue !== undefined) { await this.update( to, options.migrationFn != null ? options.migrationFn(inspection.workspaceValue) : inspection.workspaceValue, ConfigurationTarget.Workspace, ); migrated = true; // Can't delete the old setting currently because it errors with `Unable to write to User Settings because <setting name> is not a registered configuration` // if (from !== to) { // try { // await this.update(from, undefined, ConfigurationTarget.Workspace); // } // catch { } // } } if (inspection.workspaceFolderValue !== undefined) { await this.update( to, options.migrationFn != null ? options.migrationFn(inspection.workspaceFolderValue) : inspection.workspaceFolderValue, ConfigurationTarget.WorkspaceFolder, ); migrated = true; // Can't delete the old setting currently because it errors with `Unable to write to User Settings because <setting name> is not a registered configuration` // if (from !== to) { // try { // await this.update(from, undefined, ConfigurationTarget.WorkspaceFolder); // } // catch { } // } } if (!migrated && options.fallbackValue !== undefined) { await this.update(to, options.fallbackValue, ConfigurationTarget.Global); migrated = true; } return migrated; } async migrateIfMissing<T extends ConfigPath>( from: string, to: T, options: { migrationFn?(value: any): ConfigPathValue<T> }, ): Promise<void> { const fromInspection = configuration.inspect(from as any); if (fromInspection === undefined) return; const toInspection = configuration.inspect(to); if (fromInspection.globalValue !== undefined) { if (toInspection === undefined || toInspection.globalValue === undefined) { await this.update( to, options.migrationFn != null ? options.migrationFn(fromInspection.globalValue) : fromInspection.globalValue, ConfigurationTarget.Global, ); // Can't delete the old setting currently because it errors with `Unable to write to User Settings because <setting name> is not a registered configuration` // if (from !== to) { // try { // await this.update(from, undefined, ConfigurationTarget.Global); // } // catch { } // } } } if (fromInspection.workspaceValue !== undefined) { if (toInspection === undefined || toInspection.workspaceValue === undefined) { await this.update( to, options.migrationFn != null ? options.migrationFn(fromInspection.workspaceValue) : fromInspection.workspaceValue, ConfigurationTarget.Workspace, ); // Can't delete the old setting currently because it errors with `Unable to write to User Settings because <setting name> is not a registered configuration` // if (from !== to) { // try { // await this.update(from, undefined, ConfigurationTarget.Workspace); // } // catch { } // } } } if (fromInspection.workspaceFolderValue !== undefined) { if (toInspection === undefined || toInspection.workspaceFolderValue === undefined) { await this.update( to, options.migrationFn != null ? options.migrationFn(fromInspection.workspaceFolderValue) : fromInspection.workspaceFolderValue, ConfigurationTarget.WorkspaceFolder, ); // Can't delete the old setting currently because it errors with `Unable to write to User Settings because <setting name> is not a registered configuration` // if (from !== to) { // try { // await this.update(from, undefined, ConfigurationTarget.WorkspaceFolder); // } // catch { } // } } } } name<T extends ConfigPath>(section: T): string { return section; } update<T extends ConfigPath>( section: T, value: ConfigPathValue<T> | undefined, target: ConfigurationTarget, ): Thenable<void> { return workspace.getConfiguration(configPrefix).update(section, value, target); } updateAny( section: string, value: any, target: ConfigurationTarget, scope?: ConfigurationScope | null, ): Thenable<void> { return workspace .getConfiguration(undefined, target === ConfigurationTarget.Global ? undefined : scope!) .update(section, value, target); } updateEffective<T extends ConfigPath>(section: T, value: ConfigPathValue<T> | undefined): Thenable<void> { const inspect = configuration.inspect(section)!; if (inspect.workspaceFolderValue !== undefined) { if (value === inspect.workspaceFolderValue) return Promise.resolve(undefined); return configuration.update(section, value, ConfigurationTarget.WorkspaceFolder); } if (inspect.workspaceValue !== undefined) { if (value === inspect.workspaceValue) return Promise.resolve(undefined); return configuration.update(section, value, ConfigurationTarget.Workspace); } if (inspect.globalValue === value || (inspect.globalValue === undefined && value === inspect.defaultValue)) { return Promise.resolve(undefined); } return configuration.update( section, Objects.areEqual(value, inspect.defaultValue) ? undefined : value, ConfigurationTarget.Global, ); } } export const configuration = new Configuration(); type SubPath<T, Key extends keyof T> = Key extends string ? T[Key] extends Record<string, any> ? | `${Key}.${SubPath<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never; type Path<T> = SubPath<T, keyof T> | keyof T extends string | keyof T ? SubPath<T, keyof T> | keyof T : keyof T; type PathValue<T, P extends Path<T>> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path<T[Key]> ? PathValue<T[Key], Rest> : never : never : P extends keyof T ? T[P] : never; type ConfigPath = Path<Config>; type ConfigPathValue<P extends ConfigPath> = PathValue<Config, P>;
the_stack
import * as errors from 'balena-errors'; import once = require('lodash/once'); import type * as BalenaSdk from '..'; import type { InjectedDependenciesParam, InjectedOptionsParam, PineTypedResult, } from '..'; import { isId, mergePineOptions } from '../util'; import { toWritable } from '../util/types'; import type { Application, ReleaseTag, Release, User } from '../types/models'; import type { BuilderUrlDeployOptions } from '../util/builder'; export interface ReleaseWithImageDetails extends Release { images: Array<{ id: number; service_name: string; }>; user: Pick<User, 'id' | 'username'> | undefined; } const getReleaseModel = function ( deps: InjectedDependenciesParam, opts: InjectedOptionsParam, ) { const { pine } = deps; const applicationModel = once(() => (require('./application') as typeof import('./application')).default( deps, opts, ), ); const { addCallbackSupportToModule } = require('../util/callbacks') as typeof import('../util/callbacks'); const { buildDependentResource } = require('../util/dependent-resource') as typeof import('../util/dependent-resource'); const builderHelper = once(() => { const { BuilderHelper } = require('../util/builder') as typeof import('../util/builder'); return new BuilderHelper(deps, opts); }); const tagsModel = buildDependentResource<ReleaseTag>( { pine }, { resourceName: 'release_tag', resourceKeyField: 'tag_key', parentResourceName: 'release', getResourceId: async (commitOrId: string | number): Promise<number> => (await get(commitOrId, { $select: 'id' })).id, }, ); /** * @summary Get a specific release * @name get * @public * @function * @memberof balena.models.release * * @param {String|Number} commitOrId - release commit (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object} - release * @returns {Promise} * * @example * balena.models.release.get(123).then(function(release) { * console.log(release); * }); * * @example * balena.models.release.get('7cf02a6').then(function(release) { * console.log(release); * }); * * @example * balena.models.release.get(123, function(error, release) { * if (error) throw error; * console.log(release); * }); */ async function get( commitOrId: string | number, options: BalenaSdk.PineOptions<BalenaSdk.Release> = {}, ): Promise<BalenaSdk.Release> { if (commitOrId == null) { throw new errors.BalenaReleaseNotFound(commitOrId); } if (isId(commitOrId)) { const release = await pine.get({ resource: 'release', id: commitOrId, options: mergePineOptions({}, options), }); if (release == null) { throw new errors.BalenaReleaseNotFound(commitOrId); } return release; } else { const releases = await pine.get({ resource: 'release', options: mergePineOptions( { $filter: { commit: { $startswith: commitOrId }, }, }, options, ), }); if (releases.length === 0) { throw new errors.BalenaReleaseNotFound(commitOrId); } if (releases.length > 1) { throw new errors.BalenaAmbiguousRelease(commitOrId); } return releases[0]; } } /** * @summary Get a specific release with the details of the images built * @name getWithImageDetails * @public * @function * @memberof balena.models.release * * @description * This method does not map exactly to the underlying model: it runs a * larger prebuilt query, and reformats it into an easy to use and * understand format. If you want significantly more control, or to see the * raw model directly, use `release.get(id, options)` instead. * * @param {String|Number} commitOrId - release commit (string) or id (number) * @param {Object} [options={}] - a map of extra pine options * @param {Boolean} [options.release={}] - extra pine options for releases * @param {Object} [options.image={}] - extra pine options for images * @fulfil {Object} - release with image details * @returns {Promise} * * @example * balena.models.release.getWithImageDetails(123).then(function(release) { * console.log(release); * }); * * @example * balena.models.release.getWithImageDetails('7cf02a6').then(function(release) { * console.log(release); * }); * * @example * balena.models.release.getWithImageDetails(123, { image: { $select: 'build_log' } }) * .then(function(release) { * console.log(release.images[0].build_log); * }); * * @example * balena.models.release.getWithImageDetails(123, function(error, release) { * if (error) throw error; * console.log(release); * }); */ async function getWithImageDetails( commitOrId: string | number, options: { release?: BalenaSdk.PineOptions<BalenaSdk.Release>; image?: BalenaSdk.PineOptions<BalenaSdk.Image>; } = {}, ): Promise<BalenaSdk.ReleaseWithImageDetails> { const baseImageOptions = { $select: 'id', $expand: { is_a_build_of__service: { $select: 'service_name', }, }, } as const; const baseReleaseOptions = { $expand: { release_image: { $expand: { image: mergePineOptions( baseImageOptions, options.image, ) as typeof baseImageOptions, }, }, is_created_by__user: { $select: toWritable(['id', 'username'] as const), }, }, } as const; const rawRelease = (await get( commitOrId, mergePineOptions(baseReleaseOptions, options.release), )) as PineTypedResult<Release, typeof baseReleaseOptions>; const release = rawRelease as BalenaSdk.ReleaseWithImageDetails; // Squash .release_image[x].image[0] into a simple array const images = rawRelease.release_image.map( (imageJoin) => imageJoin.image[0], ); delete release.release_image; release.images = images .map(function ({ is_a_build_of__service, ...imageData }) { const image: BalenaSdk.ReleaseWithImageDetails['images'][number] = { ...imageData, service_name: is_a_build_of__service[0].service_name, }; return image; }) .sort((a, b) => a.service_name.localeCompare(b.service_name)); release.user = rawRelease.is_created_by__user[0]; return release; } /** * @summary Get all releases from an application * @name getAllByApplication * @public * @function * @memberof balena.models.release * * @param {String|Number} slugOrUuidOrId - application slug (string), uuid (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - releases * @returns {Promise} * * @example * balena.models.release.getAllByApplication('myorganization/myapp').then(function(releases) { * console.log(releases); * }); * * @example * balena.models.release.getAllByApplication(123).then(function(releases) { * console.log(releases); * }); * * @example * balena.models.release.getAllByApplication('myorganization/myapp', function(error, releases) { * if (error) throw error; * console.log(releases); * }); */ async function getAllByApplication( slugOrUuidOrId: string | number, options: BalenaSdk.PineOptions<BalenaSdk.Release> = {}, ): Promise<BalenaSdk.Release[]> { const { id } = await applicationModel().get(slugOrUuidOrId, { $select: 'id', }); return await pine.get({ resource: 'release', options: mergePineOptions( { $filter: { belongs_to__application: id, }, $orderby: 'created_at desc', }, options, ), }); } /** * @summary Get the latest successful release for an application * @name getLatestByApplication * @public * @function * @memberof balena.models.release * * @param {String|Number} slugOrUuidOrId - application slug (string), uuid (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object|undefined} - release * @returns {Promise} * * @example * balena.models.release.getLatestByApplication('myorganization/myapp').then(function(releases) { * console.log(releases); * }); * * @example * balena.models.release.getLatestByApplication(123).then(function(releases) { * console.log(releases); * }); * * @example * balena.models.release.getLatestByApplication('myorganization/myapp', function(error, releases) { * if (error) throw error; * console.log(releases); * }); */ async function getLatestByApplication( slugOrUuidOrId: string | number, options: BalenaSdk.PineOptions<BalenaSdk.Release> = {}, ): Promise<BalenaSdk.Release | undefined> { const [release] = await getAllByApplication( slugOrUuidOrId, mergePineOptions( { $top: 1, $filter: { status: 'success', }, }, options, ), ); return release; } /** * @summary Create a new release built from the source in the provided url * @name createFromUrl * @public * @function * @memberof balena.models.release * * @param {String|Number} slugOrUuidOrId - application slug (string), uuid (string) or id (number) * @param {Object} urlDeployOptions - builder options * @param {String} urlDeployOptions.url - a url with a tarball of the project to build * @param {Boolean} [urlDeployOptions.shouldFlatten=true] - Should be true when the tarball includes an extra root folder with all the content * @fulfil {number} - release ID * @returns {Promise} * * @example * balena.models.release.createFromUrl('myorganization/myapp', { url: 'https://github.com/balena-io-projects/simple-server-node/archive/v1.0.0.tar.gz' }).then(function(releaseId) { * console.log(releaseId); * }); * * @example * balena.models.release.createFromUrl(123, { url: 'https://github.com/balena-io-projects/simple-server-node/archive/v1.0.0.tar.gz' }).then(function(releaseId) { * console.log(releaseId); * }); * * @example * balena.models.release.createFromUrl('myorganization/myapp', { url: 'https://github.com/balena-io-projects/simple-server-node/archive/v1.0.0.tar.gz' }, function(error, releaseId) { * if (error) throw error; * console.log(releaseId); * }); */ async function createFromUrl( slugOrUuidOrId: string | number, urlDeployOptions: BuilderUrlDeployOptions, ): Promise<number> { const appOptions = { $select: 'app_name', $expand: { organization: { $select: 'handle', }, }, } as const; const { app_name, organization } = (await applicationModel().get( slugOrUuidOrId, appOptions, )) as PineTypedResult<Application, typeof appOptions>; return await builderHelper().buildFromUrl( organization[0].handle, app_name, urlDeployOptions, ); } /** * @summary Finalizes a draft release * @name finalize * @public * @function * @memberof balena.models.release * * @param {String|Number} commitOrId - release commit (string) or id (number) * @fulfil {void} * @returns {Promise} * * @example * balena.models.release.finalize(123).then(function() { * console.log('finalized!'); * }); * * @example * balena.models.release.finalize('7cf02a6').then(function() { * console.log('finalized!'); * }); * */ async function finalize(commitOrId: string | number): Promise<void> { const { id } = await get(commitOrId, { $select: 'id' }); await pine.patch<Release>({ resource: 'release', id, body: { is_final: true, }, }); } /** * @summary Set the is_invalidated property of a release to true or false * @name setIsInvalidated * @public * @function * @memberof balena.models.release * * @param {String|Number} commitOrId - release commit (string) or id (number) * @param {Boolean} isInvalidated - boolean value, true for invalidated, false for validated * @fulfil {void} * @returns {Promise} * * @example * balena.models.release.setIsInvalidated(123, true).then(function() { * console.log('invalidated!'); * }); * * @example * balena.models.release.setIsInvalidated('7cf02a6', true).then(function() { * console.log('invalidated!'); * }); * * @example * balena.models.release.setIsInvalidated(123, false).then(function() { * console.log('validated!'); * }); * * @example * balena.models.release.setIsInvalidated('7cf02a6', false).then(function() { * console.log('validated!'); * }); * */ async function setIsInvalidated( commitOrId: string | number, isInvalidated: boolean, ): Promise<void> { const { id } = await get(commitOrId, { $select: 'id' }); await pine.patch<Release>({ resource: 'release', id, body: { is_invalidated: isInvalidated, }, }); } // TODO: Rename to `setNote` in the next major /** * @summary Add a note to a release * @name note * @public * @function * @memberof balena.models.release * * @param {String|Number} commitOrId - release commit (string) or id (number) * @param {String|Null} noteOrNull - the note * * @returns {Promise} * * @example * balena.models.release.note('7cf02a6', 'My useful note'); * * @example * balena.models.release.note(123, 'My useful note'); */ async function note( commitOrId: string | number, noteOrNull: string | null, ): Promise<void> { const { id } = await get(commitOrId, { $select: 'id' }); await pine.patch<Release>({ resource: 'release', id, body: { note: noteOrNull, }, }); } /** * @summary Add a known issue list to a release * @name setKnownIssueList * @public * @function * @memberof balena.models.release * * @param {String|Number} commitOrId - release commit (string) or id (number) * @param {String|Null} knownIssueListOrNull - the known issue list * * @returns {Promise} * * @example * balena.models.release.setKnownIssueList('7cf02a6', 'This is an issue'); * * @example * balena.models.release.setKnownIssueList(123, 'This is an issue'); */ async function setKnownIssueList( commitOrId: string | number, knownIssueListOrNull: string | null, ): Promise<void> { const { id } = await get(commitOrId, { $select: 'id' }); await pine.patch<Release>({ resource: 'release', id, body: { known_issue_list: knownIssueListOrNull, }, }); } /** * @namespace balena.models.release.tags * @memberof balena.models.release */ const tags = addCallbackSupportToModule({ /** * @summary Get all release tags for an application * @name getAllByApplication * @public * @function * @memberof balena.models.release.tags * * @param {String|Number} slugOrUuidOrId - application slug (string), uuid (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - release tags * @returns {Promise} * * @example * balena.models.release.tags.getAllByApplication('myorganization/myapp').then(function(tags) { * console.log(tags); * }); * * @example * balena.models.release.tags.getAllByApplication(999999).then(function(tags) { * console.log(tags); * }); * * @example * balena.models.release.tags.getAllByApplication('myorganization/myapp', function(error, tags) { * if (error) throw error; * console.log(tags) * }); */ async getAllByApplication( slugOrUuidOrId: string | number, options: BalenaSdk.PineOptions<BalenaSdk.ReleaseTag> = {}, ): Promise<BalenaSdk.ReleaseTag[]> { const { id } = await applicationModel().get(slugOrUuidOrId, { $select: 'id', }); return await tagsModel.getAll( mergePineOptions( { $filter: { release: { $any: { $alias: 'r', $expr: { r: { belongs_to__application: id, }, }, }, }, }, }, options, ), ); }, /** * @summary Get all release tags for a release * @name getAllByRelease * @public * @function * @memberof balena.models.release.tags * * @param {String|Number} commitOrId - release commit (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - release tags * @returns {Promise} * * @example * balena.models.release.tags.getAllByRelease(123).then(function(tags) { * console.log(tags); * }); * * @example * balena.models.release.tags.getAllByRelease('7cf02a6').then(function(tags) { * console.log(tags); * }); * * @example * balena.models.release.tags.getAllByRelease(123, function(error, tags) { * if (error) throw error; * console.log(tags) * }); */ async getAllByRelease( commitOrId: string | number, options: BalenaSdk.PineOptions<BalenaSdk.ReleaseTag> = {}, ): Promise<BalenaSdk.ReleaseTag[]> { const releaseOpts = { $select: 'id', $expand: { release_tag: mergePineOptions({ $orderby: 'tag_key asc' }, options), }, } as const; const release = (await get(commitOrId, releaseOpts)) as PineTypedResult< Release, typeof releaseOpts >; return release.release_tag; }, /** * @summary Get all release tags * @name getAll * @public * @function * @memberof balena.models.release.tags * * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - release tags * @returns {Promise} * * @example * balena.models.release.tags.getAll().then(function(tags) { * console.log(tags); * }); * * @example * balena.models.release.tags.getAll(function(error, tags) { * if (error) throw error; * console.log(tags) * }); */ getAll: tagsModel.getAll, /** * @summary Set a release tag * @name set * @public * @function * @memberof balena.models.release.tags * * @param {String|Number} commitOrId - release commit (string) or id (number) * @param {String} tagKey - tag key * @param {String|undefined} value - tag value * * @returns {Promise} * * @example * balena.models.release.tags.set(123, 'EDITOR', 'vim'); * * @example * balena.models.release.tags.set('7cf02a6', 'EDITOR', 'vim'); * * @example * balena.models.release.tags.set(123, 'EDITOR', 'vim', function(error) { * if (error) throw error; * }); */ set: tagsModel.set, /** * @summary Remove a release tag * @name remove * @public * @function * @memberof balena.models.release.tags * * @param {String|Number} commitOrId - release commit (string) or id (number) * @param {String} tagKey - tag key * @returns {Promise} * * @example * balena.models.release.tags.remove(123, 'EDITOR'); * * @example * balena.models.release.tags.remove('7cf02a6', 'EDITOR'); * * @example * balena.models.release.tags.remove(123, 'EDITOR', function(error) { * if (error) throw error; * }); */ remove: tagsModel.remove, }); return { get, getAllByApplication, getLatestByApplication, getWithImageDetails, createFromUrl, finalize, setIsInvalidated, note, setKnownIssueList, tags, }; }; export default getReleaseModel;
the_stack
import * as crypto from "crypto"; import { BasicClient } from "../BasicClient"; import { BasicMultiClient } from "../BasicMultiClient"; import { Candle } from "../Candle"; import { CandlePeriod } from "../CandlePeriod"; import { IClient } from "../IClient"; import { Level2Point } from "../Level2Point"; import { Level2Snapshot } from "../Level2Snapshots"; import { Market } from "../Market"; import { NotImplementedFn } from "../NotImplementedFn"; import { Ticker } from "../Ticker"; import { Trade } from "../Trade"; import { Watcher } from "../Watcher"; function createSignature(timestamp: number, apiKey: string, apiSecret: string) { const hmac = crypto.createHmac("sha256", apiSecret); hmac.update(timestamp.toString() + apiKey); return hmac.digest("hex"); } function createAuthToken(apiKey: string, apiSecret: string) { const timestamp = Math.floor(Date.now() / 1000); return { key: apiKey, signature: createSignature(timestamp, apiKey, apiSecret), timestamp, }; } const multiplier = { ADA: 1e6, ATOM: 1e6, BAT: 1e6, GAS: 1e8, NEO: 1e6, ONT: 1e6, ONG: 1e6, MATIC: 1e6, LINK: 1e6, XTZ: 1e6, BCH: 1e8, BTC: 1e8, BTG: 1e8, BTT: 1e6, DASH: 1e8, ETH: 1e6, GUSD: 1e2, LTC: 1e8, MHC: 1e6, OMG: 1e6, TRX: 1e6, XLM: 1e7, XRP: 1e6, ZEC: 1e8, }; function formatAmount(amount: string, symbol: string) { return (parseInt(amount) / multiplier[symbol]).toFixed(8); } export type CexClientOptions = { apiKey: string; apiSecret: string; }; export class CexClient extends BasicMultiClient { public name: string; public options: CexClientOptions; public candlePeriod: CandlePeriod; /** * Creates a new CEX.io client using the supplied credentials */ constructor(options: CexClientOptions) { super(); this._clients = new Map(); this.name = "CEX_MULTI"; this.options = options; this.hasTickers = true; this.hasTrades = true; this.hasCandles = true; this.hasLevel2Snapshots = true; this.candlePeriod = CandlePeriod._1m; } protected _createBasicClient(clientArgs: { market: Market }): IClient { return new SingleCexClient({ ...this.options, market: clientArgs.market, parent: this, }); } } export class SingleCexClient extends BasicClient { public auth: { apiKey: string; apiSecret: string }; public market: Market; public hasTickers: boolean; public hasTrades: boolean; public hasCandles: boolean; public hasLevel2Snapshots: boolean; public authorized: boolean; public parent: CexClient; protected _sendSubLevel2Updates = NotImplementedFn; protected _sendUnsubLevel2Updates = NotImplementedFn; protected _sendSubLevel3Snapshots = NotImplementedFn; protected _sendUnsubLevel3Snapshots = NotImplementedFn; protected _sendSubLevel3Updates = NotImplementedFn; protected _sendUnsubLevel3Updates = NotImplementedFn; constructor({ wssPath = "wss://ws.cex.io/ws", watcherMs = 900 * 1000, apiKey, apiSecret, market, parent, }: { wssPath?: string; watcherMs?: number; apiKey: string; apiSecret: string; market: Market; parent: CexClient; }) { super(wssPath, "CEX", undefined, watcherMs); this._watcher = new Watcher(this, watcherMs); this.auth = { apiKey, apiSecret }; this.market = market; this.hasTickers = true; this.hasTrades = true; this.hasCandles = true; this.hasLevel2Snapshots = true; this.authorized = false; this.parent = parent; } public get candlePeriod(): CandlePeriod { return this.parent.candlePeriod; } /** * This method is fired anytime the socket is opened, whether * the first time, or any subsequent reconnects. * Since this is an authenticated feed, we first send an authenticate * request, and the normal subscriptions happen after authentication has * completed in the _onAuthorized method. */ protected _onConnected() { this._sendAuthorizeRequest(); } /** * Trigger after an authorization packet has been successfully received. * This code triggers the usual _onConnected code afterwards. */ protected _onAuthorized() { this.authorized = true; this.emit("authorized"); super._onConnected(); } protected _sendAuthorizeRequest() { this._wss.send( JSON.stringify({ e: "auth", auth: createAuthToken(this.auth.apiKey, this.auth.apiSecret), }), ); } protected _sendPong() { if (this._wss) { this._wss.send(JSON.stringify({ e: "pong" })); } } protected _sendSubTicker() { if (!this.authorized) return; this._wss.send( JSON.stringify({ e: "subscribe", rooms: ["tickers"], }), ); } protected _sendUnsubTicker() { // } protected _sendSubTrades(remote_id: string) { if (!this.authorized) return; this._wss.send( JSON.stringify({ e: "subscribe", rooms: [`pair-${remote_id.replace("/", "-")}`], }), ); } protected _sendUnsubTrades() { // } protected _sendSubCandles(remote_id: string) { if (!this.authorized) return; this._wss.send( JSON.stringify({ e: "init-ohlcv", i: candlePeriod(this.candlePeriod), rooms: [`pair-${remote_id.replace("/", "-")}`], }), ); } protected _sendUnsubCandles() { // } protected _sendSubLevel2Snapshots(remote_id: string) { if (!this.authorized) return; this._wss.send( JSON.stringify({ e: "subscribe", rooms: [`pair-${remote_id.replace("/", "-")}`], }), ); } protected _sendUnsubLevel2Snapshots() { // } protected _onMessage(raw: any) { const message = JSON.parse(raw); const { e, data } = message; if (e === "ping") { this._sendPong(); return; } if (e === "subscribe") { if (message.error) { throw new Error(`CEX error: ${JSON.stringify(message)}`); } } if (e === "auth") { if (data.ok === "ok") { this._onAuthorized(); } else { throw new Error("Authentication error"); } return; } if (e === "tick") { // {"e":"tick","data":{"symbol1":"BTC","symbol2":"USD","price":"4244.4","open24":"4248.4","volume":"935.58669239"}} const marketId = `${data.symbol1}/${data.symbol2}`; const market = this._tickerSubs.get(marketId); if (!market) return; const ticker = this._constructTicker(data, market); this.emit("ticker", ticker, market); return; } if (e === "md") { const marketId = data.pair.replace(":", "/"); const market = this._level2SnapshotSubs.get(marketId); if (!market) return; const result = this._constructevel2Snapshot(data, market); this.emit("l2snapshot", result, market); return; } if (e === "history") { const marketId = this.market.id; const market = this._tradeSubs.get(marketId); if (!market) return; // sell/buy:timestamp_ms:amount:price:transaction_id for (const rawTrade of data.reverse()) { const tradeData = rawTrade.split(":"); const trade = this._constructTrade(tradeData, market); this.emit("trade", trade, market); } return; } if (e === "history-update") { const marketId = this.market.id; const market = this._tradeSubs.get(marketId); if (this._tradeSubs.has(marketId)) { for (const rawTrade of data) { const trade = this._constructTrade(rawTrade, market); this.emit("trade", trade, market); } return; } } // ohlcv{period} - why the F*** are there three styles of candles??? if (e === `ohlcv${candlePeriod(this.candlePeriod)}`) { const marketId = message.data.pair.replace(":", "/"); const market = this._candleSubs.get(marketId); if (!market) return; const candle = this._constructCandle(message.data); this.emit("candle", candle, market); return; } } protected _constructTicker(data: any, market: Market) { // {"e":"tick","data":{"symbol1":"BTC","symbol2":"USD","price":"4244.4","open24":"4248.4","volume":"935.58669239"}} const { open24, price, volume } = data; const change = parseFloat(price) - parseFloat(open24); const changePercent = open24 !== 0 ? ((parseFloat(price) - parseFloat(open24)) / parseFloat(open24)) * 100 : 0; return new Ticker({ exchange: this.name, base: market.base, quote: market.quote, timestamp: Date.now(), last: price, open: open24, volume: volume, change: change.toFixed(8), changePercent: changePercent.toFixed(8), }); } protected _constructevel2Snapshot(msg: any, market: Market) { const asks = msg.sell.map( p => new Level2Point(p[0].toFixed(8), formatAmount(p[1], market.base)), ); const bids = msg.buy.map( p => new Level2Point(p[0].toFixed(8), formatAmount(p[1], market.base)), ); return new Level2Snapshot({ exchange: this.name, base: market.base, quote: market.quote, sequenceId: msg.id, asks, bids, }); } protected _constructTrade(data: any, market: Market) { //["buy","1543967891439","4110282","3928.1","9437977"] //format: sell/buy, timestamp_ms, amount, price, transaction_id const [side, timestamp_ms, amount, price, tradeId] = data; return new Trade({ exchange: this.name, base: market.base, quote: market.quote, tradeId: tradeId, unix: parseInt(timestamp_ms), side: side, price: price, amount: formatAmount(amount, market.base), rawAmount: amount, }); } /** { e: 'ohlcv1m', data: { pair: 'BTC:USD', time: '1597261140', o: '11566.8', h: '11566.8', l: '11566.8', c: '11566.8', v: 664142, d: 664142 } } */ protected _constructCandle(data) { const ms = Number(data.time) * 1000; return new Candle(ms, data.o, data.h, data.l, data.c, data.v.toFixed(8)); } } function candlePeriod(period) { switch (period) { case CandlePeriod._1m: return "1m"; case CandlePeriod._3m: return "3m"; case CandlePeriod._5m: return "5m"; case CandlePeriod._15m: return "15m"; case CandlePeriod._30m: return "30m"; case CandlePeriod._1h: return "1h"; case CandlePeriod._2h: return "2h"; case CandlePeriod._4h: return "4h"; case CandlePeriod._6h: return "6h"; case CandlePeriod._12h: return "12h"; case CandlePeriod._1d: return "1d"; case CandlePeriod._3d: return "3d"; case CandlePeriod._1w: return "1w"; } }
the_stack
import { Component, OnInit, OnChanges, Input, Output, ViewChild, EventEmitter } from '@angular/core'; import { ProductSkuVO, ProductWithLinksVO, ProductOptionVO, AttributeVO, Pair } from './../../shared/model/index'; import { Util } from './../../shared/services/index'; import { ModalComponent, ModalResult, ModalAction } from './../../shared/modal/index'; import { ProductSelectComponent } from './../../shared/catalog/index'; import { FormValidationEvent, Futures, Future } from './../../shared/event/index'; import { Config } from './../../../environments/environment'; import { LogUtil } from './../../shared/log/index'; @Component({ selector: 'cw-product-options', templateUrl: 'product-options.component.html', }) export class ProductOptionsComponent implements OnInit, OnChanges { @Input() showHelp:boolean = false; @Output() dataSelected: EventEmitter<ProductOptionVO> = new EventEmitter<ProductOptionVO>(); @Output() dataChanged: EventEmitter<FormValidationEvent<Array<ProductOptionVO>>> = new EventEmitter<FormValidationEvent<Array<ProductOptionVO>>>(); @Output() pageSelected: EventEmitter<number> = new EventEmitter<number>(); @Output() sortSelected: EventEmitter<Pair<string, boolean>> = new EventEmitter<Pair<string, boolean>>(); public options:Array<ProductSkuVO> = null; private _masterObject:ProductWithLinksVO; //sorting public sortColumn:string = 'rank'; public sortDesc:boolean = false; //paging public maxSize:number = Config.UI_TABLE_PAGE_NUMS; public itemsPerPage:number = Config.UI_TABLE_PAGE_SIZE; public totalItems:number = 0; public currentPage:number = 1; // Must use separate variables (not currentPage) for table since that causes // cyclic even update and then exception https://github.com/angular/angular/issues/6005 public pageStart:number = 0; public pageEnd:number = this.itemsPerPage; private _objectOptions:Array<ProductOptionVO>; private _optionFilter:string; public filteredObjectOptions:Array<ProductOptionVO>; private delayedFiltering:Future; private delayedFilteringMs:number = Config.UI_INPUT_DELAY; public changed:boolean = false; public validForSave:boolean = false; @ViewChild('deleteConfirmationModalDialog') private deleteConfirmationModalDialog:ModalComponent; @ViewChild('editModalDialog') private editModalDialog:ModalComponent; @ViewChild('addModalDialog') private addModalDialog:ModalComponent; public selectedAttribute:AttributeVO; public selectedRow:ProductOptionVO; public selectedOptionSku:ProductSkuVO; public optionToEdit:ProductOptionVO; @ViewChild('productSelectDialog') private productSelectDialog:ProductSelectComponent; /** * Construct option panel */ constructor() { LogUtil.debug('ProductOptionsComponent constructed'); this.optionToEdit = null; let that = this; this.delayedFiltering = Futures.perpetual(function() { that.filterOptions(); }, this.delayedFilteringMs); } @Input() set masterObject(master:ProductWithLinksVO) { this._masterObject = master; this.loadData(); } @Input() set optionFilter(optionFilter:string) { this._optionFilter = optionFilter; this.delayedFiltering.delay(); } @Input() set sortorder(sort:Pair<string, boolean>) { if (sort != null && (sort.first !== this.sortColumn || sort.second !== this.sortDesc)) { this.sortColumn = sort.first; this.sortDesc = sort.second; this.delayedFiltering.delay(); } } get masterObject():ProductWithLinksVO { return this._masterObject; } ngOnInit() { LogUtil.debug('ProductOptionsComponent ngOnInit', this.masterObject); } ngOnChanges(changes:any) { LogUtil.debug('ProductOptionsComponent ngOnChanges', changes); this.delayedFiltering.delay(); } onRowAdd() { LogUtil.debug('ProductOptionsComponent onRowAdd'); this.addModalDialog.show(); } onRowDeleteSelected() { if (this.selectedRow != null) { this.onRowDelete(this.selectedRow); } } onRowEditSelected() { if (this.selectedRow != null) { this.onRowEdit(this.selectedRow); } } onAttributeSelected(row:AttributeVO) { this.selectedAttribute = row; } onAttributeAddModalResult(modalresult: ModalResult) { LogUtil.debug('AttributeValuesComponent onAttributeAddModalResult modal result is ', modalresult); if (ModalAction.POSITIVE === modalresult.action) { this.optionToEdit = { productoptionId: 0, rank: 0, productId: this.masterObject.productId, quantity: 1, mandatory: false, skuCode: null, attributeCode: this.selectedAttribute.code, optionSkuCodes: [] }; this.onRowEdit(this.optionToEdit); } else { this.selectedAttribute = null; } } onRowDelete(row:ProductOptionVO) { LogUtil.debug('ProductOptionsComponent onRowDelete handler', row); this.deleteConfirmationModalDialog.show(); } onRowEdit(row:ProductOptionVO) { LogUtil.debug('ProductOptionsComponent onRowEdit handler', row); this.validForSave = false; this.optionToEdit = Util.clone(row); this.editModalDialog.show(); } onOptionSkuSelected(row:ProductSkuVO) { this.selectedOptionSku = row; } onSelectRow(row:ProductOptionVO) { LogUtil.debug('ProductOptionsComponent onSelectRow handler', row); if (row == this.selectedRow) { this.selectedRow = null; } else { this.selectedRow = row; } this.dataSelected.emit(this.selectedRow); } onDataChange(event:any) { this.validForSave = this.optionToEdit.attributeCode != null && this.optionToEdit.attributeCode != '' && this.optionToEdit.optionSkuCodes != null && this.optionToEdit.optionSkuCodes.length > 0; LogUtil.debug('ProductOptionsComponent data changed and ' + (this.validForSave ? 'is valid' : 'is NOT valid'), event); } onSearchProduct() { if (this.optionToEdit != null) { this.productSelectDialog.showDialog(); } } onProductSelected(event:FormValidationEvent<ProductSkuVO>) { LogUtil.debug('ProductOptionsComponent onProductSelected', event); if (event.valid && this.optionToEdit != null) { if (this.optionToEdit.optionSkuCodes.findIndex(val => val.first === event.source.code) === -1 && this.options.findIndex(val => val.code === event.source.code) === -1) { this.optionToEdit.optionSkuCodes.push({first: event.source.code, second: event.source.name}); LogUtil.debug('ProductOptionsComponent onProductSelected', this.optionToEdit); this.onDataChange(event); } } } onOptionSkuRemove(event:Pair<string, string>) { LogUtil.debug('ProductOptionsComponent onOptionSkuRemove', event); if (event != null && this.optionToEdit != null) { this.optionToEdit.optionSkuCodes = this.optionToEdit.optionSkuCodes.filter(val => val.first !== event.first ); LogUtil.debug('ProductOptionsComponent onOptionSkuRemove', this.optionToEdit); this.onDataChange(event); } } onDeleteConfirmationResult(modalresult: ModalResult) { LogUtil.debug('ProductOptionsComponent onDeleteConfirmationResult modal result is ', modalresult); if (ModalAction.POSITIVE === modalresult.action) { let attrToDelete = this.selectedRow.productoptionId; if (attrToDelete == 0) { let idx = this._objectOptions.findIndex(attrVo => { return attrVo.skuCode === this.selectedRow.skuCode && attrVo.attributeCode === this.selectedRow.attributeCode; }); if (idx != -1) { this._objectOptions.splice(idx, 1); } LogUtil.debug('ProductOptionsComponent onDeleteConfirmationResult option ' + attrToDelete); } else { let idx = this._objectOptions.findIndex(attrVo => { return attrVo.productoptionId === attrToDelete; }); if (idx != -1) { this._objectOptions.splice(idx, 1); } LogUtil.debug('ProductOptionsComponent onDeleteConfirmationResult option ' + attrToDelete); } this.filterOptions(); this.onSelectRow(null); this.changed = true; this.processDataChangesEvent(); } else { this.optionToEdit = null; } } onEditModalResult(modalresult: ModalResult) { LogUtil.debug('ProductOptionsComponent onEditModalResult modal result is ', modalresult); if (ModalAction.POSITIVE === modalresult.action) { if (this.optionToEdit.productoptionId === 0) { // add new LogUtil.debug('ProductOptionsComponent onEditModalResult add new option', this._objectOptions); let idx = this._objectOptions.findIndex(attrVo => { return attrVo.skuCode === this.optionToEdit.skuCode && attrVo.attributeCode === this.optionToEdit.attributeCode; }); if (idx != -1) { this._objectOptions[idx] = this.optionToEdit; } else { this._objectOptions.push(this.optionToEdit); } } else { // edit existing LogUtil.debug('ProductOptionsComponent onEditModalResult update existing', this._objectOptions); let idx = this._objectOptions.findIndex(attrVo => { return attrVo.productoptionId === this.optionToEdit.productoptionId; }); this._objectOptions[idx] = this.optionToEdit; } this.selectedRow = this.optionToEdit; this.changed = true; this.filterOptions(); this.processDataChangesEvent(); } else { this.optionToEdit = null; } } resetLastPageEnd() { let _pageEnd = this.pageStart + this.itemsPerPage; if (_pageEnd > this.totalItems) { this.pageEnd = this.totalItems; } else { this.pageEnd = _pageEnd; } } onPageChanged(event:any) { if (this.currentPage != event.page) { this.pageSelected.emit(event.page - 1); } this.pageStart = (event.page - 1) * this.itemsPerPage; let _pageEnd = this.pageStart + this.itemsPerPage; if (_pageEnd > this.totalItems) { this.pageEnd = this.totalItems; } else { this.pageEnd = _pageEnd; } } onSortClick(event:any) { if (event == this.sortColumn) { if (this.sortDesc) { // same column already desc, remove sort this.sortColumn = 'rank'; this.sortDesc = false; } else { // same column asc, change to desc this.sortColumn = event; this.sortDesc = true; } } else { // different column, start asc sort this.sortColumn = event; this.sortDesc = false; } this.filterOptions(); this.sortSelected.emit({ first: this.sortColumn, second: this.sortDesc }); } getSkuName(row:ProductOptionVO):string { if (row != null && row.skuCode != null && this.options != null) { let idx = this.options.findIndex(sku => { return sku.code == row.skuCode; }); if (idx != -1) { return this.options[idx].name; } } return ''; } private loadData() { if (this.masterObject) { this._objectOptions = this.masterObject.configurationOptions; this.options = this.masterObject.sku; LogUtil.debug('ProductOptionsComponent options', this._objectOptions); this.filterOptions(); } else { this.filteredObjectOptions = []; } this.changed = false; this.onSelectRow(null); } private filterOptions() { let _filter = this._optionFilter ? this._optionFilter.toLowerCase() : null; let _filteredObjectOptions:Array<ProductOptionVO> = []; if (this._objectOptions) { if (_filter) { if (_filter.indexOf('#') === 0) { let _type = _filter.substr(1); _filteredObjectOptions = this._objectOptions.filter(val => val.attributeCode.toLowerCase().indexOf(_type) !== -1 ); } else { _filteredObjectOptions = this._objectOptions.filter(val => { if (val.skuCode != null && val.skuCode.toLowerCase().indexOf(_filter) !== -1) { return true; } return val.optionSkuCodes.findIndex(val => val.first.toLowerCase().indexOf(_filter) !== -1 ) !== -1; } ); } LogUtil.debug('ProductOptionsComponent filterOptions ' + _filter, _filteredObjectOptions); } else { _filteredObjectOptions = this._objectOptions.slice(0, this._objectOptions.length); LogUtil.debug('ProductOptionsComponent filterOptions no filter', _filteredObjectOptions); } } if (_filteredObjectOptions === null) { _filteredObjectOptions = []; } let _sortProp = this.sortColumn; let _sortOrder = this.sortDesc ? -1 : 1; let _sort = function(a:any, b:any):number { return (a[_sortProp] > b[_sortProp] ? 1 : -1) * _sortOrder; }; _filteredObjectOptions.sort(_sort); this.filteredObjectOptions = _filteredObjectOptions; let _total = this.filteredObjectOptions.length; this.totalItems = _total; if (_total > 0) { this.resetLastPageEnd(); } } private processDataChangesEvent() { LogUtil.debug('ProductOptionsComponent data changes', this.masterObject); if (this.masterObject && this._objectOptions) { LogUtil.debug('ProductOptionsComponent data changes update', this._objectOptions); this.dataChanged.emit({ source: this._objectOptions, valid: true }); } } }
the_stack
import { Worksheets } from './worksheets'; import { Worksheet, FreezePane, MergeCell, MergeCells, HyperLink, Grouping } from './worksheet'; import { CellStyle, Font, Border, Borders, CellXfs, Alignment, NumFmt, CellStyleXfs, CellStyles } from './cell-style'; import { Column } from './column'; import { Row, Rows } from './row'; import { Image } from './image'; import { Cell, Cells } from './cell'; import { ZipArchive, ZipArchiveItem } from '@syncfusion/ej2-compression'; import { SaveType, BlobSaveType } from './enum'; import { CsvHelper } from './csv-helper'; import { Internationalization, isNullOrUndefined } from '@syncfusion/ej2-base'; import { BlobHelper } from './blob-helper'; import { AutoFilters } from './auto-filters'; /** * Workbook class */ export class Workbook { private mArchive: ZipArchive; private sharedString: string[]; private sharedStringCount: number = 0; public cellStyles: Map<string, CellStyles>; public mergedCellsStyle: Map<string, { x: number, y: number, styleIndex: number }>; private worksheets: Worksheets; private builtInProperties: BuiltInProperties; private mFonts: Font[]; private mBorders: Borders[]; private mFills: Map<string, number>; private mNumFmt: Map<string, NumFmt>; private mStyles: CellStyle[]; private mCellXfs: CellXfs[]; private mCellStyleXfs: CellStyleXfs[]; private mergeCells: MergeCells; private csvHelper: CsvHelper; private mSaveType: SaveType; private mHyperLinks: HyperLink[]; private unitsProportions: number[] = [ 96 / 75.0, // Display 96 / 300.0, // Document 96, // Inch 96 / 25.4, // Millimeter 96 / 2.54, // Centimeter 1, // Pixel 96 / 72.0, // Point 96 / 72.0 / 12700, // EMU ]; /* tslint:disable:no-any */ private hyperlinkStyle: any = { fontColor: '#0000FF', underline: true }; private printTitles: Map<number, string>; private culture: string; private currency: string; private intl: Internationalization; private globalStyles: Map<string, any>; private rgbColors: Map<string, string>; private drawingCount: number; private imageCount: number; /* tslint:disable:no-any */ public constructor(json: any, saveType: SaveType, culture?: string, currencyString?: string, separator?: string) { if (culture !== undefined) { this.culture = culture; } else { this.culture = 'en-US'; } if (currencyString !== undefined) { this.currency = currencyString; } else { this.currency = 'USD'; } this.intl = new Internationalization(this.culture); this.mSaveType = saveType; if (saveType === 'xlsx') { this.mArchive = new ZipArchive(); this.sharedString = []; this.mFonts = []; this.mBorders = []; this.mStyles = []; this.printTitles = new Map<number, string>(); this.cellStyles = new Map<string, CellStyles>(); this.mNumFmt = new Map<string, NumFmt>(); this.mFills = new Map<string, number>(); this.mStyles.push(new CellStyle()); this.mFonts.push(new Font()); /* tslint:disable */ this.cellStyles.set('Normal', new CellStyles()); /* tslint:enable */ this.mCellXfs = []; this.mCellStyleXfs = []; this.drawingCount = 0; this.imageCount = 0; if (json.styles !== null && json.styles !== undefined) { /* tslint:disable-next-line:no-any */ this.globalStyles = new Map<string, any>(); for (let i: number = 0; i < json.styles.length; i++) { if (json.styles[i].name !== undefined) { if (!this.cellStyles.has(json.styles[i].name)) { let cellStyle: CellStyle = new CellStyle(); cellStyle.isGlobalStyle = true; this.parserCellStyle(json.styles[i], cellStyle, 'none'); let cellStylesIn: CellStyles = new CellStyles(); cellStylesIn.name = cellStyle.name; cellStylesIn.xfId = (cellStyle.index - 1); this.cellStyles.set(cellStylesIn.name, cellStylesIn); /* tslint:disable-next-line:no-any */ let tFormat: any = {}; if (json.styles[i].numberFormat !== undefined) { tFormat.format = json.styles[i].numberFormat; } if (json.styles[i].type !== undefined) { tFormat.type = json.styles[i].type; } else { tFormat.type = 'datetime'; } if (tFormat.format !== undefined) { this.globalStyles.set(json.styles[i].name, tFormat); } } else { throw Error('Style name ' + json.styles[i].name + ' is already existed'); } } } } // Parses Worksheets data to DOM. if (json.worksheets !== null && json.worksheets !== undefined) { this.parserWorksheets(json.worksheets); } else { throw Error('Worksheet is expected.'); } // Parses the BuiltInProperties data to DOM. if (json.builtInProperties !== null && json.builtInProperties !== undefined) { this.builtInProperties = new BuiltInProperties(); this.parserBuiltInProperties(json.builtInProperties, this.builtInProperties); } } else { this.csvHelper = new CsvHelper(json, separator); } } /* tslint:disable:no-any */ private parserBuiltInProperties(jsonBuiltInProperties: any, builtInProperties: BuiltInProperties): void { //Author if (jsonBuiltInProperties.author !== null && jsonBuiltInProperties.author !== undefined) { builtInProperties.author = jsonBuiltInProperties.author; } //Comments if (jsonBuiltInProperties.comments !== null && jsonBuiltInProperties.comments !== undefined) { builtInProperties.comments = jsonBuiltInProperties.comments; } //Category if (jsonBuiltInProperties.category !== null && jsonBuiltInProperties.category !== undefined) { builtInProperties.category = jsonBuiltInProperties.category; } //Company if (jsonBuiltInProperties.company !== null && jsonBuiltInProperties.company !== undefined) { builtInProperties.company = jsonBuiltInProperties.company; } //Manager if (jsonBuiltInProperties.manager !== null && jsonBuiltInProperties.manager !== undefined) { builtInProperties.manager = jsonBuiltInProperties.manager; } //Subject if (jsonBuiltInProperties.subject !== null && jsonBuiltInProperties.subject !== undefined) { builtInProperties.subject = jsonBuiltInProperties.subject; } //Title if (jsonBuiltInProperties.title !== null && jsonBuiltInProperties.title !== undefined) { builtInProperties.title = jsonBuiltInProperties.title; } //Creation date if (jsonBuiltInProperties.createdDate !== null && jsonBuiltInProperties.createdDate !== undefined) { builtInProperties.createdDate = jsonBuiltInProperties.createdDate; } //Modified date if (jsonBuiltInProperties.modifiedDate !== null && jsonBuiltInProperties.modifiedDate !== undefined) { builtInProperties.modifiedDate = jsonBuiltInProperties.modifiedDate; } //Tags if (jsonBuiltInProperties.tags !== null && jsonBuiltInProperties.tags !== undefined) { builtInProperties.tags = jsonBuiltInProperties.tags; } //Status if (jsonBuiltInProperties.status !== null && jsonBuiltInProperties.status !== undefined) { builtInProperties.status = jsonBuiltInProperties.status; } } /* tslint:disable:no-any */ private parserWorksheets(json: any): void { this.worksheets = new Worksheets(); let length: number = json.length; for (let i: number = 0; i < length; i++) { let jsonSheet: any = json[i]; let sheet: Worksheet = new Worksheet(); this.mergeCells = new MergeCells(); this.mergedCellsStyle = new Map<string, { x: number, y: number, styleIndex: number }>(); this.mHyperLinks = []; //Name if (jsonSheet.name !== null && jsonSheet.name !== undefined) { sheet.name = jsonSheet.name; } else { sheet.name = 'Sheet' + (i + 1).toString(); } if (jsonSheet.enableRtl !== null && jsonSheet.enableRtl !== undefined) { sheet.enableRtl = jsonSheet.enableRtl; } sheet.index = (i + 1); //Columns if (jsonSheet.columns !== null && jsonSheet.columns !== undefined) { this.parserColumns(jsonSheet.columns, sheet); } //Rows if (jsonSheet.rows !== null && jsonSheet.rows !== undefined) { this.parserRows(jsonSheet.rows, sheet); } //showGridLines if (jsonSheet.showGridLines !== null && jsonSheet.showGridLines !== undefined) { sheet.showGridLines = jsonSheet.showGridLines; } //FreezePanes if (jsonSheet.freeze !== null && jsonSheet.freeze !== undefined) { this.parserFreezePanes(jsonSheet.freeze, sheet); } //Print Title if (jsonSheet.printTitle !== null && jsonSheet.printTitle !== undefined) { this.parserPrintTitle(jsonSheet.printTitle, sheet); } if (jsonSheet.pageSetup !== undefined) { if (jsonSheet.pageSetup.isSummaryRowBelow !== undefined) { sheet.isSummaryRowBelow = jsonSheet.pageSetup.isSummaryRowBelow; } } if (jsonSheet.images !== undefined) { this.parserImages(jsonSheet.images, sheet); } if (jsonSheet.autoFilters !== null && jsonSheet.autoFilters !== undefined) { this.parseFilters(jsonSheet.autoFilters, sheet); } sheet.index = (i + 1); sheet.mergeCells = this.mergeCells; sheet.hyperLinks = this.mHyperLinks; this.worksheets.push(sheet); } } /* tslint:disable:no-any */ private mergeOptions(fromJson: any, toJson: any): any { /* tslint:disable:no-any */ let result: any = {}; this.applyProperties(fromJson, result); this.applyProperties(toJson, result); return result; } /* tslint:disable:no-any */ private applyProperties(sourceJson: any, destJson: any): void { let keys: any = Object.keys(sourceJson); for (let index: number = 0; index < keys.length; index++) { if (keys[index] !== 'name') { destJson[keys[index]] = sourceJson[keys[index]]; } } } private getCellName(row: number, column: number): string { return this.getColumnName(column) + row.toString(); } private getColumnName(col: number): string { col--; let strColumnName: string = ''; do { let iCurrentDigit: number = col % 26; col = col / 26 - 1; strColumnName = String.fromCharCode(65 + iCurrentDigit) + strColumnName; } while (col >= 0); return strColumnName; } /* tslint:disable:no-any */ private parserPrintTitle(json: any, sheet: Worksheet): void { let printTitleName: string = ''; let titleRowName: string; if (json.fromRow !== null && json.fromRow !== undefined) { let fromRow: number = json.fromRow; let toRow: number; if (json.toRow !== null && json.toRow !== undefined) { toRow = json.toRow; } else { toRow = json.fromRow; } titleRowName = '$' + fromRow + ':$' + toRow; } let titleColName: string; if (json.fromColumn !== null && json.fromColumn !== undefined) { let fromColumn: number = json.fromColumn; let toColumn: number; if (json.toColumn !== null && json.toColumn !== undefined) { toColumn = json.toColumn; } else { toColumn = json.fromColumn; } titleColName = '$' + this.getColumnName(fromColumn) + ':$' + this.getColumnName(toColumn); } if (titleRowName !== undefined) { printTitleName += (sheet.name + '!' + titleRowName); } if (titleColName !== undefined && titleRowName !== undefined) { printTitleName += ',' + (sheet.name + '!' + titleColName); } else if (titleColName !== undefined) { printTitleName += (sheet.name + '!' + titleColName); } if (printTitleName !== '') { this.printTitles.set(sheet.index - 1, printTitleName); } } /* tslint:disable:no-any */ private parserFreezePanes(json: any, sheet: Worksheet): void { sheet.freezePanes = new FreezePane(); if (json.row !== null && json.row !== undefined) { sheet.freezePanes.row = json.row; } else { sheet.freezePanes.row = 0; } if (json.column !== null && json.column !== undefined) { sheet.freezePanes.column = json.column; } else { sheet.freezePanes.column = 0; } sheet.freezePanes.leftCell = this.getCellName(sheet.freezePanes.row + 1, sheet.freezePanes.column + 1); } /* tslint:disable:no-any */ private parserColumns(json: any, sheet: Worksheet): void { let columnsLength: number = json.length; sheet.columns = []; for (let column: number = 0; column < columnsLength; column++) { let col: Column = new Column(); if (json[column].index !== null && json[column].index !== undefined) { col.index = json[column].index; } else { throw Error('Column index is missing.'); } if (json[column].width !== null && json[column].width !== undefined) { col.width = json[column].width; } sheet.columns.push(col); } } /* tslint:disable:no-any */ private parserRows(json: any, sheet: Worksheet): void { let rowsLength: number = json.length; sheet.rows = new Rows(); let rowId: number = 0; for (let r: number = 0; r < rowsLength; r++) { let row: Row = this.parserRow(json[r], rowId); rowId = row.index; sheet.rows.add(row); } this.insertMergedCellsStyle(sheet); } private insertMergedCellsStyle(sheet: Worksheet): void { if (this.mergeCells.length > 0) { this.mergedCellsStyle.forEach((value: { x: number, y: number, styleIndex: number }, key: string) => { let row: Row = sheet.rows.filter((item: Row) => { return item.index === value.y; })[0]; if (!isNullOrUndefined(row)) { let cell: Cell = row.cells.filter((item: Cell) => { return item.index === value.x; })[0]; if (!isNullOrUndefined(cell)) { cell.styleIndex = value.styleIndex; } else { let cells: Cell[] = row.cells.filter((item: Cell) => { return item.index <= value.x; }); let insertIndex: number = 0; if (cells.length > 0) { insertIndex = row.cells.indexOf(cells[cells.length - 1]) + 1; } row.cells.splice(insertIndex, 0, this.createCell(value, key)); } } else { let rows: Row[] = sheet.rows.filter((item: Row) => { return item.index <= value.y; }); let rowToInsert: Row = new Row(); rowToInsert.index = value.y; rowToInsert.cells = new Cells(); rowToInsert.cells.add(this.createCell(value, key)); let insertIndex: number = 0; if (rows.length > 0) { insertIndex = sheet.rows.indexOf(rows[rows.length - 1]) + 1; } sheet.rows.splice(insertIndex, 0, rowToInsert); } }); } } private createCell(value: { x: number, y: number, styleIndex: number }, key: string): Cell { let cellToInsert: Cell = new Cell(); cellToInsert.refName = key; cellToInsert.index = value.x; cellToInsert.cellStyle = new CellStyle(); cellToInsert.styleIndex = value.styleIndex; return cellToInsert; } /* tslint:disable:no-any */ private parserRow(json: any, rowIndex: number): Row { let row: Row = new Row(); //Row Height if (json.height !== null && json.height !== undefined) { row.height = json.height; } //Row index if (json.index !== null && json.index !== undefined) { row.index = json.index; } else { throw Error('Row index is missing.'); } if (json.grouping !== null && json.grouping !== undefined) { this.parseGrouping(json.grouping, row); } this.parseCells(json.cells, row); return row; } /* tslint:disable:no-any */ private parseGrouping(json: any, row: Row): void { row.grouping = new Grouping(); if (json.outlineLevel !== undefined) { row.grouping.outlineLevel = json.outlineLevel; } if (json.isCollapsed !== undefined) { row.grouping.isCollapsed = json.isCollapsed; } if (json.isHidden !== undefined) { row.grouping.isHidden = json.isHidden; } } /* tslint:disable:no-any */ private parseCells(json: any, row: Row): void { row.cells = new Cells(); let cellsLength: number = json !== undefined ? json.length : 0; let spanMin: number = 1; let spanMax: number = 1; let curCellIndex: number = 0; for (let cellId: number = 0; cellId < cellsLength; cellId++) { /* tslint:disable:no-any */ let jsonCell: any = json[cellId]; let cell: Cell = new Cell(); //cell index if (jsonCell.index !== null && jsonCell.index !== undefined) { cell.index = jsonCell.index; } else { throw Error('Cell index is missing.'); } if (cell.index < spanMin) { spanMin = cell.index; } else if (cell.index > spanMax) { spanMax = cell.index; } //Update the Cell name cell.refName = this.getCellName(row.index, cell.index); //Row span if (jsonCell.rowSpan !== null && jsonCell.rowSpan !== undefined) { cell.rowSpan = jsonCell.rowSpan - 1; } else { cell.rowSpan = 0; } //Column span if (jsonCell.colSpan !== null && jsonCell.colSpan !== undefined) { cell.colSpan = jsonCell.colSpan - 1; } else { cell.colSpan = 0; } //Hyperlink if (jsonCell.hyperlink !== null && jsonCell.hyperlink !== undefined) { let hyperLink: HyperLink = new HyperLink(); if (jsonCell.hyperlink.target !== undefined) { hyperLink.target = jsonCell.hyperlink.target; if (jsonCell.hyperlink.displayText !== undefined) { cell.value = jsonCell.hyperlink.displayText; } else { cell.value = jsonCell.hyperlink.target; } cell.type = this.getCellValueType(cell.value); hyperLink.ref = cell.refName; hyperLink.rId = (this.mHyperLinks.length + 1); this.mHyperLinks.push(hyperLink); cell.cellStyle = new CellStyle(); /* tslint:disable-next-line:max-line-length */ this.parserCellStyle((jsonCell.style !== undefined ? this.mergeOptions(jsonCell.style, this.hyperlinkStyle) : this.hyperlinkStyle), cell.cellStyle, 'string'); cell.styleIndex = cell.cellStyle.index; } } // formulas if (jsonCell.formula !== null && jsonCell.formula !== undefined) { cell.formula = jsonCell.formula; cell.type = 'formula'; } //Cell value if (jsonCell.value !== null && jsonCell.value !== undefined) { if (cell.formula !== undefined) { cell.value = 0; } else { cell.value = jsonCell.value; cell.type = this.getCellValueType(cell.value); } } if (jsonCell.style !== null && jsonCell.style !== undefined && cell.styleIndex === undefined) { cell.cellStyle = new CellStyle(); if (cell.value instanceof Date) { this.parserCellStyle(jsonCell.style, cell.cellStyle, cell.type, 14); } else { this.parserCellStyle(jsonCell.style, cell.cellStyle, cell.type); } cell.styleIndex = cell.cellStyle.index; } else if (cell.value instanceof Date) { cell.cellStyle = new CellStyle(); this.parserCellStyle({}, cell.cellStyle, cell.type, 14); cell.styleIndex = cell.cellStyle.index; } this.parseCellType(cell); this.mergeCells = this.processMergeCells(cell, row.index, this.mergeCells); row.cells.add(cell); curCellIndex = (cell.index + 1); } row.spans = (spanMin) + ':' + (spanMax); } private GetColors(): Map<string, string> { let colors: Map<string, string>; colors = new Map<string, string>(); /* tslint:disable */ colors.set('WHITE', 'FFFFFFFF'); /* tslint:disable */ colors.set('SILVER', 'FFC0C0C0'); /* tslint:disable */ colors.set('GRAY', 'FF808080'); /* tslint:disable */ colors.set('BLACK', 'FF000000'); /* tslint:disable */ colors.set('RED', 'FFFF0000'); /* tslint:disable */ colors.set('MAROON', 'FF800000'); /* tslint:disable */ colors.set('YELLOW', 'FFFFFF00'); /* tslint:disable */ colors.set('OLIVE', 'FF808000'); /* tslint:disable */ colors.set('LIME', 'FF00FF00'); /* tslint:disable */ colors.set('GREEN', 'FF008000'); /* tslint:disable */ colors.set('AQUA', 'FF00FFFF'); /* tslint:disable */ colors.set('TEAL', 'FF008080'); /* tslint:disable */ colors.set('BLUE', 'FF0000FF'); /* tslint:disable */ colors.set('NAVY', 'FF000080'); /* tslint:disable */ colors.set('FUCHSIA', 'FFFF00FF'); /* tslint:disable */ colors.set('PURPLE', 'FF800080'); return colors; } private processColor(colorVal: string): string { if (colorVal.indexOf('#') === 0) { return colorVal.replace('#', 'FF'); } colorVal = colorVal.toUpperCase(); this.rgbColors = this.GetColors(); if (this.rgbColors.has(colorVal)) { colorVal = this.rgbColors.get(colorVal); } else { colorVal = 'FF000000'; } return colorVal; } private processCellValue(value: string, cell: Cell): string { let cellValue : string = value; if(value.indexOf("<font") !== -1 || value.indexOf("<a") !== -1 || value.indexOf("<b>") !== -1 || value.indexOf("<i>") !== -1 || value.indexOf("<u>") !== -1 ){ let processedVal: string = ''; let startindex: number = value.indexOf('<', 0); let endIndex: number = value.indexOf('>', startindex + 1); if (startindex >= 0 && endIndex >= 0) { if (startindex !== 0) { processedVal += '<r><t xml:space="preserve">' + this.processString(value.substring(0, startindex)) + '</t></r>'; } while (startindex >= 0 && endIndex >= 0 ) { endIndex = value.indexOf('>', startindex + 1); if (endIndex >= 0) { let subString: string = value.substring(startindex + 1, endIndex); startindex = value.indexOf('<', endIndex + 1); if (startindex < 0) { startindex = cellValue.length; } let text = cellValue.substring(endIndex + 1, startindex); if(text.length !== 0) { let subSplit: string[] = subString.split(' '); if (subSplit.length > 0) { processedVal += '<r><rPr>'; } if (subSplit.length > 1) { for (let element of subSplit) { let start: string = element.trim().substring(0,5); switch (start) { case 'size=': processedVal += '<sz val="' + element.substring(6, element.length - 1) + '"/>'; break; case 'face=' : processedVal += '<rFont val="' + element.substring(6, element.length - 1) + '"/>'; break; case 'color': processedVal += '<color rgb="' + this.processColor(element.substring(7, element.length - 1)) + '"/>'; break; case 'href=': let hyperLink: HyperLink = new HyperLink(); hyperLink.target = element.substring(6, element.length - 1).trim(); hyperLink.ref = cell.refName; hyperLink.rId = (this.mHyperLinks.length + 1); this.mHyperLinks.push(hyperLink); processedVal += '<color rgb="FF0000FF"/><u/><b/>'; break; } } } else if (subSplit.length === 1) { let style: string = subSplit[0].trim(); switch (style){ case 'b': processedVal += '<b/>'; break; case 'i': processedVal += '<i/>'; break; case 'u': processedVal += '<u/>'; break; } } processedVal += '</rPr><t xml:space="preserve">' + this.processString(text) + '</t></r>'; } } } if (processedVal === '') { return cellValue; } return processedVal; } else { return cellValue; } }else { return cellValue; } } private applyGlobalStyle(json: any, cellStyle: CellStyle): void { let index: number = 0; if (this.cellStyles.has(json.name)) { cellStyle.index = this.mStyles.filter((a: CellStyle) => (a.name === json.name))[0].index; cellStyle.name = json.name; } } /* tslint:disable:no-any */ private parserCellStyle(json: any, cellStyle: CellStyle, cellType: string): void; /* tslint:disable:no-any */ private parserCellStyle(json: any, cellStyle: CellStyle, cellType: string, defStyleIndex: number): void; /* tslint:disable:no-any */ private parserCellStyle(json: any, cellStyle: CellStyle, cellType: string, defStyleIndex?: number): void { //name if (json.name !== null && json.name !== undefined) { if (cellStyle.isGlobalStyle) { cellStyle.name = json.name; } else { this.applyGlobalStyle(json, cellStyle); return; } } //background color if (json.backColor !== null && json.backColor !== undefined) { cellStyle.backColor = json.backColor; } //borders //leftBorder cellStyle.borders = new Borders(); //AllBorder if (json.borders !== null && json.borders !== undefined) { this.parserBorder(json.borders, cellStyle.borders.all); } //leftborder if (json.leftBorder !== null && json.leftBorder !== undefined) { this.parserBorder(json.leftBorder, cellStyle.borders.left); } //rightBorder if (json.rightBorder !== null && json.rightBorder !== undefined) { this.parserBorder(json.rightBorder, cellStyle.borders.right); } //topBorder if (json.topBorder !== null && json.topBorder !== undefined) { this.parserBorder(json.topBorder, cellStyle.borders.top); } //bottomBorder if (json.bottomBorder !== null && json.bottomBorder !== undefined) { this.parserBorder(json.bottomBorder, cellStyle.borders.bottom); } //fontName if (json.fontName !== null && json.fontName !== undefined) { cellStyle.fontName = json.fontName; } //fontSize if (json.fontSize !== null && json.fontSize !== undefined) { cellStyle.fontSize = json.fontSize; } //fontColor if (json.fontColor !== null && json.fontColor !== undefined) { cellStyle.fontColor = json.fontColor; } //italic if (json.italic !== null && json.italic !== undefined) { cellStyle.italic = json.italic; } //bold if (json.bold !== null && json.bold !== undefined) { cellStyle.bold = json.bold; } //hAlign if (json.hAlign !== null && json.hAlign !== undefined) { cellStyle.hAlign = json.hAlign.toLowerCase(); } //indent if (json.indent !== null && json.indent !== undefined) { cellStyle.indent = json.indent; if (!(cellStyle.hAlign === 'left' || cellStyle.hAlign === 'right')) { cellStyle.hAlign = 'left'; } } if (json.rotation !== null && json.rotation !== undefined) { cellStyle.rotation = json.rotation; } //vAlign if (json.vAlign !== null && json.vAlign !== undefined) { cellStyle.vAlign = json.vAlign.toLowerCase(); } //underline if (json.underline !== null && json.underline !== undefined) { cellStyle.underline = json.underline; } //strikeThrough if (json.strikeThrough !== null && json.strikeThrough !== undefined) { cellStyle.strikeThrough = json.strikeThrough; } //wrapText if (json.wrapText !== null && json.wrapText !== undefined) { cellStyle.wrapText = json.wrapText; } //numberFormat if (json.numberFormat !== null && json.numberFormat !== undefined) { if (json.type !== null && json.type !== undefined) { cellStyle.numberFormat = this.getNumberFormat(json.numberFormat, json.type); } else { cellStyle.numberFormat = this.getNumberFormat(json.numberFormat, cellType); } } else if (defStyleIndex !== undefined) { cellStyle.numFmtId = 14; cellStyle.numberFormat = 'GENERAL'; } else { cellStyle.numberFormat = 'GENERAL'; } cellStyle.index = this.processCellStyle(cellStyle); } private switchNumberFormat(numberFormat: string, type: string): void { let format: string = this.getNumberFormat(numberFormat, type); if (format !== numberFormat) { let numFmt: NumFmt = this.mNumFmt.get(numberFormat); if (numFmt !== undefined) { numFmt.formatCode = format; if (this.mNumFmt.has(format)) { for (let cellStyleXfs of this.mCellStyleXfs) { if (cellStyleXfs.numFmtId === numFmt.numFmtId) { cellStyleXfs.numFmtId = this.mNumFmt.get(format).numFmtId; } } for (let cellXfs of this.mCellXfs) { if (cellXfs.numFmtId === numFmt.numFmtId) { cellXfs.numFmtId = this.mNumFmt.get(format).numFmtId; } } } } } } private getNumberFormat(numberFormat: string, type: string): string { let returnFormat: string; switch (type) { case 'number': try { returnFormat = this.intl.getNumberPattern({ format: numberFormat, currency: this.currency, useGrouping: true }, true); } catch (error) { returnFormat = numberFormat; } break; case 'datetime': try { returnFormat = this.intl.getDatePattern({ skeleton: numberFormat, type: 'dateTime' }, true); } catch (error) { try { returnFormat = this.intl.getDatePattern({ format: numberFormat, type: 'dateTime' }, true); } catch (error) { returnFormat = numberFormat; } } break; case 'date': try { returnFormat = this.intl.getDatePattern({ skeleton: numberFormat, type: 'date' }, true); } catch (error) { try { returnFormat = this.intl.getDatePattern({ format: numberFormat, type: 'date' }, true); } catch (error) { returnFormat = numberFormat; } } break; case 'time': try { returnFormat = this.intl.getDatePattern({ skeleton: numberFormat, type: 'time' }, true); } catch (error) { try { returnFormat = this.intl.getDatePattern({ format: numberFormat, type: 'time' }, true); } catch (error) { returnFormat = numberFormat; } } break; default: returnFormat = numberFormat; break; } return returnFormat; } /* tslint:disable:no-any */ private parserBorder(json: any, border: Border): void { if (json.color !== null && json.color !== undefined) { border.color = json.color; } else { border.color = '#000000'; } if (json.lineStyle !== null && json.lineStyle !== undefined) { border.lineStyle = json.lineStyle; } else { border.lineStyle = 'thin'; } } private processCellStyle(style: CellStyle): number { if (style.isGlobalStyle) { this.processNumFormatId(style); this.mStyles.push(style); return this.mStyles.length; } else { let compareResult: { index: number, result: boolean } = this.compareStyle(style); if (!compareResult.result) { this.processNumFormatId(style); this.mStyles.push(style); return this.mStyles.length; } else { //Return the index of the already existing style. return compareResult.index; } } } private processNumFormatId(style: CellStyle): void { if (style.numberFormat !== 'GENERAL' && !this.mNumFmt.has(style.numberFormat)) { let id: number = this.mNumFmt.size + 164; this.mNumFmt.set(style.numberFormat, new NumFmt(id, style.numberFormat)); } } private isNewFont(toCompareStyle: CellStyle): { index: number, result: boolean } { let result: boolean = false; let index: number = 0; for (let font of this.mFonts) { index++; let fontColor: string = undefined; if (toCompareStyle.fontColor !== undefined) { fontColor = ('FF' + toCompareStyle.fontColor.replace('#', '')); } result = font.color === fontColor && font.b === toCompareStyle.bold && font.i === toCompareStyle.italic && font.u === toCompareStyle.underline && font.strike === toCompareStyle.strikeThrough && font.name === toCompareStyle.fontName && font.sz === toCompareStyle.fontSize; if (result) { break; } } index = index - 1; return { index, result }; } private isNewBorder(toCompareStyle: CellStyle): boolean { let bStyle: CellStyle = new CellStyle(); if (this.isAllBorder(toCompareStyle.borders)) { return (bStyle.borders.all.color === toCompareStyle.borders.all.color && bStyle.borders.all.lineStyle === toCompareStyle.borders.all.lineStyle); } else { return (bStyle.borders.left.color === toCompareStyle.borders.left.color && bStyle.borders.left.lineStyle === toCompareStyle.borders.left.lineStyle && bStyle.borders.right.color === toCompareStyle.borders.right.color && bStyle.borders.right.lineStyle === toCompareStyle.borders.right.lineStyle && bStyle.borders.top.color === toCompareStyle.borders.top.color && bStyle.borders.top.lineStyle === toCompareStyle.borders.top.lineStyle && bStyle.borders.bottom.color === toCompareStyle.borders.bottom.color && bStyle.borders.bottom.lineStyle === toCompareStyle.borders.bottom.lineStyle); } } private isAllBorder(toCompareBorder: Borders): boolean { let allBorderStyle: CellStyle = new CellStyle(); return allBorderStyle.borders.all.color !== toCompareBorder.all.color && allBorderStyle.borders.all.lineStyle !== toCompareBorder.all.lineStyle; } private compareStyle(toCompareStyle: CellStyle): { index: number, result: boolean } { let result: boolean = true; let index: number = 0; let globalStyleIndex: number = 0; for (let baseStyle of this.mStyles) { result = baseStyle.isGlobalStyle ? false : (baseStyle.backColor === toCompareStyle.backColor && baseStyle.bold === toCompareStyle.bold && baseStyle.numFmtId === toCompareStyle.numFmtId && baseStyle.numberFormat === toCompareStyle.numberFormat && baseStyle.type === toCompareStyle.type && baseStyle.fontColor === toCompareStyle.fontColor && baseStyle.fontName === toCompareStyle.fontName && baseStyle.fontSize === toCompareStyle.fontSize && baseStyle.hAlign === toCompareStyle.hAlign && baseStyle.italic === toCompareStyle.italic && baseStyle.underline === toCompareStyle.underline && baseStyle.strikeThrough === toCompareStyle.strikeThrough && baseStyle.vAlign === toCompareStyle.vAlign && baseStyle.indent === toCompareStyle.indent && baseStyle.rotation === toCompareStyle.rotation && baseStyle.wrapText === toCompareStyle.wrapText && (baseStyle.borders.all.color === toCompareStyle.borders.all.color && baseStyle.borders.all.lineStyle === toCompareStyle.borders.all.lineStyle) && (baseStyle.borders.left.color === toCompareStyle.borders.left.color && baseStyle.borders.left.lineStyle === toCompareStyle.borders.left.lineStyle && baseStyle.borders.right.color === toCompareStyle.borders.right.color && baseStyle.borders.right.lineStyle === toCompareStyle.borders.right.lineStyle && baseStyle.borders.top.color === toCompareStyle.borders.top.color && baseStyle.borders.top.lineStyle === toCompareStyle.borders.top.lineStyle && baseStyle.borders.bottom.color === toCompareStyle.borders.bottom.color && baseStyle.borders.bottom.lineStyle === toCompareStyle.borders.bottom.lineStyle)); if (result) { index = baseStyle.index; break; } } return { index, result }; } private contains(array: string[], item: string): boolean { let index: number = array.indexOf(item); return index > -1 && index < array.length; } private getCellValueType(value: any): string { if (value instanceof Date) { return 'datetime'; } else if (typeof (value) === 'boolean') { return 'boolean'; } else if (typeof (value) === 'number') { return 'number'; } else { return 'string'; } } private parseCellType(cell: Cell): void { let type: string = cell.type; let saveType: string; let value: any = cell.value; switch (type) { case 'datetime': value = this.toOADate(value); if (cell.cellStyle !== undefined && cell.cellStyle.name !== undefined) { if (this.globalStyles.has(cell.cellStyle.name)) { let value: any = this.globalStyles.get(cell.cellStyle.name); this.switchNumberFormat(value.format, value.type); } } saveType = 'n'; break; //TODO: Update the number format index and style case 'boolean': value = value ? 1 : 0; saveType = 'b'; break; case 'number': saveType = 'n'; if (cell.cellStyle !== undefined && cell.cellStyle.name !== undefined) { if (this.globalStyles.has(cell.cellStyle.name)) { this.switchNumberFormat(this.globalStyles.get(cell.cellStyle.name).format, 'number'); } } break; case 'string': this.sharedStringCount++; saveType = 's'; let sstvalue = this.processCellValue(value, cell); if (!this.contains(this.sharedString, sstvalue)) { this.sharedString.push(sstvalue); } value = this.sharedString.indexOf(sstvalue); break; default: break; } cell.saveType = saveType; cell.value = value; } private parserImages(json: any, sheet: Worksheet): void { let imagesLength: number = json.length; sheet.images = []; let imageId: number = 0; for (let p: number = 0; p < imagesLength; p++) { let image: Image = this.parserImage(json[p]); sheet.images.push(image); } } private parseFilters(json: any, sheet: Worksheet): void { sheet.autoFilters = new AutoFilters(); if (json.row !== null && json.row !== undefined) sheet.autoFilters.row = json.row; else throw new Error('Argument Null Exception: row null or empty'); if (json.lastRow !== null && json.lastRow !== undefined) sheet.autoFilters.lastRow = json.lastRow; else throw new Error('Argument Null Exception: lastRow cannot be null or empty'); if (json.column !== null && json.column !== undefined) sheet.autoFilters.column = json.column; else throw new Error('Argument Null Exception: column cannot be null or empty'); if (json.lastColumn !== null && json.row !== undefined) sheet.autoFilters.lastColumn = json.lastColumn; else throw new Error('Argument Null Exception: lastColumn cannot be null or empty'); } private parserImage(json: any): Image { let image: Image = new Image(); if (json.image !== null && json.image !== undefined) { image.image = json.image; } if (json.row !== null && json.row !== undefined) { image.row = json.row; } if (json.column !== null && json.column !== undefined) { image.column = json.column; } if (json.lastRow !== null && json.lastRow !== undefined) { image.lastRow = json.lastRow; } if (json.lastColumn !== null && json.lastColumn !== undefined) { image.lastColumn = json.lastColumn; } if (json.width !== null && json.width !== undefined) { image.width = json.width; } if (json.height !== null && json.height !== undefined) { image.height = json.height; } if (json.horizontalFlip !== null && json.horizontalFlip !== undefined) { image.horizontalFlip = json.horizontalFlip; } if (json.verticalFlip !== null && json.verticalFlip !== undefined) { image.verticalFlip = json.verticalFlip; } if (json.rotation !== null && json.rotation !== undefined) { image.rotation = json.rotation; } return image; } public saveAsBlob(blobSaveType: BlobSaveType): Promise<{ blobData: Blob }> { switch (blobSaveType) { case 'text/csv': return new Promise((resolve: Function, reject: Function) => { let obj: any = {}; obj.blobData = this.csvHelper.saveAsBlob(); resolve(obj); }); default: return new Promise((resolve: Function, reject: Function) => { this.saveInternal(); this.mArchive.saveAsBlob().then((blob: Blob) => { let obj: any = {}; obj.blobData = new Blob([blob], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); resolve(obj); }); }); } } public save(fileName: string, proxyUrl?: string): void { if (fileName === null || fileName === undefined || fileName === '') { throw new Error('Argument Null Exception: fileName cannot be null or empty'); } let xlsxMatch: RegExpMatchArray = fileName.match('.xlsx$'); let csvMatch: RegExpMatchArray = fileName.match('.csv$'); if (xlsxMatch !== null && xlsxMatch[0] === ('.' + this.mSaveType)) { this.saveInternal(); this.mArchive.save(fileName).then(() => { this.mArchive.destroy(); }); } else if (csvMatch !== null && csvMatch[0] === ('.' + this.mSaveType)) { this.csvHelper.save(fileName); } else { throw Error('Save type and file extension is different.'); } } private saveInternal(): void { this.saveWorkbook(); this.saveWorksheets(); this.saveSharedString(); this.saveStyles(); this.saveApp(this.builtInProperties); this.saveCore(this.builtInProperties); this.saveContentType(); this.saveTopLevelRelation(); this.saveWorkbookRelation(); } private saveWorkbook(): void { /* tslint:disable-next-line:max-line-length */ let workbookTemp: string = '<?xml version="1.0" encoding="utf-8"?><workbook xmlns:r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns= "http://schemas.openxmlformats.org/spreadsheetml/2006/main"><workbookPr codeName="ThisWorkbook" defaultThemeVersion= "153222"/><bookViews><workbookView activeTab="0"/></bookViews>'; let sheets: string = '<sheets>'; let length: number = this.worksheets.length; for (let i: number = 0; i < length; i++) { /* tslint:disable-next-line:max-line-length */ let sheetName= this.worksheets[i].name; sheetName= sheetName.replace("&", "&amp;"); sheetName= sheetName.replace("<", "&lt;"); sheetName= sheetName.replace(">", "&gt;"); sheetName= sheetName.replace("\"", "&quot;"); sheets += '<sheet name="' + sheetName + '" sheetId="' + (i + 1).toString() + '" r:id ="rId' + (i + 1).toString() + '" />'; } sheets += '</sheets>'; workbookTemp += sheets; if (this.printTitles.size > 0) { let printTitle: string = '<definedNames>'; this.printTitles.forEach((value: string, key: number) => { printTitle += '<definedName name="_xlnm.Print_Titles" localSheetId="' + key + '">' + value + '</definedName>'; }); printTitle += '</definedNames>'; workbookTemp += printTitle; } this.addToArchive(workbookTemp + '</workbook>', 'xl/workbook.xml'); } private saveWorksheets(): void { let length: number = this.worksheets.length; for (let i: number = 0; i < length; i++) { this.saveWorksheet(this.worksheets[i], i); } } private saveWorksheet(sheet: Worksheet, index: number): void { let sheetBlob: BlobHelper = new BlobHelper(); /* tslint:disable-next-line:max-line-length */ let sheetString: string = '<?xml version="1.0" encoding="utf-8" standalone="yes"?><worksheet xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'; if (!sheet.isSummaryRowBelow) { sheetString += ('<sheetPr>' + '<outlinePr ' + 'summaryBelow="0" >' + '</outlinePr>' + '</sheetPr>'); } else { sheetString += ('<sheetPr />'); } sheetString += this.saveSheetView(sheet); if (sheet.columns !== undefined) { let colString: string = '<cols>'; for (let column of sheet.columns) { /* tslint:disable-next-line:max-line-length */ if (column.width !== undefined) { colString += '<col min="' + (column.index) + '" max="' + (column.index) + '" width="' + this.pixelsToColumnWidth(column.width) + '" customWidth="1" />'; } else { colString += '<col min="' + (column.index) + '" max="' + (column.index) + '" width="' + '8.43' + '" customWidth="1" />'; } } sheetString += (colString + '</cols>'); } sheetString += ('<sheetData>'); sheetBlob.append(sheetString); sheetString = ''; if (sheet.rows !== undefined) { for (let row of sheet.rows) { let rowString: string = '<row r="' + (row.index) + '" '; if (!isNullOrUndefined(row.spans)) { rowString += 'spans="' + row.spans + '" '; } if (row.height !== undefined) { rowString += ('ht="' + this.pixelsToRowHeight(row.height) + '" customHeight="1" '); } if (row.grouping !== undefined) { if (row.grouping.isHidden) { rowString += ('hidden="1" '); } if (row.grouping.outlineLevel !== undefined) { rowString += ('outlineLevel="' + row.grouping.outlineLevel + '" '); } if (row.grouping.isCollapsed) { rowString += ('collapsed="1" '); } } rowString += ('>'); for (let cell of row.cells) { if (cell !== undefined && (cell.value !== undefined || cell.cellStyle !== undefined)) { rowString += ('<c r="' + cell.refName + '" '); if (cell.saveType !== undefined) { rowString += ('t="' + cell.saveType + '" '); } if (cell.styleIndex !== undefined) { rowString += ('s="' + cell.styleIndex + '" '); } rowString += (' >'); if (cell.formula !== undefined) { rowString += ('<f>' + cell.formula + '</f>'); } if (cell.value !== undefined) { rowString += ('<v>' + cell.value + '</v></c>'); } else { rowString += ('</c>'); } } } rowString += ('</row>'); sheetBlob.append(rowString); } } sheetString += ('</sheetData>'); /* tslint:disable-next-line:max-line-length */ if(sheet.autoFilters !== null && sheet.autoFilters !== undefined) sheetString += ('<autoFilter ref="' + this.getCellName(sheet.autoFilters.row,sheet.autoFilters.column) + ':' + this.getCellName(sheet.autoFilters.lastRow,sheet.autoFilters.lastColumn) + '"/>'); if (sheet.mergeCells.length > 0) { sheetString += ('<mergeCells count="' + sheet.mergeCells.length + '">'); for (let mCell of sheet.mergeCells) { sheetString += ('<mergeCell ref="' + mCell.ref + '" />'); } sheetString += ('</mergeCells>'); } if (sheet.hyperLinks.length > 0) { sheetString += ('<hyperlinks>'); for (let hLink of sheet.hyperLinks) { sheetString += ('<hyperlink ref="' + hLink.ref + '" r:id="rId' + hLink.rId + '" />'); } sheetString += ('</hyperlinks>'); } /* tslint:disable-next-line:max-line-length */ sheetString += ('<pageMargins left="0.75" right="0.75" top="1" bottom="1" header="0.5" footer="0.5" /><headerFooter scaleWithDoc="1" alignWithMargins="0" differentFirst="0" differentOddEven="0" />'); if(sheet.images != undefined && sheet.images.length > 0){ this.drawingCount++; this.saveDrawings(sheet, sheet.index); sheetString += '<drawing r:id="rId'+ (sheet.hyperLinks.length + 1) + '"/>'; } this.addToArchive(this.saveSheetRelations(sheet), ('xl/worksheets/_rels/sheet' + sheet.index + '.xml.rels')); sheetBlob.append(sheetString+'</worksheet>'); this.addToArchive(sheetBlob.getBlob(), 'xl/worksheets' + '/sheet' + (index + 1) + '.xml'); } private saveDrawings(sheet: Worksheet, index: number): void { let drawings: BlobHelper = new BlobHelper(); /* tslint:disable-next-line:max-line-length */ let sheetDrawingString: string = '<xdr:wsDr xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">'; if (sheet.images !== undefined) { let imgId: number = 0; for (let pic of sheet.images) { if(pic.height !== undefined && pic.width !== undefined){ this.updatelastRowOffset(sheet, pic); this.updatelastColumnOffSet(sheet, pic); pic.lastRow -= 1; pic.lastColumn -= 1; }else if(pic.lastRow !== undefined && pic.lastColumn !== undefined) { pic.lastRowOffset = 0; pic.lastColOffset = 0; } imgId++; sheetDrawingString += '<xdr:twoCellAnchor editAs="oneCell">'; sheetDrawingString += '<xdr:from><xdr:col>'; //col sheetDrawingString += pic.column - 1; sheetDrawingString += '</xdr:col><xdr:colOff>'; //colOff sheetDrawingString += 0; sheetDrawingString += '</xdr:colOff><xdr:row>'; //row sheetDrawingString += pic.row - 1; sheetDrawingString += '</xdr:row><xdr:rowOff>'; //rowOff sheetDrawingString += 0; sheetDrawingString += '</xdr:rowOff></xdr:from>'; sheetDrawingString += '<xdr:to><xdr:col>'; //col sheetDrawingString += pic.lastColumn; sheetDrawingString += '</xdr:col><xdr:colOff>'; //colOff sheetDrawingString += pic.lastColOffset; sheetDrawingString += '</xdr:colOff><xdr:row>'; //row sheetDrawingString += pic.lastRow; sheetDrawingString += '</xdr:row><xdr:rowOff>'; //rowOff sheetDrawingString += pic.lastRowOffset; sheetDrawingString += '</xdr:rowOff></xdr:to>'; sheetDrawingString += '<xdr:pic>'; sheetDrawingString += '<xdr:nvPicPr>'; sheetDrawingString += '<xdr:cNvPr id="' + imgId + '" name="Picture ' + imgId + '"> </xdr:cNvPr>'; sheetDrawingString += '<xdr:cNvPicPr><a:picLocks noChangeAspect="1"/></xdr:cNvPicPr> </xdr:nvPicPr>'; sheetDrawingString += '<xdr:blipFill>'; /* tslint:disable-next-line:max-line-length */ sheetDrawingString += '<a:blip xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" r:embed="rId'+ imgId + '" cstate="print">'; sheetDrawingString += '</a:blip><a:stretch><a:fillRect /></a:stretch></xdr:blipFill>'; sheetDrawingString += '<xdr:spPr>'; sheetDrawingString += '<a:xfrm'; if (pic.rotation != undefined && pic.rotation <= 3600 && pic.rotation >= -3600) { sheetDrawingString +=' rot="' + (pic.rotation * 60000) + '"'; } if (pic.verticalFlip != undefined && pic.verticalFlip != false) { sheetDrawingString += ' flipV="1"'; } if (pic.horizontalFlip != undefined && pic.horizontalFlip != false) { sheetDrawingString += ' flipH="1"'; } sheetDrawingString += '/>'; sheetDrawingString += '<a:prstGeom prst="rect"><a:avLst /></a:prstGeom></xdr:spPr>'; sheetDrawingString += '</xdr:pic><xdr:clientData /></xdr:twoCellAnchor>'; let imageFile: BlobHelper = new BlobHelper(); let imageData:Blob = this.convertBase64toImage(pic.image); this.imageCount += 1; this.addToArchive(imageData, 'xl/media/image' + this.imageCount + '.png'); } drawings.append(sheetDrawingString); drawings.append('</xdr:wsDr>'); this.saveDrawingRelations(sheet); this.addToArchive(drawings.getBlob(), 'xl/drawings/drawing'+ this.drawingCount +'.xml'); } } private updatelastRowOffset(sheet : Worksheet, picture: Image) : void{ let iCurHeight = picture.height; let iCurRow = picture.row; let iCurOffset = 0; while( iCurHeight >= 0 ) { let iRowHeight = 0; if(sheet.rows !== undefined && sheet.rows[iCurRow - 1] !== undefined) iRowHeight = this.convertToPixels(sheet.rows[iCurRow - 1].height === undefined? 15: sheet.rows[iCurRow - 1].height); else iRowHeight = this.convertToPixels(15); let iSpaceInCell = iRowHeight - (iCurOffset * iRowHeight / 256); if( iSpaceInCell > iCurHeight ) { picture.lastRow = iCurRow; picture.lastRowOffset = iCurOffset + (iCurHeight * 256 / iRowHeight); let rowHiddenHeight = 0; if(sheet.rows !== undefined && sheet.rows[iCurRow - 1] !== undefined) rowHiddenHeight = this.convertToPixels(sheet.rows[iCurRow - 1].height === undefined ? 15 :sheet.rows[iCurRow - 1].height ); else rowHiddenHeight = this.convertToPixels(15); picture.lastRowOffset = (rowHiddenHeight * picture.lastRowOffset)/256; picture.lastRowOffset = Math.round(picture.lastRowOffset / this.unitsProportions[7]); break; } else { iCurHeight -= iSpaceInCell; iCurRow++; iCurOffset = 0; } } } private updatelastColumnOffSet(sheet : Worksheet, picture: Image) : void{ let iCurWidth = picture.width; let iCurCol = picture.column; let iCurOffset = 0; while( iCurWidth >= 0 ) { let iColWidth = 0; if(sheet.columns !== undefined && sheet.columns[iCurCol - 1] !== undefined) iColWidth = this.ColumnWidthToPixels(sheet.columns[iCurCol - 1].width === undefined ? 8.43 :sheet.columns[iCurCol - 1].width ); else iColWidth = this.ColumnWidthToPixels(8.43); let iSpaceInCell = iColWidth - (iCurOffset * iColWidth / 1024); if( iSpaceInCell > iCurWidth ) { picture.lastColumn = iCurCol; picture.lastColOffset = iCurOffset + (iCurWidth * 1024 / iColWidth); let colHiddenWidth = 0; if(sheet.columns !== undefined && sheet.columns[iCurCol - 1] !== undefined) colHiddenWidth = this.ColumnWidthToPixels(sheet.columns[iCurCol - 1].width === undefined ? 8.43 :sheet.columns[iCurCol].width ); else colHiddenWidth = this.ColumnWidthToPixels(8.43); picture.lastColOffset = (colHiddenWidth * picture.lastColOffset)/1024; picture.lastColOffset = Math.round(picture.lastColOffset / this.unitsProportions[7]); break; } else { iCurWidth -= iSpaceInCell; iCurCol++; iCurOffset = 0; } } } private convertToPixels(value: number): number{ return value * this.unitsProportions[6]; } private convertBase64toImage(img: string) : Blob { const byteStr = window.atob(img); const buffer = new ArrayBuffer(byteStr.length); const data = new Uint8Array(buffer); for (let i = 0; i < byteStr.length; i++) { data[i] = byteStr.charCodeAt(i); } const blob = new Blob([data], { type: 'image/png' }); return blob; } private saveDrawingRelations(sheet: Worksheet) { /* tslint:disable-next-line:max-line-length */ let drawingRelation: string = '<?xml version="1.0" encoding="utf-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'; let length: number = sheet.images.length; let id: number = this.imageCount - sheet.images.length; for (let i: number = 1; i <= length; i++ ) { id++; /* tslint:disable-next-line:max-line-length */ drawingRelation += '<Relationship Id="rId' + i + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="../media/image' + id + '.png" />'; } this.addToArchive((drawingRelation + '</Relationships>'), 'xl/drawings/_rels/drawing'+ this.drawingCount +'.xml.rels'); } private pixelsToColumnWidth(pixels: number): number { let dDigitWidth: number = 7; let val: number = (pixels > dDigitWidth + 5) ? this.trunc((pixels - 5) / dDigitWidth * 100 + 0.5) / 100 : pixels / (dDigitWidth + 5); return (val > 1) ? ((val * dDigitWidth + 5) / dDigitWidth * 256.0) / 256.0 : (val * (dDigitWidth + 5) / dDigitWidth * 256.0) / 256.0; } private ColumnWidthToPixels(val: number): number { let dDigitWidth: number = 7; let fileWidth = (val > 1) ? ((val * dDigitWidth + 5) / dDigitWidth * 256.0) / 256.0 : (val * (dDigitWidth + 5) / dDigitWidth * 256.0) / 256.0; return this.trunc( ( ( 256 * fileWidth + this.trunc( 128 / dDigitWidth ) ) / 256 ) * dDigitWidth ); } private trunc(x: number): number { let n: number = x - x % 1; return n === 0 && (x < 0 || (x === 0 && (1 / x !== 1 / 0))) ? -0 : n; } private pixelsToRowHeight(pixels: number): number { return (pixels * this.unitsProportions[5] / this.unitsProportions[6]); } private saveSheetRelations(sheet: Worksheet): string { /* tslint:disable-next-line:max-line-length */ let relStr: string = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'; for (let hLink of sheet.hyperLinks) { /* tslint:disable-next-line:max-line-length */ relStr += '<Relationship Id="rId' + hLink.rId + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="' + this.processString(hLink.target) + '" TargetMode="External" />'; } if(sheet.images != undefined && sheet.images.length > 0) { /* tslint:disable-next-line:max-line-length */ relStr += '<Relationship Id="rId'+ (sheet.hyperLinks.length + 1) +'" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing" Target="../drawings/drawing'+ this.drawingCount +'.xml" />' } relStr += '</Relationships>'; return relStr; } private saveSheetView(sheet: Worksheet): string { let paneString: string = '<sheetViews><sheetView workbookViewId="0" '; if(sheet.enableRtl === true) { paneString += 'rightToLeft="1"'; } if (sheet.showGridLines === false) { paneString += 'showGridLines="0" >'; } else { paneString += '>'; } if (sheet.freezePanes !== undefined) { paneString += '<pane state="frozen"' + ' topLeftCell="' + sheet.freezePanes.leftCell + '" '; if (sheet.freezePanes.row !== 0) { paneString += 'ySplit="' + sheet.freezePanes.row + '" '; } if (sheet.freezePanes.column !== 0) { paneString += 'xSplit="' + sheet.freezePanes.column + '" '; } paneString += '/>'; } paneString += '</sheetView></sheetViews > '; return paneString; } private saveSharedString(): void { let length: number = this.sharedString.length; if (length > 0) { /* tslint:disable-next-line:max-line-length */ let sstStart: string = '<?xml version="1.0" encoding="utf-8"?><sst uniqueCount="' + length + '" count="' + this.sharedStringCount + '" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'; let si: string = ''; for (let i: number = 0; i < length; i++) { if (this.sharedString[i].indexOf('<r>') !== 0) { si += '<si><t>'; si += this.processString(this.sharedString[i]); si += '</t></si>'; } else { si += '<si>'; si += this.sharedString[i]; si += '</si>'; } } si += '</sst>'; this.addToArchive(sstStart + si, 'xl/sharedStrings.xml'); } } private processString(value: string): string { if (value.indexOf('&') !== -1) { value = value.replace(/&/g, '&amp;'); } if (value.indexOf('<') !== -1) { value = value.replace(/</g, '&lt;'); } if (value.indexOf('>') !== -1) { value = value.replace(/>/g, '&gt;'); } return value; } private saveStyles(): void { this.updateCellXfsStyleXfs(); /* tslint:disable-next-line:max-line-length */ let styleTemp: string = '<?xml version="1.0" encoding="utf-8"?><styleSheet xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'; styleTemp += this.saveNumberFormats(); styleTemp += this.saveFonts(); styleTemp += this.saveFills(); styleTemp += this.saveBorders(); styleTemp += this.saveCellStyleXfs(); styleTemp += this.saveCellXfs(); styleTemp += this.saveCellStyles(); this.addToArchive(styleTemp + '</styleSheet>', 'xl/styles.xml'); } private updateCellXfsStyleXfs(): void { for (let style of this.mStyles) { let cellXfs: any = undefined; if (style.isGlobalStyle) { cellXfs = new CellStyleXfs(); cellXfs.xfId = (style.index - 1); } else { cellXfs = new CellXfs(); cellXfs.xfId = 0; } //Add font let compareFontResult: { index: number, result: boolean } = this.isNewFont(style); if (!compareFontResult.result) { let font: Font = new Font(); font.b = style.bold; font.i = style.italic; font.name = style.fontName; font.sz = style.fontSize; font.u = style.underline; font.strike = style.strikeThrough; font.color = ('FF' + style.fontColor.replace('#', '')); this.mFonts.push(font); cellXfs.fontId = this.mFonts.length - 1; } else { cellXfs.fontId = compareFontResult.index; } //Add fill if (style.backColor !== 'none') { let backColor: string = 'FF' + style.backColor.replace('#', ''); if (this.mFills.has(backColor)) { let fillId: number = this.mFills.get(backColor); cellXfs.fillId = fillId; } else { let fillId: number = this.mFills.size + 2; this.mFills.set(backColor, fillId); cellXfs.fillId = (fillId); } } else { cellXfs.fillId = 0; } //Add border if (!this.isNewBorder(style)) { this.mBorders.push(style.borders); cellXfs.borderId = this.mBorders.length; } else { cellXfs.borderId = 0; } //Add Number Format if (style.numberFormat !== 'GENERAL') { if (this.mNumFmt.has(style.numberFormat)) { let numFmt: NumFmt = this.mNumFmt.get(style.numberFormat); cellXfs.numFmtId = numFmt.numFmtId; } else { let id: number = this.mNumFmt.size + 164; this.mNumFmt.set(style.numberFormat, new NumFmt(id, style.numberFormat)); cellXfs.numFmtId = id; } } else { if (style.numberFormat === 'GENERAL' && style.numFmtId === 14) { cellXfs.numFmtId = 14; } else { cellXfs.numFmtId = 0; } } //Add alignment if (!style.isGlobalStyle) { cellXfs.applyAlignment = 1; } cellXfs.alignment = new Alignment(); cellXfs.alignment.indent = style.indent; cellXfs.alignment.horizontal = style.hAlign; cellXfs.alignment.vertical = style.vAlign; cellXfs.alignment.wrapText = style.wrapText ? 1 : 0; cellXfs.alignment.rotation = style.rotation; if (style.isGlobalStyle) { this.mCellStyleXfs.push(cellXfs); this.mCellXfs.push(cellXfs); } else { //Add cellxfs this.mCellXfs.push(cellXfs); } } } private saveNumberFormats(): string { if (this.mNumFmt.size >= 1) { let numFmtStyle: string = '<numFmts count="' + (this.mNumFmt.size) + '">'; this.mNumFmt.forEach((value: NumFmt, key: string) => { numFmtStyle += '<numFmt numFmtId="' + value.numFmtId + '" formatCode="' + value.formatCode.replace(/"/g, '&quot;') + '" />'; }); return (numFmtStyle += '</numFmts>'); } else { return ''; } } private saveFonts(): string { /* tslint:disable-next-line:max-line-length */ let fontStyle: string = '<fonts count="' + (this.mFonts.length) + '">'; if (this.mFonts.length >= 1) { for (let font of this.mFonts) { fontStyle += '<font>'; if (font.b) { fontStyle += '<b />'; } if (font.i) { fontStyle += '<i />'; } if (font.u) { fontStyle += '<u />'; } if (font.strike) { fontStyle += '<strike />'; } fontStyle += '<sz val="' + font.sz + '" />'; fontStyle += '<color rgb="' + font.color + '" />'; fontStyle += '<name val="' + font.name + '" /></font>'; } } return fontStyle + '</fonts>'; } private saveFills(): string { /* tslint:disable-next-line:max-line-length */ let fillsStyle: string = '<fills count="' + (this.mFills.size + 2) + '"><fill><patternFill patternType="none"></patternFill></fill><fill><patternFill patternType="gray125"></patternFill></fill>'; if (this.mFills.size >= 1) { this.mFills.forEach((value: number, key: string) => { /* tslint:disable-next-line:max-line-length */ fillsStyle += '<fill><patternFill patternType="solid"><fgColor rgb="' + key + '" /><bgColor rgb="FFFFFFFF" /></patternFill></fill>'; }); } return fillsStyle + '</fills>'; } private saveBorders(): string { /* tslint:disable-next-line:max-line-length */ let bordersStyle: string = '<borders count="' + (this.mBorders.length + 1) + '"><border><left /><right /><top /><bottom /><diagonal /></border>'; if (this.mBorders.length >= 1) { for (let borders of this.mBorders) { if (this.isAllBorder(borders)) { let color: string = borders.all.color.replace('#', ''); let lineStyle: string = borders.all.lineStyle; /* tslint:disable-next-line:max-line-length */ bordersStyle += '<border><left style="' + lineStyle + '"><color rgb="FF' + color + '" /></left><right style="' + lineStyle + '"><color rgb="FF' + color + '" /></right><top style="' + lineStyle + '"><color rgb="FF' + color + '" /></top><bottom style="' + lineStyle + '"><color rgb="FF' + color + '" /></bottom></border>'; } else { /* tslint:disable-next-line:max-line-length */ bordersStyle += '<border><left style="' + borders.left.lineStyle + '"><color rgb="FF' + borders.left.color.replace('#', '') + '" /></left><right style="' + borders.right.lineStyle + '"><color rgb="FF' + borders.right.color.replace('#', '') + '" /></right><top style="' + borders.top.lineStyle + '"><color rgb="FF' + borders.top.color.replace('#', '') + '" /></top><bottom style="' + borders.bottom.lineStyle + '"><color rgb="FF' + borders.bottom.color.replace('#', '') + '" /></bottom></border>'; } } } return bordersStyle + '</borders>'; } private saveCellStyles(): string { let cellStyleString: string = '<cellStyles count="' + (this.cellStyles.size) + '">'; this.cellStyles.forEach((value: CellStyles, key: string) => { cellStyleString += '<cellStyle name="' + key + '" xfId="' + this.cellStyles.get(key).xfId + '"'; if (key === 'Normal') { cellStyleString += ' builtinId="0"'; } cellStyleString += ' />'; }); return cellStyleString += '</cellStyles>'; } private saveCellStyleXfs(): string { /* tslint:disable-next-line:max-line-length */ let cellXfsStyle: string = '<cellStyleXfs count="' + (this.mCellStyleXfs.length + 1) + '"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" />'; if (this.mCellStyleXfs.length >= 1) { for (let cellStyleXf of this.mCellStyleXfs) { /* tslint:disable-next-line:max-line-length */ cellXfsStyle += '<xf numFmtId="' + cellStyleXf.numFmtId + '" fontId="' + cellStyleXf.fontId + '" fillId="' + cellStyleXf.fillId + '" borderId="' + cellStyleXf.borderId + '" '; if (cellStyleXf.alignment !== undefined) { cellXfsStyle += '>' + this.saveAlignment(cellStyleXf) + '</xf>'; } else { cellXfsStyle += ' />'; } } } return cellXfsStyle + '</cellStyleXfs>'; } private saveCellXfs(): string { /* tslint:disable-next-line:max-line-length */ let cellXfsStyle: string = '<cellXfs count="' + (this.mCellXfs.length + 1) + '"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" />'; if (this.mCellXfs.length >= 1) { for (let cellXf of this.mCellXfs) { /* tslint:disable-next-line:max-line-length */ cellXfsStyle += '<xf numFmtId="' + cellXf.numFmtId + '" fontId="' + cellXf.fontId + '" fillId="' + cellXf.fillId + '" borderId="' + cellXf.borderId + '" xfId="' + cellXf.xfId + '" '; if (cellXf.applyAlignment === 1) { cellXfsStyle += 'applyAlignment="1"'; } cellXfsStyle += '>' + this.saveAlignment(cellXf) + '</xf>'; } } return cellXfsStyle + '</cellXfs>'; } private saveAlignment(cellXf: any): string { let alignString: string = '<alignment '; if (cellXf.alignment.horizontal !== undefined) { alignString += 'horizontal="' + cellXf.alignment.horizontal + '" '; } if (cellXf.alignment.indent !== undefined && cellXf.alignment.indent !== 0 ) { alignString += 'indent="' + cellXf.alignment.indent + '" '; }else if (cellXf.alignment.rotation !== undefined && cellXf.alignment.rotation !== 0 ) { alignString += 'textRotation="' + cellXf.alignment.rotation + '" '; } if (cellXf.alignment.vertical !== undefined) { alignString += 'vertical="' + cellXf.alignment.vertical + '" '; } alignString += 'wrapText="' + cellXf.alignment.wrapText + '" />'; return alignString; } private saveApp(builtInProperties: BuiltInProperties): void { /* tslint:disable-next-line:max-line-length */ let appString: string = '<?xml version="1.0" encoding="utf-8" standalone="yes"?><Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"><Application>Essential XlsIO</Application>'; if (builtInProperties !== undefined) { if (builtInProperties.manager !== undefined) { appString += '<Manager>' + builtInProperties.manager + '</Manager>'; } if (builtInProperties.company !== undefined) { appString += '<Company>' + builtInProperties.company + '</Company>'; } } this.addToArchive((appString + '</Properties>'), 'docProps/app.xml'); } private saveCore(builtInProperties: BuiltInProperties): void { let createdDate: Date = new Date(); /* tslint:disable-next-line:max-line-length */ let coreString: string = '<?xml version="1.0" encoding="utf-8" standalone="yes"?><cp:coreProperties xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties">'; if (this.builtInProperties !== undefined) { if (builtInProperties.author !== undefined) { coreString += '<dc:creator>' + builtInProperties.author + '</dc:creator>'; } if (builtInProperties.subject !== undefined) { coreString += '<dc:subject>' + builtInProperties.subject + '</dc:subject>'; } if (builtInProperties.category !== undefined) { coreString += '<cp:category>' + builtInProperties.category + '</cp:category>'; } if (builtInProperties.comments !== undefined) { coreString += '<dc:description>' + builtInProperties.comments + '</dc:description>'; } if (builtInProperties.title !== undefined) { coreString += '<dc:title>' + builtInProperties.title + '</dc:title>'; } if (builtInProperties.tags !== undefined) { coreString += '<cp:keywords>' + builtInProperties.tags + '</cp:keywords>'; } if (builtInProperties.status !== undefined) { coreString += '<cp:contentStatus>' + builtInProperties.status + '</cp:contentStatus>'; } if (builtInProperties.createdDate !== undefined) { /* tslint:disable-next-line:max-line-length */ coreString += '<dcterms:created xsi:type="dcterms:W3CDTF">' + builtInProperties.createdDate.toISOString() + '</dcterms:created>'; } else { coreString += '<dcterms:created xsi:type="dcterms:W3CDTF">' + createdDate.toISOString() + '</dcterms:created>'; } if (builtInProperties.modifiedDate !== undefined) { /* tslint:disable-next-line:max-line-length */ coreString += '<dcterms:modified xsi:type="dcterms:W3CDTF">' + builtInProperties.modifiedDate.toISOString() + '</dcterms:modified>'; } else { coreString += '<dcterms:modified xsi:type="dcterms:W3CDTF">' + createdDate.toISOString() + '</dcterms:modified>'; } } else { coreString += '<dcterms:created xsi:type="dcterms:W3CDTF">' + createdDate.toISOString() + '</dcterms:created>'; coreString += '<dcterms:modified xsi:type="dcterms:W3CDTF">' + createdDate.toISOString() + '</dcterms:modified>'; } /* tslint:disable-next-line:max-line-length */ coreString += '</cp:coreProperties>'; this.addToArchive(coreString, 'docProps/core.xml'); } private saveTopLevelRelation(): void { /* tslint:disable-next-line:max-line-length */ let topRelation: string = '<?xml version="1.0" encoding="utf-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml" /><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml" /><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml" /></Relationships>'; this.addToArchive(topRelation, '_rels/.rels'); } private saveWorkbookRelation(): void { /* tslint:disable-next-line:max-line-length */ let wbRelation: string = '<?xml version="1.0" encoding="utf-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'; let length: number = this.worksheets.length; let count: number = 0; for (let i: number = 0; i < length; i++ , count++) { /* tslint:disable-next-line:max-line-length */ wbRelation += '<Relationship Id="rId' + (i + 1).toString() + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet' + (i + 1).toString() + '.xml" />'; } /* tslint:disable-next-line:max-line-length */ wbRelation += '<Relationship Id="rId' + (++count).toString() + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml" />'; if (this.sharedStringCount > 0) { /* tslint:disable-next-line:max-line-length */ wbRelation += '<Relationship Id="rId' + (++count).toString() + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml" />'; } this.addToArchive((wbRelation + '</Relationships>'), 'xl/_rels/workbook.xml.rels'); } private saveContentType(): void { /* tslint:disable-next-line:max-line-length */ let contentTypeString: string = '<?xml version="1.0" encoding="utf-8" standalone="yes"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/xml" /><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" /><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml" /><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml" /><Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml" /><Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml" />'; let sheetsOverride: string = ''; let length: number = this.worksheets.length; for (let i: number = 0; i < length; i++) { /* tslint:disable-next-line:max-line-length */ sheetsOverride += '<Override PartName="/xl/worksheets/sheet' + (i + 1).toString() + '.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" />'; if(this.worksheets[i].images != undefined && this.worksheets[i].images.length > 0){ /* tslint:disable-next-line:max-line-length */ sheetsOverride += '<Override PartName="/xl/drawings/drawing' + (i + 1).toString() + '.xml" ContentType="application/vnd.openxmlformats-officedocument.drawing+xml" />'; } } if(this.imageCount > 0) sheetsOverride += '<Default Extension="png" ContentType="image/png" />'; if (this.sharedStringCount > 0) { /* tslint:disable-next-line:max-line-length */ contentTypeString += '<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml" />'; } this.addToArchive((contentTypeString + sheetsOverride + '</Types>'), '[Content_Types].xml'); } private addToArchive(xmlString: string | Blob, itemName: string): void { if (typeof (xmlString) === 'string') { let blob: Blob = new Blob([xmlString], { type: 'text/plain' }); let archiveItem: ZipArchiveItem = new ZipArchiveItem(blob, itemName); this.mArchive.addItem(archiveItem); } else { let archiveItem: ZipArchiveItem = new ZipArchiveItem(xmlString, itemName); this.mArchive.addItem(archiveItem); } } private processMergeCells(cell: Cell, rowIndex: number, mergeCells: MergeCells): MergeCells { if (cell.rowSpan !== 0 || cell.colSpan !== 0) { let mCell: MergeCell = new MergeCell(); mCell.x = cell.index; mCell.width = cell.colSpan; mCell.y = rowIndex; mCell.height = cell.rowSpan; let startCell: string = this.getCellName(mCell.y, mCell.x); let endCell: string = this.getCellName(rowIndex + mCell.height, cell.index + mCell.width); mCell.ref = startCell + ':' + endCell; let mergedCell: MergeCell = mergeCells.add(mCell); let start: { x: number, y: number } = { x: mCell.x, y: mCell.y }; let end: { x: number, y: number } = { x: (cell.index + mCell.width), y: (rowIndex + mCell.height) }; this.updatedMergedCellStyles(start, end, cell); } return mergeCells; } private updatedMergedCellStyles(sCell: { x: number, y: number }, eCell: { x: number, y: number }, cell: Cell): void { for (let x: number = sCell.x; x <= eCell.x; x++) { for (let y: number = sCell.y; y <= eCell.y; y++) { this.mergedCellsStyle.set(this.getCellName(y, x), { x: x, y: y, styleIndex: cell.styleIndex }); } } } /** * Returns the tick count corresponding to the given year, month, and day. * @param year number value of year * @param month number value of month * @param day number value of day */ private dateToTicks(year: number, month: number, day: number): number { let ticksPerDay: number = 10000 * 1000 * 60 * 60 * 24; let daysToMonth365: number[] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]; let daysToMonth366: number[] = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]; if (year >= 1 && year <= 9999 && month >= 1 && month <= 12) { let days: number[] = this.isLeapYear(year) ? daysToMonth366 : daysToMonth365; let y: number = year - 1; let n: number = y * 365 + ((y / 4) | 0) - ((y / 100) | 0) + ((y / 400) | 0) + days[month - 1] + day - 1; return n * ticksPerDay; } throw new Error('Not a valid date'); } /** * Return the tick count corresponding to the given hour, minute, second. * @param hour number value of hour * @param minute number value if minute * @param second number value of second */ private timeToTicks(hour: number, minute: number, second: number): number { if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60) { let totalSeconds: number = hour * 3600 + minute * 60 + second; return totalSeconds * 10000 * 1000; } throw new Error('Not valid time'); } /** * Checks if given year is a leap year. * @param year Year value. */ public isLeapYear(year: number): boolean { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } /** * Converts `DateTime` to the equivalent OLE Automation date. */ private toOADate(date: Date): number { let ticks: number = 0; /* tslint:disable-next-line:max-line-length */ ticks = this.dateToTicks(date.getFullYear(), (date.getMonth() + 1), date.getDate()) + this.timeToTicks(date.getHours(), date.getMinutes(), date.getSeconds()); if (ticks === 0) { return 0.0; } let ticksPerDay: number = 10000 * 1000 * 60 * 60 * 24; let daysTo1899: number = (((365 * 4 + 1) * 25 - 1) * 4 + 1) * 4 + ((365 * 4 + 1) * 25 - 1) * 3 - 367; let doubleDateOffset: number = daysTo1899 * ticksPerDay; let oaDateMinAsTicks: number = (((365 * 4 + 1) * 25 - 1) - 365) * ticksPerDay; if (ticks < oaDateMinAsTicks) { throw new Error('Arg_OleAutDateInvalid'); } let millisPerDay: number = 1000 * 60 * 60 * 24; return ((ticks - doubleDateOffset) / 10000) / millisPerDay; } } /** * BuiltInProperties Class * @private */ export class BuiltInProperties { public author: string; public comments: string; public category: string; public company: string; public manager: string; public subject: string; public title: string; public createdDate: Date; public modifiedDate: Date; public tags: string; public status: string; }
the_stack
type auto = i32; // @ts-ignore: decorator @builtin export declare function isInteger<T>(value?: T): bool; // @ts-ignore: decorator @builtin export declare function isFloat<T>(value?: T): bool; // @ts-ignore: decorator @builtin export declare function isBoolean<T>(value?: T): bool; // @ts-ignore: decorator @builtin export declare function isSigned<T>(value?: T): bool; // @ts-ignore: decorator @builtin export declare function isReference<T>(value?: T): bool; // @ts-ignore: decorator @builtin export declare function isString<T>(value?: T): bool; // @ts-ignore: decorator @builtin export declare function isArray<T>(value?: T): bool; // @ts-ignore: decorator @builtin export declare function isArrayLike<T>(value?: T): bool; // @ts-ignore: decorator @builtin export declare function isFunction<T>(value?: T): bool; // @ts-ignore: decorator @builtin export declare function isNullable<T>(value?: T): bool; // @ts-ignore: decorator @builtin export declare function isDefined(expression: auto): bool; // @ts-ignore: decorator @builtin export declare function isConstant(expression: auto): bool; // @ts-ignore: decorator @builtin export declare function isManaged<T>(value?: T): bool; // @ts-ignore: decorator @builtin export declare function isVoid<T>(): bool; // @ts-ignore @builtin export declare function lengthof<T>(func?: T): i32; // @ts-ignore: decorator @builtin export declare function clz<T>(value: T): T; // @ts-ignore: decorator @builtin export declare function ctz<T>(value: T): T; // @ts-ignore: decorator @builtin export declare function popcnt<T>(value: T): T; // @ts-ignore: decorator @builtin export declare function rotl<T>(value: T, shift: T): T; // @ts-ignore: decorator @builtin export declare function rotr<T>(value: T, shift: T): T; // @ts-ignore: decorator @builtin export declare function abs<T>(value: T): T; // @ts-ignore: decorator @builtin export declare function max<T>(left: T, right: T): T; // @ts-ignore: decorator @builtin export declare function min<T>(left: T, right: T): T; // @ts-ignore: decorator @builtin export declare function ceil<T>(value: T): T; // @ts-ignore: decorator @builtin export declare function floor<T>(value: T): T; // @ts-ignore: decorator @builtin export declare function copysign<T>(left: T, right: T): T; // @ts-ignore: decorator @builtin export declare function nearest<T>(value: T): T; // @ts-ignore: decorator @builtin export declare function reinterpret<T>(value: number): T; // @ts-ignore: decorator @builtin export declare function sqrt<T>(value: T): T; // @ts-ignore: decorator @builtin export declare function trunc<T>(value: T): T; // @ts-ignore: decorator @builtin export declare function add<T>(left: T, right: T): T; // @ts-ignore: decorator @builtin export declare function sub<T>(left: T, right: T): T; // @ts-ignore: decorator @builtin export declare function mul<T>(left: T, right: T): T; // @ts-ignore: decorator @builtin export declare function div<T>(left: T, right: T): T; // @ts-ignore: decorator @unsafe @builtin export declare function load<T>(ptr: usize, immOffset?: usize, immAlign?: usize): T; // @ts-ignore: decorator @unsafe @builtin export declare function store<T>(ptr: usize, value: auto, immOffset?: usize, immAlign?: usize): void; // @ts-ignore: decorator @builtin export declare function sizeof<T>(): usize; // | u32 / u64 // @ts-ignore: decorator @builtin export declare function alignof<T>(): usize; // | u32 / u64 // @ts-ignore: decorator @builtin export declare function offsetof<T>(fieldName?: string): usize; // | u32 / u64 // @ts-ignore: decorator @builtin export declare function idof<T>(): u32; // @ts-ignore @builtin export declare function nameof<T>(): string; // @ts-ignore: decorator @builtin export declare function select<T>(ifTrue: T, ifFalse: T, condition: bool): T; // @ts-ignore: decorator @unsafe @builtin export declare function unreachable(): auto; // @ts-ignore: decorator @builtin export declare function changetype<T>(value: auto): T; // @ts-ignore: decorator @builtin export declare function assert<T>(isTrueish: T, message?: string): T; // @ts-ignore: decorator @unsafe @builtin export declare function unchecked<T>(expr: T): T; // @ts-ignore: decorator @unsafe @builtin export declare function call_indirect<T>(index: u32, ...args: auto[]): T; // @ts-ignore: decorator @builtin export declare function instantiate<T>(...args: auto[]): T; export namespace atomic { // @ts-ignore: decorator @unsafe @builtin export declare function load<T>(ptr: usize, immOffset?: usize): T; // @ts-ignore: decorator @unsafe @builtin export declare function store<T>(ptr: usize, value: T, immOffset?: usize): void; // @ts-ignore: decorator @builtin export declare function add<T>(ptr: usize, value: T, immOffset?: usize): T; // @ts-ignore: decorator @builtin export declare function sub<T>(ptr: usize, value: T, immOffset?: usize): T; // @ts-ignore: decorator @builtin export declare function and<T>(ptr: usize, value: T, immOffset?: usize): T; // @ts-ignore: decorator @builtin export declare function or<T>(ptr: usize, value: T, immOffset?: usize): T; // @ts-ignore: decorator @builtin export declare function xor<T>(ptr: usize, value: T, immOffset?: usize): T; // @ts-ignore: decorator @unsafe @builtin export declare function xchg<T>(ptr: usize, value: T, immOffset?: usize): T; // @ts-ignore: decorator @unsafe @builtin export declare function cmpxchg<T>(ptr: usize, expected: T, replacement: T, immOffset?: usize): T; // @ts-ignore: decorator @builtin export declare function wait<T>(ptr: usize, expected: T, timeout: i64): AtomicWaitResult; // @ts-ignore: decorator @builtin export declare function notify(ptr: usize, count: i32): i32; // @ts-ignore: decorator @builtin export declare function fence(): void; } // @ts-ignore: decorator @lazy export const enum AtomicWaitResult { OK = 0, NOT_EQUAL = 1, TIMED_OUT = 2 } // @ts-ignore: decorator @builtin export declare function i8(value: auto): i8; export namespace i8 { // @ts-ignore: decorator @lazy export const MIN_VALUE: i8 = -128; // @ts-ignore: decorator @lazy export const MAX_VALUE: i8 = 127; } // @ts-ignore: decorator @builtin export declare function i16(value: auto): i16; export namespace i16 { // @ts-ignore: decorator @lazy export const MIN_VALUE: i16 = -32768; // @ts-ignore: decorator @lazy export const MAX_VALUE: i16 = 32767; } // @ts-ignore: decorator @builtin export declare function i32(value: auto): i32; export namespace i32 { // @ts-ignore: decorator @lazy export const MIN_VALUE: i32 = -2147483648; // @ts-ignore: decorator @lazy export const MAX_VALUE: i32 = 2147483647; // @ts-ignore: decorator @builtin export declare function clz(value: i32): i32; // @ts-ignore: decorator @builtin export declare function ctz(value: i32): i32; // @ts-ignore: decorator @builtin export declare function popcnt(value: i32): i32; // @ts-ignore: decorator @builtin export declare function add(left: i32, right:i32): i32; // @ts-ignore: decorator @builtin export declare function sub(left: i32, right:i32): i32; // @ts-ignore: decorator @builtin export declare function mul(left: i32, right:i32): i32; // @ts-ignore: decorator @builtin export declare function div_s(left: i32, right:i32): i32; // @ts-ignore: decorator @builtin export declare function div_u(left: i32, right:i32): i32; // @ts-ignore: decorator @builtin export declare function rotl(value: i32, shift: i32): i32; // @ts-ignore: decorator @builtin export declare function rotr(value: i32, shift: i32): i32; // @ts-ignore: decorator @builtin export declare function reinterpret_f32(value: f32): i32; // @ts-ignore: decorator @builtin export declare function load8_s(ptr: usize, immOffset?: usize, immAlign?: usize): i32; // @ts-ignore: decorator @builtin export declare function load8_u(ptr: usize, immOffset?: usize, immAlign?: usize): i32; // @ts-ignore: decorator @builtin export declare function load16_s(ptr: usize, immOffset?: usize, immAlign?: usize): i32; // @ts-ignore: decorator @builtin export declare function load16_u(ptr: usize, immOffset?: usize, immAlign?: usize): i32; // @ts-ignore: decorator @builtin export declare function load(ptr: usize, immOffset?: usize, immAlign?: usize): i32; // @ts-ignore: decorator @unsafe @builtin export declare function store8(ptr: usize, value: i32, immOffset?: usize, immAlign?: usize): void; // @ts-ignore: decorator @unsafe @builtin export declare function store16(ptr: usize, value: i32, immOffset?: usize, immAlign?: usize): void; // @ts-ignore: decorator @unsafe @builtin export declare function store(ptr: usize, value: i32, immOffset?: usize, immAlign?: usize): void; export namespace atomic { // @ts-ignore: decorator @builtin export declare function load8_u(ptr: usize, immOffset?: usize): i32; // @ts-ignore: decorator @builtin export declare function load16_u(ptr: usize, immOffset?: usize): i32; // @ts-ignore: decorator @builtin export declare function load(ptr: usize, immOffset?: usize): i32; // @ts-ignore: decorator @unsafe @builtin export declare function store8(ptr: usize, value: i32, immOffset?: usize): void; // @ts-ignore: decorator @unsafe @builtin export declare function store16(ptr: usize, value: i32, immOffset?: usize): void; // @ts-ignore: decorator @unsafe @builtin export declare function store(ptr: usize, value: i32, immOffset?: usize): void; // @ts-ignore: decorator @builtin export declare function wait(ptr: usize, expected: i32, timeout: i64): AtomicWaitResult; export namespace rmw8 { // @ts-ignore: decorator @builtin export declare function add_u(ptr: usize, value: i32, immOffset?: usize): i32; // @ts-ignore: decorator @builtin export declare function sub_u(ptr: usize, value: i32, immOffset?: usize): i32; // @ts-ignore: decorator @builtin export declare function and_u(ptr: usize, value: i32, immOffset?: usize): i32; // @ts-ignore: decorator @builtin export declare function or_u(ptr: usize, value: i32, immOffset?: usize): i32; // @ts-ignore: decorator @builtin export declare function xor_u(ptr: usize, value: i32, immOffset?: usize): i32; // @ts-ignore: decorator @unsafe @builtin export declare function xchg_u(ptr: usize, value: i32, immOffset?: usize): i32; // @ts-ignore: decorator @unsafe @builtin export declare function cmpxchg_u(ptr: usize, expected: i32, replacement: i32, immOffset?: usize): i32; } export namespace rmw16 { // @ts-ignore: decorator @builtin export declare function add_u(ptr: usize, value: i32, immOffset?: usize): i32; // @ts-ignore: decorator @builtin export declare function sub_u(ptr: usize, value: i32, immOffset?: usize): i32; // @ts-ignore: decorator @builtin export declare function and_u(ptr: usize, value: i32, immOffset?: usize): i32; // @ts-ignore: decorator @builtin export declare function or_u(ptr: usize, value: i32, immOffset?: usize): i32; // @ts-ignore: decorator @builtin export declare function xor_u(ptr: usize, value: i32, immOffset?: usize): i32; // @ts-ignore: decorator @unsafe @builtin export declare function xchg_u(ptr: usize, value: i32, immOffset?: usize): i32; // @ts-ignore: decorator @unsafe @builtin export declare function cmpxchg_u(ptr: usize, expected: i32, replacement: i32, immOffset?: usize): i32; } export namespace rmw { // @ts-ignore: decorator @builtin export declare function add(ptr: usize, value: i32, immOffset?: usize): i32; // @ts-ignore: decorator @builtin export declare function sub(ptr: usize, value: i32, immOffset?: usize): i32; // @ts-ignore: decorator @builtin export declare function and(ptr: usize, value: i32, immOffset?: usize): i32; // @ts-ignore: decorator @builtin export declare function or(ptr: usize, value: i32, immOffset?: usize): i32; // @ts-ignore: decorator @builtin export declare function xor(ptr: usize, value: i32, immOffset?: usize): i32; // @ts-ignore: decorator @unsafe @builtin export declare function xchg(ptr: usize, value: i32, immOffset?: usize): i32; // @ts-ignore: decorator @unsafe @builtin export declare function cmpxchg(ptr: usize, expected: i32, replacement: i32, immOffset?: usize): i32; } } } // @ts-ignore: decorator @builtin export declare function i64(value: auto): i64; export namespace i64 { // @ts-ignore: decorator @lazy export const MIN_VALUE: i64 = -9223372036854775808; // @ts-ignore: decorator @lazy export const MAX_VALUE: i64 = 9223372036854775807; // @ts-ignore: decorator @builtin export declare function clz(value: i64): i64; // @ts-ignore: decorator @builtin export declare function ctz(value: i64): i64; // @ts-ignore: decorator @builtin export declare function add(left: i64, right:i64): i64; // @ts-ignore: decorator @builtin export declare function sub(left: i64, right:i64): i64; // @ts-ignore: decorator @builtin export declare function mul(left: i64, right:i64): i64; // @ts-ignore: decorator @builtin export declare function div_s(left: i64, right:i64): i64; // @ts-ignore: decorator @builtin export declare function div_u(left: i64, right:i64): i64; // @ts-ignore: decorator @builtin export declare function load8_s(ptr: usize, immOffset?: usize, immAlign?: usize): i64; // @ts-ignore: decorator @builtin export declare function load8_u(ptr: usize, immOffset?: usize, immAlign?: usize): i64; // @ts-ignore: decorator @builtin export declare function load16_s(ptr: usize, immOffset?: usize, immAlign?: usize): i64; // @ts-ignore: decorator @builtin export declare function load16_u(ptr: usize, immOffset?: usize, immAlign?: usize): i64; // @ts-ignore: decorator @builtin export declare function load32_s(ptr: usize, immOffset?: usize, immAlign?: usize): i64; // @ts-ignore: decorator @builtin export declare function load32_u(ptr: usize, immOffset?: usize, immAlign?: usize): i64; // @ts-ignore: decorator @builtin export declare function load(ptr: usize, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function popcnt(value: i64): i64; // @ts-ignore: decorator @builtin export declare function rotl(value: i64, shift: i64): i64; // @ts-ignore: decorator @builtin export declare function rotr(value: i64, shift: i64): i64; // @ts-ignore: decorator @builtin export declare function reinterpret_f64(value: f64): i64; // @ts-ignore: decorator @unsafe @builtin export declare function store8(ptr: usize, value: i64, immOffset?: usize, immAlign?: usize): void; // @ts-ignore: decorator @unsafe @builtin export declare function store16(ptr: usize, value: i64, immOffset?: usize, immAlign?: usize): void; // @ts-ignore: decorator @unsafe @builtin export declare function store32(ptr: usize, value: i64, immOffset?: usize, immAlign?: usize): void; // @ts-ignore: decorator @unsafe @builtin export declare function store(ptr: usize, value: i64, immOffset?: usize, immAlign?: usize): void; export namespace atomic { // @ts-ignore: decorator @builtin export declare function load8_u(ptr: usize, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function load16_u(ptr: usize, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function load32_u(ptr: usize, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function load(ptr: usize, immOffset?: usize): i64; // @ts-ignore: decorator @unsafe @builtin export declare function store8(ptr: usize, value: i64, immOffset?: usize): void; // @ts-ignore: decorator @unsafe @builtin export declare function store16(ptr: usize, value: i64, immOffset?: usize): void; // @ts-ignore: decorator @unsafe @builtin export declare function store32(ptr: usize, value: i64, immOffset?: usize): void; // @ts-ignore: decorator @unsafe @builtin export declare function store(ptr: usize, value: i64, immOffset?: usize): void; // @ts-ignore: decorator @builtin export declare function wait(ptr: usize, expected: i64, timeout: i64): AtomicWaitResult; export namespace rmw8 { // @ts-ignore: decorator @builtin export declare function add_u(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function sub_u(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function and_u(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function or_u(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function xor_u(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @unsafe @builtin export declare function xchg_u(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @unsafe @builtin export declare function cmpxchg_u(ptr: usize, expected: i64, replacement: i64, immOffset?: usize): i64; } export namespace rmw16 { // @ts-ignore: decorator @builtin export declare function add_u(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function sub_u(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function and_u(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function or_u(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function xor_u(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @unsafe @builtin export declare function xchg_u(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @unsafe @builtin export declare function cmpxchg_u(ptr: usize, expected: i64, replacement: i64, immOffset?: usize): i64; } export namespace rmw32 { // @ts-ignore: decorator @builtin export declare function add_u(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function sub_u(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function and_u(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function or_u(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function xor_u(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @unsafe @builtin export declare function xchg_u(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @unsafe @builtin export declare function cmpxchg_u(ptr: usize, expected: i64, replacement: i64, immOffset?: usize): i64; } export namespace rmw { // @ts-ignore: decorator @builtin export declare function add(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function sub(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function and(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function or(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @builtin export declare function xor(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @unsafe @builtin export declare function xchg(ptr: usize, value: i64, immOffset?: usize): i64; // @ts-ignore: decorator @unsafe @builtin export declare function cmpxchg(ptr: usize, expected: i64, replacement: i64, immOffset?: usize): i64; } } } // @ts-ignore: decorator @builtin export declare function isize(value: auto): isize; export namespace isize { // @ts-ignore: decorator @lazy export const MIN_VALUE: isize = sizeof<i32>() == sizeof<isize>() ? -2147483648 : <isize>-9223372036854775808; // @ts-ignore: decorator @lazy export const MAX_VALUE: isize = sizeof<i32>() == sizeof<isize>() ? 2147483647 : <isize>9223372036854775807; } // @ts-ignore: decorator @builtin export declare function u8(value: auto): u8; export namespace u8 { // @ts-ignore: decorator @lazy export const MIN_VALUE: u8 = 0; // @ts-ignore: decorator @lazy export const MAX_VALUE: u8 = 255; } // @ts-ignore: decorator @builtin export declare function u16(value: auto): u16; export namespace u16 { // @ts-ignore: decorator @lazy export const MIN_VALUE: u16 = 0; // @ts-ignore: decorator @lazy export const MAX_VALUE: u16 = 65535; } // @ts-ignore: decorator @builtin export declare function u32(value: auto): u32; export namespace u32 { // @ts-ignore: decorator @lazy export const MIN_VALUE: u32 = 0; // @ts-ignore: decorator @lazy export const MAX_VALUE: u32 = 4294967295; } // @ts-ignore: decorator @builtin export declare function u64(value: auto): u64; export namespace u64 { // @ts-ignore: decorator @lazy export const MIN_VALUE: u64 = 0; // @ts-ignore: decorator @lazy export const MAX_VALUE: u64 = 18446744073709551615; } // @ts-ignore: decorator @builtin export declare function usize(value: auto): usize; export namespace usize { // @ts-ignore: decorator @lazy export const MIN_VALUE: usize = 0; // @ts-ignore: decorator @lazy export const MAX_VALUE: usize = sizeof<u32>() == sizeof<usize>() ? 4294967295 : <usize>18446744073709551615; } // @ts-ignore: decorator @builtin export declare function bool(value: auto): bool; export namespace bool { // @ts-ignore: decorator @lazy export const MIN_VALUE: bool = false; // @ts-ignore: decorator @lazy export const MAX_VALUE: bool = true; } // @ts-ignore: decorator @builtin export declare function f32(value: auto): f32; export namespace f32 { // @ts-ignore: decorator @lazy export const EPSILON = reinterpret<f32>(0x34000000); // 0x1p-23f // @ts-ignore: decorator @lazy export const MIN_VALUE = reinterpret<f32>(0x00000001); // 0x0.000001p+0f // @ts-ignore: decorator @lazy export const MAX_VALUE = reinterpret<f32>(0x7F7FFFFF); // 0x1.fffffep+127f // @ts-ignore: decorator @lazy export const MIN_NORMAL_VALUE = reinterpret<f32>(0x00800000); // 0x1p-126f // @ts-ignore: decorator @lazy export const MIN_SAFE_INTEGER: f32 = -16777215; // @ts-ignore: decorator @lazy export const MAX_SAFE_INTEGER: f32 = 16777215; // @ts-ignore: decorator @lazy export const POSITIVE_INFINITY: f32 = Infinity; // @ts-ignore: decorator @lazy export const NEGATIVE_INFINITY: f32 = -Infinity; // @ts-ignore: decorator @lazy export const NaN: f32 = 0.0 / 0.0; // @ts-ignore: decorator @builtin export declare function abs(value: f32): f32; // @ts-ignore: decorator @builtin export declare function ceil(value: f32): f32; // @ts-ignore: decorator @builtin export declare function copysign(x: f32, y: f32): f32; // @ts-ignore: decorator @builtin export declare function floor(value: f32): f32; // @ts-ignore: decorator @builtin export declare function load(ptr: usize, immOffset?: usize, immAlign?: usize): f32; // @ts-ignore: decorator @builtin export declare function max(left: f32, right: f32): f32; // @ts-ignore: decorator @builtin export declare function min(left: f32, right: f32): f32; // @ts-ignore: decorator @builtin export declare function nearest(value: f32): f32; // @ts-ignore: decorator @builtin export declare function reinterpret_i32(value: i32): f32; // @ts-ignore: decorator @builtin export declare function sqrt(value: f32): f32; // @ts-ignore: decorator @unsafe @builtin export declare function store(ptr: usize, value: f32, immOffset?: usize, immAlign?: usize): void; // @ts-ignore: decorator @builtin export declare function trunc(value: f32): f32; // @ts-ignore: decorator @builtin export declare function add(left: f32, right: f32): f32; // @ts-ignore: decorator @builtin export declare function sub(left: f32, right: f32): f32; // @ts-ignore: decorator @builtin export declare function mul(left: f32, right: f32): f32; // @ts-ignore: decorator @builtin export declare function div(left: f32, right: f32): f32; } // @ts-ignore: decorator @builtin export declare function f64(value: auto): f64; export namespace f64 { // @ts-ignore: decorator @lazy export const EPSILON = reinterpret<f64>(0x3CB0000000000000); // 0x1p-52 // @ts-ignore: decorator @lazy export const MIN_VALUE = reinterpret<f64>(0x0000000000000001); // 0x0.0000000000001p+0 // @ts-ignore: decorator @lazy export const MAX_VALUE = reinterpret<f64>(0x7FEFFFFFFFFFFFFF); // 0x1.fffffffffffffp+1023 // @ts-ignore: decorator @lazy export const MIN_NORMAL_VALUE = reinterpret<f64>(0x0010000000000000); // 0x1p-1022 // @ts-ignore: decorator @lazy export const MIN_SAFE_INTEGER: f64 = -9007199254740991; // @ts-ignore: decorator @lazy export const MAX_SAFE_INTEGER: f64 = 9007199254740991; // @ts-ignore: decorator @lazy export const POSITIVE_INFINITY: f64 = Infinity; // @ts-ignore: decorator @lazy export const NEGATIVE_INFINITY: f64 = -Infinity; // @ts-ignore: decorator @lazy export const NaN: f64 = 0.0 / 0.0; // @ts-ignore: decorator @builtin export declare function abs(value: f64): f64; // @ts-ignore: decorator @builtin export declare function ceil(value: f64): f64; // @ts-ignore: decorator @builtin export declare function copysign(x: f64, y: f64): f64; // @ts-ignore: decorator @builtin export declare function floor(value: f64): f64; // @ts-ignore: decorator @builtin export declare function load(ptr: usize, immOffset?: usize, immAlign?: usize): f64; // @ts-ignore: decorator @builtin export declare function max(left: f64, right: f64): f64; // @ts-ignore: decorator @builtin export declare function min(left: f64, right: f64): f64; // @ts-ignore: decorator @builtin export declare function nearest(value: f64): f64; // @ts-ignore: decorator @builtin export declare function reinterpret_i64(value: i64): f64; // @ts-ignore: decorator @builtin export declare function sqrt(value: f64): f64; // @ts-ignore: decorator @unsafe @builtin export declare function store(ptr: usize, value: f64, immOffset?: usize, immAlign?: usize): void; // @ts-ignore: decorator @builtin export declare function trunc(value: f64): f64; // @ts-ignore: decorator @builtin export declare function add(left: f64, right: f64): f64; // @ts-ignore: decorator @builtin export declare function sub(left: f64, right: f64): f64; // @ts-ignore: decorator @builtin export declare function mul(left: f64, right: f64): f64; // @ts-ignore: decorator @builtin export declare function div(left: f64, right: f64): f64; } // @ts-ignore: decorator @builtin export declare function v128( a: i8, b: i8, c: i8, d: i8, e: i8, f: i8, g: i8, h: i8, i: i8, j: i8, k: i8, l: i8, m: i8, n: i8, o: i8, p: i8 ): v128; export namespace v128 { // @ts-ignore: decorator @builtin export declare function splat<T>(x: T): v128; // @ts-ignore: decorator @builtin export declare function extract_lane<T>(x: v128, idx: u8): T; // @ts-ignore: decorator @builtin export declare function replace_lane<T>(x: v128, idx: u8, value: T): v128; // @ts-ignore: decorator @builtin export declare function shuffle<T>(a: v128, b: v128, ...lanes: u8[]): v128; // @ts-ignore: decorator @builtin export declare function swizzle(a: v128, s: v128): v128; // @ts-ignore: decorator @unsafe @builtin export declare function load(ptr: usize, immOffset?: usize, immAlign?: usize): v128; // @ts-ignore: decorator @unsafe @builtin export declare function load_ext<TFrom>(ptr: usize, immOffset?: usize, immAlign?: usize): v128; // @ts-ignore: decorator @unsafe @builtin export declare function load_zero<TFrom>(ptr: usize, immOffset?: usize, immAlign?: usize): v128; // @ts-ignore: decorator @unsafe @builtin export declare function load_lane<TFrom>(ptr: usize, vec: v128, idx: u8, immOffset?: usize, immAlign?: usize): v128; // @ts-ignore: decorator @unsafe @builtin export declare function store_lane<TFrom>(ptr: usize, vec: v128, idx: u8, immOffset?: usize, immAlign?: usize): v128; // @ts-ignore: decorator @builtin export declare function load8x8_s(ptr: usize, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @builtin export declare function load8x8_u(ptr: usize, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @builtin export declare function load16x4_s(ptr: usize, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @builtin export declare function load16x4_u(ptr: usize, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @builtin export declare function load32x2_s(ptr: usize, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @builtin export declare function load32x2_u(ptr: usize, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @unsafe @builtin export declare function load_splat<T>(ptr: usize, immOffset?: usize, immAlign?: usize): v128; // @ts-ignore: decorator @unsafe @builtin export declare function load8_splat(ptr: usize, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @unsafe @builtin export declare function load16_splat(ptr: usize, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @unsafe @builtin export declare function load32_splat(ptr: usize, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @unsafe @builtin export declare function load64_splat(ptr: usize, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @unsafe @builtin export declare function load32_zero(ptr: usize, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @unsafe @builtin export declare function load64_zero(ptr: usize, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @unsafe @builtin export declare function load8_lane(ptr: usize, vec: v128, idx: u8, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @unsafe @builtin export declare function load16_lane(ptr: usize, vec: v128, idx: u8, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @unsafe @builtin export declare function load32_lane(ptr: usize, vec: v128, idx: u8, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @unsafe @builtin export declare function load64_lane(ptr: usize, vec: v128, idx: u8, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @unsafe @builtin export declare function store8_lane(ptr: usize, vec: v128, idx: u8, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @unsafe @builtin export declare function store16_lane(ptr: usize, vec: v128, idx: u8, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @unsafe @builtin export declare function store32_lane(ptr: usize, vec: v128, idx: u8, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @unsafe @builtin export declare function store64_lane(ptr: usize, vec: v128, idx: u8, immOffset?: u32, immAlign?: u32): v128; // @ts-ignore: decorator @unsafe @builtin export declare function store(ptr: usize, value: v128, immOffset?: usize, immAlign?: usize): void; // @ts-ignore: decorator @builtin export declare function add<T>(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function sub<T>(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function mul<T>(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function div<T>(a: v128, b: v128): v128; // f32, f64 only // @ts-ignore: decorator @builtin export declare function neg<T>(a: v128): v128; // @ts-ignore: decorator @builtin export declare function add_sat<T>(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function sub_sat<T>(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function shl<T>(a: v128, b: i32): v128; // @ts-ignore: decorator @builtin export declare function shr<T>(a: v128, b: i32): v128; // @ts-ignore: decorator @builtin export declare function and(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function or(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function xor(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function andnot(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function not(a: v128): v128; // @ts-ignore: decorator @builtin export declare function bitselect(v1: v128, v2: v128, c: v128): v128; // @ts-ignore: decorator @builtin export declare function any_true(a: v128): bool; // @ts-ignore: decorator @builtin export declare function all_true<T>(a: v128): bool; // @ts-ignore: decorator @builtin export declare function bitmask<T>(a: v128): i32; // @ts-ignore: decorator @builtin export declare function popcnt<T>(a: v128): v128; // @ts-ignore: decorator @builtin export declare function min<T>(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function max<T>(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function pmin<T>(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function pmax<T>(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function dot<T>(a: v128, b: v128): v128; // i16 only // @ts-ignore: decorator @builtin export declare function avgr<T>(a: v128, b: v128): v128; // u8, u16 only // @ts-ignore: decorator @builtin export declare function abs<T>(a: v128): v128; // f32, f64 only // @ts-ignore: decorator @builtin export declare function sqrt<T>(a: v128): v128; // f32, f64 only // @ts-ignore: decorator @builtin export declare function ceil<T>(a: v128): v128; // f32, f64 only // @ts-ignore: decorator @builtin export declare function floor<T>(a: v128): v128; // f32, f64 only // @ts-ignore: decorator @builtin export declare function trunc<T>(a: v128): v128; // f32, f64 only // @ts-ignore: decorator @builtin export declare function nearest<T>(a: v128): v128; // f32, f64 only // @ts-ignore: decorator @builtin export declare function eq<T>(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function ne<T>(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function lt<T>(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function le<T>(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function gt<T>(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function ge<T>(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function convert<T>(a: v128): v128; // @ts-ignore: decorator @builtin export declare function convert_low<T>(a: v128): v128; // @ts-ignore: decorator @builtin export declare function trunc_sat<T>(a: v128): v128; // @ts-ignore: decorator @builtin export declare function trunc_sat_zero<T>(a: v128): v128; // @ts-ignore: decorator @builtin export declare function narrow<T>(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function extend_low<T>(a: v128): v128; // @ts-ignore: decorator @builtin export declare function extend_high<T>(a: v128): v128; // @ts-ignore: decorator @builtin export declare function extadd_pairwise<T>(a: v128): v128; // @ts-ignore: decorator @builtin export declare function demote_zero<T = f64>(a: v128): v128; // @ts-ignore: decorator @builtin export declare function promote_low<T = f32>(a: v128): v128; // @ts-ignore: decorator @builtin export declare function q15mulr_sat<T>(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function extmul_low<T>(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function extmul_high<T>(a: v128, b: v128): v128; } // @ts-ignore: decorator @builtin export declare function i8x16( a: i8, b: i8, c: i8, d: i8, e: i8, f: i8, g: i8, h: i8, i: i8, j: i8, k: i8, l: i8, m: i8, n: i8, o: i8, p: i8 ): v128; export namespace i8x16 { // @ts-ignore: decorator @builtin export declare function splat(x: i8): v128; // @ts-ignore: decorator @builtin export declare function extract_lane_s(x: v128, idx: u8): i8; // @ts-ignore: decorator @builtin export declare function extract_lane_u(x: v128, idx: u8): u8; // @ts-ignore: decorator @builtin export declare function replace_lane(x: v128, idx: u8, value: i8): v128; // @ts-ignore: decorator @builtin export declare function add(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function sub(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function min_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function min_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function max_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function max_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function avgr_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function abs(a: v128): v128; // @ts-ignore: decorator @builtin export declare function neg(a: v128): v128; // @ts-ignore: decorator @builtin export declare function add_sat_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function add_sat_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function sub_sat_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function sub_sat_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function shl(a: v128, b: i32): v128; // @ts-ignore: decorator @builtin export declare function shr_s(a: v128, b: i32): v128; // @ts-ignore: decorator @builtin export declare function shr_u(a: v128, b: i32): v128; // @ts-ignore: decorator @builtin export declare function all_true(a: v128): bool; // @ts-ignore: decorator @builtin export declare function bitmask(a: v128): i32; // @ts-ignore: decorator @builtin export declare function popcnt(a: v128): v128; // @ts-ignore: decorator @builtin export declare function eq(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function ne(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function lt_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function lt_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function le_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function le_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function gt_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function gt_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function ge_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function ge_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function narrow_i16x8_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function narrow_i16x8_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function shuffle( a: v128, b: v128, l0: u8, l1: u8, l2: u8, l3: u8, l4: u8, l5: u8, l6: u8, l7: u8, l8: u8, l9: u8, l10: u8, l11: u8, l12: u8, l13: u8, l14: u8, l15: u8 ): v128; // @ts-ignore: decorator @builtin export declare function swizzle(a: v128, s: v128): v128; } // @ts-ignore: decorator @builtin export declare function i16x8(a: i16, b: i16, c: i16, d: i16, e: i16, f: i16, g: i16, h: i16): v128; export namespace i16x8 { // @ts-ignore: decorator @builtin export declare function splat(x: i16): v128; // @ts-ignore: decorator @builtin export declare function extract_lane_s(x: v128, idx: u8): i16; // @ts-ignore: decorator @builtin export declare function extract_lane_u(x: v128, idx: u8): u16; // @ts-ignore: decorator @builtin export declare function replace_lane(x: v128, idx: u8, value: i16): v128; // @ts-ignore: decorator @builtin export declare function add(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function sub(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function mul(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function min_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function min_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function max_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function max_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function avgr_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function abs(a: v128): v128; // @ts-ignore: decorator @builtin export declare function neg(a: v128): v128; // @ts-ignore: decorator @builtin export declare function add_sat_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function add_sat_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function sub_sat_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function sub_sat_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function shl(a: v128, b: i32): v128; // @ts-ignore: decorator @builtin export declare function shr_s(a: v128, b: i32): v128; // @ts-ignore: decorator @builtin export declare function shr_u(a: v128, b: i32): v128; // @ts-ignore: decorator @builtin export declare function all_true(a: v128): bool; // @ts-ignore: decorator @builtin export declare function bitmask(a: v128): i32; // @ts-ignore: decorator @builtin export declare function eq(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function ne(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function lt_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function lt_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function le_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function le_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function gt_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function gt_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function ge_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function ge_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function narrow_i32x4_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function narrow_i32x4_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function extend_low_i8x16_s(a: v128): v128; // @ts-ignore: decorator @builtin export declare function extend_low_i8x16_u(a: v128): v128; // @ts-ignore: decorator @builtin export declare function extend_high_i8x16_s(a: v128): v128; // @ts-ignore: decorator @builtin export declare function extend_high_i8x16_u(a: v128): v128; // @ts-ignore: decorator @builtin export declare function extadd_pairwise_i8x16_s(a: v128): v128; // @ts-ignore: decorator @builtin export declare function extadd_pairwise_i8x16_u(a: v128): v128; // @ts-ignore: decorator @builtin export declare function q15mulr_sat_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function extmul_low_i8x16_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function extmul_low_i8x16_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function extmul_high_i8x16_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function extmul_high_i8x16_u(a: v128, b: v128): v128; } // @ts-ignore: decorator @builtin export declare function i32x4(a: i32, b: i32, c: i32, d: i32): v128; export namespace i32x4 { // @ts-ignore: decorator @builtin export declare function splat(x: i32): v128; // @ts-ignore: decorator @builtin export declare function extract_lane(x: v128, idx: u8): i32; // @ts-ignore: decorator @builtin export declare function replace_lane(x: v128, idx: u8, value: i32): v128; // @ts-ignore: decorator @builtin export declare function add(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function sub(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function mul(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function min_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function min_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function max_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function max_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function dot_i16x8_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function abs(a: v128): v128; // @ts-ignore: decorator @builtin export declare function neg(a: v128): v128; // @ts-ignore: decorator @builtin export declare function shl(a: v128, b: i32): v128; // @ts-ignore: decorator @builtin export declare function shr_s(a: v128, b: i32): v128; // @ts-ignore: decorator @builtin export declare function shr_u(a: v128, b: i32): v128; // @ts-ignore: decorator @builtin export declare function all_true(a: v128): bool; // @ts-ignore: decorator @builtin export declare function bitmask(a: v128): i32; // @ts-ignore: decorator @builtin export declare function eq(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function ne(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function lt_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function lt_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function le_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function le_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function gt_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function gt_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function ge_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function ge_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function trunc_sat_f32x4_s(a: v128): v128; // @ts-ignore: decorator @builtin export declare function trunc_sat_f32x4_u(a: v128): v128; // @ts-ignore: decorator @builtin export declare function trunc_sat_f64x2_s_zero(a: v128): v128; // @ts-ignore: decorator @builtin export declare function trunc_sat_f64x2_u_zero(a: v128): v128; // @ts-ignore: decorator @builtin export declare function extend_low_i16x8_s(a: v128): v128; // @ts-ignore: decorator @builtin export declare function extend_low_i16x8_u(a: v128): v128; // @ts-ignore: decorator @builtin export declare function extend_high_i16x8_s(a: v128): v128; // @ts-ignore: decorator @builtin export declare function extend_high_i16x8_u(a: v128): v128; // @ts-ignore: decorator @builtin export declare function extadd_pairwise_i16x8_s(a: v128): v128; // @ts-ignore: decorator @builtin export declare function extadd_pairwise_i16x8_u(a: v128): v128; // @ts-ignore: decorator @builtin export declare function extmul_low_i16x8_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function extmul_low_i16x8_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function extmul_high_i16x8_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function extmul_high_i16x8_u(a: v128, b: v128): v128; } // @ts-ignore: decorator @builtin export declare function i64x2(a: i64, b: i64): v128; export namespace i64x2 { // @ts-ignore: decorator @builtin export declare function splat(x: i64): v128; // @ts-ignore: decorator @builtin export declare function extract_lane(x: v128, idx: u8): i64; // @ts-ignore: decorator @builtin export declare function replace_lane(x: v128, idx: u8, value: i64): v128; // @ts-ignore: decorator @builtin export declare function add(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function sub(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function mul(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function abs(a: v128): v128; // @ts-ignore: decorator @builtin export declare function neg(a: v128): v128; // @ts-ignore: decorator @builtin export declare function shl(a: v128, b: i32): v128; // @ts-ignore: decorator @builtin export declare function shr_s(a: v128, b: i32): v128; // @ts-ignore: decorator @builtin export declare function shr_u(a: v128, b: i32): v128; // @ts-ignore: decorator @builtin export declare function all_true(a: v128): bool; // @ts-ignore: decorator @builtin export declare function bitmask(a: v128): i32; // @ts-ignore: decorator @builtin export declare function eq(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function ne(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function lt_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function le_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function gt_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function ge_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function extend_low_i32x4_s(a: v128): v128; // @ts-ignore: decorator @builtin export declare function extend_low_i32x4_u(a: v128): v128; // @ts-ignore: decorator @builtin export declare function extend_high_i32x4_s(a: v128): v128; // @ts-ignore: decorator @builtin export declare function extend_high_i32x4_u(a: v128): v128; // @ts-ignore: decorator @builtin export declare function extmul_low_i32x4_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function extmul_low_i32x4_u(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function extmul_high_i32x4_s(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function extmul_high_i32x4_u(a: v128, b: v128): v128; } // @ts-ignore: decorator @builtin export declare function f32x4(a: f32, b: f32, c: f32, d: f32): v128; export namespace f32x4 { // @ts-ignore: decorator @builtin export declare function splat(x: f32): v128; // @ts-ignore: decorator @builtin export declare function extract_lane(x: v128, idx: u8): f32; // @ts-ignore: decorator @builtin export declare function replace_lane(x: v128, idx: u8, value: f32): v128; // @ts-ignore: decorator @builtin export declare function add(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function sub(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function mul(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function div(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function neg(a: v128): v128; // @ts-ignore: decorator @builtin export declare function min(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function max(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function pmin(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function pmax(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function abs(a: v128): v128; // @ts-ignore: decorator @builtin export declare function sqrt(a: v128): v128; // @ts-ignore: decorator @builtin export declare function ceil(a: v128): v128; // @ts-ignore: decorator @builtin export declare function floor(a: v128): v128; // @ts-ignore: decorator @builtin export declare function trunc(a: v128): v128; // @ts-ignore: decorator @builtin export declare function nearest(a: v128): v128; // @ts-ignore: decorator @builtin export declare function eq(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function ne(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function lt(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function le(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function gt(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function ge(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function convert_i32x4_s(a: v128): v128; // @ts-ignore: decorator @builtin export declare function convert_i32x4_u(a: v128): v128; // @ts-ignore: decorator @builtin export declare function demote_f64x2_zero(a: v128): v128; } // @ts-ignore: decorator @builtin export declare function f64x2(a: f64, b: f64): v128; export namespace f64x2 { // @ts-ignore: decorator @builtin export declare function splat(x: f64): v128; // @ts-ignore: decorator @builtin export declare function extract_lane(x: v128, idx: u8): f64; // @ts-ignore: decorator @builtin export declare function replace_lane(x: v128, idx: u8, value: f64): v128; // @ts-ignore: decorator @builtin export declare function add(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function sub(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function mul(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function div(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function neg(a: v128): v128; // @ts-ignore: decorator @builtin export declare function min(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function max(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function pmin(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function pmax(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function abs(a: v128): v128; // @ts-ignore: decorator @builtin export declare function sqrt(a: v128): v128; // @ts-ignore: decorator @builtin export declare function ceil(a: v128): v128; // @ts-ignore: decorator @builtin export declare function floor(a: v128): v128; // @ts-ignore: decorator @builtin export declare function trunc(a: v128): v128; // @ts-ignore: decorator @builtin export declare function nearest(a: v128): v128; // @ts-ignore: decorator @builtin export declare function eq(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function ne(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function lt(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function le(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function gt(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function ge(a: v128, b: v128): v128; // @ts-ignore: decorator @builtin export declare function convert_low_i32x4_s(a: v128): v128; // @ts-ignore: decorator @builtin export declare function convert_low_i32x4_u(a: v128): v128; // @ts-ignore: decorator @builtin export declare function promote_low_f32x4(a: v128): v128; } @final export abstract class i31 { // FIXME: usage of 'new' requires a class :( // @ts-ignore: decorator @builtin static new(value: i32): i31ref { return changetype<i31ref>(unreachable()); } // @ts-ignore: decorator @builtin static get(i31expr: i31ref): i32 { return unreachable(); } } /* eslint-disable @typescript-eslint/no-unused-vars */ // @ts-ignore: decorator @external("env", "abort") declare function abort( message?: string | null, fileName?: string | null, lineNumber?: u32, columnNumber?: u32 ): void; // @ts-ignore: decorator @external("env", "trace") declare function trace( message: string, n?: i32, a0?: f64, a1?: f64, a2?: f64, a3?: f64, a4?: f64 ): void; // @ts-ignore: decorator @external("env", "seed") declare function seed(): f64; /* eslint-enable @typescript-eslint/no-unused-vars */
the_stack
namespace ts.OutliningElementsCollector { export function collectElements(sourceFile: SourceFile, cancellationToken: CancellationToken): OutliningSpan[] { const res: OutliningSpan[] = []; addNodeOutliningSpans(sourceFile, cancellationToken, res); addRegionOutliningSpans(sourceFile, res); return res.sort((span1, span2) => span1.textSpan.start - span2.textSpan.start); } function addNodeOutliningSpans(sourceFile: SourceFile, cancellationToken: CancellationToken, out: Push<OutliningSpan>): void { let depthRemaining = 40; let current = 0; const statements = sourceFile.statements; const n = statements.length; while (current < n) { while (current < n && !isAnyImportSyntax(statements[current])) { visitNonImportNode(statements[current]); current++; } if (current === n) break; const firstImport = current; while (current < n && isAnyImportSyntax(statements[current])) { addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out); current++; } const lastImport = current - 1; if (lastImport !== firstImport) { out.push(createOutliningSpanFromBounds(findChildOfKind(statements[firstImport], SyntaxKind.ImportKeyword, sourceFile)!.getStart(sourceFile), statements[lastImport].getEnd(), OutliningSpanKind.Imports)); } } function visitNonImportNode(n: Node) { if (depthRemaining === 0) return; cancellationToken.throwIfCancellationRequested(); if (isDeclaration(n)) { addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out); } const span = getOutliningSpanForNode(n, sourceFile); if (span) out.push(span); depthRemaining--; if (isIfStatement(n) && n.elseStatement && isIfStatement(n.elseStatement)) { // Consider an 'else if' to be on the same depth as the 'if'. visitNonImportNode(n.expression); visitNonImportNode(n.thenStatement); depthRemaining++; visitNonImportNode(n.elseStatement); depthRemaining--; } else { n.forEachChild(visitNonImportNode); } depthRemaining++; } } function addRegionOutliningSpans(sourceFile: SourceFile, out: Push<OutliningSpan>): void { const regions: OutliningSpan[] = []; const lineStarts = sourceFile.getLineStarts(); for (let i = 0; i < lineStarts.length; i++) { const currentLineStart = lineStarts[i]; const lineEnd = i + 1 === lineStarts.length ? sourceFile.getEnd() : lineStarts[i + 1] - 1; const lineText = sourceFile.text.substring(currentLineStart, lineEnd); const result = isRegionDelimiter(lineText); if (!result || isInComment(sourceFile, currentLineStart)) { continue; } if (!result[1]) { const span = createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); regions.push(createOutliningSpan(span, OutliningSpanKind.Region, span, /*autoCollapse*/ false, result[2] || "#region")); } else { const region = regions.pop(); if (region) { region.textSpan.length = lineEnd - region.textSpan.start; region.hintSpan.length = lineEnd - region.textSpan.start; out.push(region); } } } } const regionDelimiterRegExp = /^\s*\/\/\s*#(end)?region(?:\s+(.*))?(?:\r)?$/; function isRegionDelimiter(lineText: string) { return regionDelimiterRegExp.exec(lineText); } function addOutliningForLeadingCommentsForNode(n: Node, sourceFile: SourceFile, cancellationToken: CancellationToken, out: Push<OutliningSpan>): void { const comments = getLeadingCommentRangesOfNode(n, sourceFile); if (!comments) return; let firstSingleLineCommentStart = -1; let lastSingleLineCommentEnd = -1; let singleLineCommentCount = 0; const sourceText = sourceFile.getFullText(); for (const { kind, pos, end } of comments) { cancellationToken.throwIfCancellationRequested(); switch (kind) { case SyntaxKind.SingleLineCommentTrivia: // never fold region delimiters into single-line comment regions const commentText = sourceText.slice(pos, end); if (isRegionDelimiter(commentText)) { combineAndAddMultipleSingleLineComments(); singleLineCommentCount = 0; break; } // For single line comments, combine consecutive ones (2 or more) into // a single span from the start of the first till the end of the last if (singleLineCommentCount === 0) { firstSingleLineCommentStart = pos; } lastSingleLineCommentEnd = end; singleLineCommentCount++; break; case SyntaxKind.MultiLineCommentTrivia: combineAndAddMultipleSingleLineComments(); out.push(createOutliningSpanFromBounds(pos, end, OutliningSpanKind.Comment)); singleLineCommentCount = 0; break; default: Debug.assertNever(kind); } } combineAndAddMultipleSingleLineComments(); function combineAndAddMultipleSingleLineComments(): void { // Only outline spans of two or more consecutive single line comments if (singleLineCommentCount > 1) { out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, OutliningSpanKind.Comment)); } } } function createOutliningSpanFromBounds(pos: number, end: number, kind: OutliningSpanKind): OutliningSpan { return createOutliningSpan(createTextSpanFromBounds(pos, end), kind); } function getOutliningSpanForNode(n: Node, sourceFile: SourceFile): OutliningSpan | undefined { switch (n.kind) { case SyntaxKind.Block: if (isFunctionBlock(n)) { return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== SyntaxKind.ArrowFunction); } // Check if the block is standalone, or 'attached' to some parent statement. // If the latter, we want to collapse the block, but consider its hint span // to be the entire span of the parent. switch (n.parent.kind) { case SyntaxKind.DoStatement: case SyntaxKind.ForInStatement: case SyntaxKind.ForOfStatement: case SyntaxKind.ForStatement: case SyntaxKind.IfStatement: case SyntaxKind.WhileStatement: case SyntaxKind.WithStatement: case SyntaxKind.CatchClause: return spanForNode(n.parent); case SyntaxKind.TryStatement: // Could be the try-block, or the finally-block. const tryStatement = <TryStatement>n.parent; if (tryStatement.tryBlock === n) { return spanForNode(n.parent); } else if (tryStatement.finallyBlock === n) { return spanForNode(findChildOfKind(tryStatement, SyntaxKind.FinallyKeyword, sourceFile)!); } // falls through default: // Block was a standalone block. In this case we want to only collapse // the span of the block, independent of any parent span. return createOutliningSpan(createTextSpanFromNode(n, sourceFile), OutliningSpanKind.Code); } case SyntaxKind.ModuleBlock: return spanForNode(n.parent); case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.CaseBlock: return spanForNode(n); case SyntaxKind.ObjectLiteralExpression: return spanForObjectOrArrayLiteral(n); case SyntaxKind.ArrayLiteralExpression: return spanForObjectOrArrayLiteral(n, SyntaxKind.OpenBracketToken); case SyntaxKind.JsxElement: return spanForJSXElement(<JsxElement>n); case SyntaxKind.JsxSelfClosingElement: case SyntaxKind.JsxOpeningElement: return spanForJSXAttributes((<JsxOpeningLikeElement>n).attributes); } function spanForJSXElement(node: JsxElement): OutliningSpan | undefined { const textSpan = createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); const tagName = node.openingElement.tagName.getText(sourceFile); const bannerText = "<" + tagName + ">...</" + tagName + ">"; return createOutliningSpan(textSpan, OutliningSpanKind.Code, textSpan, /*autoCollapse*/ false, bannerText); } function spanForJSXAttributes(node: JsxAttributes): OutliningSpan | undefined { if (node.properties.length === 0) { return undefined; } return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), OutliningSpanKind.Code); } function spanForObjectOrArrayLiteral(node: Node, open: SyntaxKind.OpenBraceToken | SyntaxKind.OpenBracketToken = SyntaxKind.OpenBraceToken): OutliningSpan | undefined { // If the block has no leading keywords and is inside an array literal, // we only want to collapse the span of the block. // Otherwise, the collapsed section will include the end of the previous line. return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !isArrayLiteralExpression(node.parent), open); } function spanForNode(hintSpanNode: Node, autoCollapse = false, useFullStart = true, open: SyntaxKind.OpenBraceToken | SyntaxKind.OpenBracketToken = SyntaxKind.OpenBraceToken): OutliningSpan | undefined { const openToken = findChildOfKind(n, open, sourceFile); const close = open === SyntaxKind.OpenBraceToken ? SyntaxKind.CloseBraceToken : SyntaxKind.CloseBracketToken; const closeToken = findChildOfKind(n, close, sourceFile); if (!openToken || !closeToken) { return undefined; } const textSpan = createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd()); return createOutliningSpan(textSpan, OutliningSpanKind.Code, createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); } } function createOutliningSpan(textSpan: TextSpan, kind: OutliningSpanKind, hintSpan: TextSpan = textSpan, autoCollapse = false, bannerText = "..."): OutliningSpan { return { textSpan, kind, hintSpan, bannerText, autoCollapse }; } }
the_stack
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { AbstractClient } from "../../../common/abstract_client" import { ClientConfig } from "../../../common/interface" import { PeerDetailForUser, GetBcosTransListRequest, QueryRequest, QueryChainMakerContractRequest, DeployDynamicBcosContractResponse, GetClusterListForUserResponse, SendTransactionHandlerRequest, GetBlockTransactionListForUserResponse, SendTransactionHandlerResponse, ApplyUserCertRequest, TransByDynamicContractHandlerRequest, GetTransListHandlerResponse, InvokeBcosTransRequest, GetChaincodeInitializeResultForUserRequest, InitializeChaincodeForUserRequest, DeployDynamicContractHandlerResponse, SrvInvokeRequest, ApplyUserCertResponse, GetChaincodeCompileLogForUserRequest, GetBcosBlockByNumberRequest, GetPeerLogForUserResponse, GetBcosBlockListResponse, DownloadUserCertResponse, QueryChainMakerBlockTransactionRequest, GetChaincodeLogForUserRequest, GetLatesdTransactionListRequest, InvokeResponse, GetTransactionDetailForUserRequest, GetBlockListResponse, GetBlockTransactionListForUserRequest, QueryChainMakerBlockTransactionResponse, GetBcosBlockListRequest, GetClusterSummaryRequest, BlockByNumberHandlerResponse, GetTransListHandlerRequest, InvokeChainMakerContractResponse, GetTransByHashHandlerResponse, GetInvokeTxRequest, DeployDynamicContractHandlerRequest, ClusterDetailForUser, GetPeerLogForUserRequest, GetLatesdTransactionListResponse, QueryChainMakerTransactionResponse, DownloadUserCertRequest, GetClusterSummaryResponse, TransByDynamicContractHandlerResponse, PeerSet, ChainMakerTransactionResult, CreateChaincodeAndInstallForUserRequest, SrvInvokeResponse, GetBcosTransByHashResponse, GetBlockListHandlerRequest, GetChaincodeLogForUserResponse, LogDetailForUser, InvokeBcosTransResponse, InitializeChaincodeForUserResponse, GroupDetailForUser, GetBcosBlockByNumberResponse, ChainMakerContractResult, GetClusterListForUserRequest, Block, GetBlockListRequest, BcosTransInfo, GetChaincodeInitializeResultForUserResponse, InvokeRequest, GetInvokeTxResponse, GetBlockListHandlerResponse, GetTransactionDetailForUserResponse, QueryChainMakerContractResponse, GetBcosTransByHashRequest, GetChannelListForUserResponse, QueryChainMakerTransactionRequest, GetChaincodeCompileLogForUserResponse, DeployDynamicBcosContractRequest, InvokeChainMakerContractRequest, GetBcosTransListResponse, BlockByNumberHandlerRequest, BcosBlockObj, ChannelDetailForUser, GetTransByHashHandlerRequest, CreateChaincodeAndInstallForUserResponse, GetChannelListForUserRequest, QueryResponse, EndorserGroup, TransactionItem, } from "./tbaas_models" /** * tbaas client * @class */ export class Client extends AbstractClient { constructor(clientConfig: ClientConfig) { super("tbaas.tencentcloudapi.com", "2018-04-16", clientConfig) } /** * 执行Bcos交易,支持动态部署的合约 */ async InvokeBcosTrans( req: InvokeBcosTransRequest, cb?: (error: string, rep: InvokeBcosTransResponse) => void ): Promise<InvokeBcosTransResponse> { return this.request("InvokeBcosTrans", req, cb) } /** * 通过交易ID查询长安链交易 */ async QueryChainMakerTransaction( req: QueryChainMakerTransactionRequest, cb?: (error: string, rep: QueryChainMakerTransactionResponse) => void ): Promise<QueryChainMakerTransactionResponse> { return this.request("QueryChainMakerTransaction", req, cb) } /** * 使用块高查询Bcos区块信息 */ async GetBcosBlockByNumber( req: GetBcosBlockByNumberRequest, cb?: (error: string, rep: GetBcosBlockByNumberResponse) => void ): Promise<GetBcosBlockByNumberResponse> { return this.request("GetBcosBlockByNumber", req, cb) } /** * 调用长安链合约查询 */ async QueryChainMakerContract( req: QueryChainMakerContractRequest, cb?: (error: string, rep: QueryChainMakerContractResponse) => void ): Promise<QueryChainMakerContractResponse> { return this.request("QueryChainMakerContract", req, cb) } /** * 获取合约容器日志 */ async GetChaincodeLogForUser( req: GetChaincodeLogForUserRequest, cb?: (error: string, rep: GetChaincodeLogForUserResponse) => void ): Promise<GetChaincodeLogForUserResponse> { return this.request("GetChaincodeLogForUser", req, cb) } /** * Bcos根据交易哈希查看交易详细信息 */ async GetBcosTransByHash( req: GetBcosTransByHashRequest, cb?: (error: string, rep: GetBcosTransByHashResponse) => void ): Promise<GetBcosTransByHashResponse> { return this.request("GetBcosTransByHash", req, cb) } /** * 获取该用户的网络列表。网络信息中包含组织信息,但仅包含该用户所在组织的信息。 */ async GetClusterListForUser( req: GetClusterListForUserRequest, cb?: (error: string, rep: GetClusterListForUserResponse) => void ): Promise<GetClusterListForUserResponse> { return this.request("GetClusterListForUser", req, cb) } /** * Bcos分页查询当前群组下的区块列表 */ async GetBcosBlockList( req: GetBcosBlockListRequest, cb?: (error: string, rep: GetBcosBlockListResponse) => void ): Promise<GetBcosBlockListResponse> { return this.request("GetBcosBlockList", req, cb) } /** * 获取交易详情 */ async GetTransactionDetailForUser( req: GetTransactionDetailForUserRequest, cb?: (error: string, rep: GetTransactionDetailForUserResponse) => void ): Promise<GetTransactionDetailForUserResponse> { return this.request("GetTransactionDetailForUser", req, cb) } /** * 版本升级 Bcos分页查询当前群组的交易信息列表 */ async GetTransListHandler( req: GetTransListHandlerRequest, cb?: (error: string, rep: GetTransListHandlerResponse) => void ): Promise<GetTransListHandlerResponse> { return this.request("GetTransListHandler", req, cb) } /** * 新增交易 */ async Invoke( req: InvokeRequest, cb?: (error: string, rep: InvokeResponse) => void ): Promise<InvokeResponse> { return this.request("Invoke", req, cb) } /** * 获取区块链网络概要 */ async GetClusterSummary( req: GetClusterSummaryRequest, cb?: (error: string, rep: GetClusterSummaryResponse) => void ): Promise<GetClusterSummaryResponse> { return this.request("GetClusterSummary", req, cb) } /** * 获取节点日志 */ async GetPeerLogForUser( req: GetPeerLogForUserRequest, cb?: (error: string, rep: GetPeerLogForUserResponse) => void ): Promise<GetPeerLogForUserResponse> { return this.request("GetPeerLogForUser", req, cb) } /** * 动态部署并发布Bcos合约 */ async DeployDynamicBcosContract( req: DeployDynamicBcosContractRequest, cb?: (error: string, rep: DeployDynamicBcosContractResponse) => void ): Promise<DeployDynamicBcosContractResponse> { return this.request("DeployDynamicBcosContract", req, cb) } /** * 下载用户证书 */ async DownloadUserCert( req: DownloadUserCertRequest, cb?: (error: string, rep: DownloadUserCertResponse) => void ): Promise<DownloadUserCertResponse> { return this.request("DownloadUserCert", req, cb) } /** * 创建并安装合约 */ async CreateChaincodeAndInstallForUser( req: CreateChaincodeAndInstallForUserRequest, cb?: (error: string, rep: CreateChaincodeAndInstallForUserResponse) => void ): Promise<CreateChaincodeAndInstallForUserResponse> { return this.request("CreateChaincodeAndInstallForUser", req, cb) } /** * 版本升级 Bcos根据交易哈希查看交易详细信息 */ async GetTransByHashHandler( req: GetTransByHashHandlerRequest, cb?: (error: string, rep: GetTransByHashHandlerResponse) => void ): Promise<GetTransByHashHandlerResponse> { return this.request("GetTransByHashHandler", req, cb) } /** * 获取最新交易列表 */ async GetLatesdTransactionList( req: GetLatesdTransactionListRequest, cb?: (error: string, rep: GetLatesdTransactionListResponse) => void ): Promise<GetLatesdTransactionListResponse> { return this.request("GetLatesdTransactionList", req, cb) } /** * 申请用户证书 */ async ApplyUserCert( req: ApplyUserCertRequest, cb?: (error: string, rep: ApplyUserCertResponse) => void ): Promise<ApplyUserCertResponse> { return this.request("ApplyUserCert", req, cb) } /** * 调用长安链合约执行交易 */ async InvokeChainMakerContract( req: InvokeChainMakerContractRequest, cb?: (error: string, rep: InvokeChainMakerContractResponse) => void ): Promise<InvokeChainMakerContractResponse> { return this.request("InvokeChainMakerContract", req, cb) } /** * 版本升级 Bcos根据块高查询区块信息 */ async BlockByNumberHandler( req: BlockByNumberHandlerRequest, cb?: (error: string, rep: BlockByNumberHandlerResponse) => void ): Promise<BlockByNumberHandlerResponse> { return this.request("BlockByNumberHandler", req, cb) } /** * Invoke异步调用结果查询 */ async GetInvokeTx( req: GetInvokeTxRequest, cb?: (error: string, rep: GetInvokeTxResponse) => void ): Promise<GetInvokeTxResponse> { return this.request("GetInvokeTx", req, cb) } /** * 实例化结果查询 */ async GetChaincodeInitializeResultForUser( req: GetChaincodeInitializeResultForUserRequest, cb?: (error: string, rep: GetChaincodeInitializeResultForUserResponse) => void ): Promise<GetChaincodeInitializeResultForUserResponse> { return this.request("GetChaincodeInitializeResultForUser", req, cb) } /** * 获取通道列表 */ async GetChannelListForUser( req: GetChannelListForUserRequest, cb?: (error: string, rep: GetChannelListForUserResponse) => void ): Promise<GetChannelListForUserResponse> { return this.request("GetChannelListForUser", req, cb) } /** * 查询长安链指定高度区块的交易 */ async QueryChainMakerBlockTransaction( req: QueryChainMakerBlockTransactionRequest, cb?: (error: string, rep: QueryChainMakerBlockTransactionResponse) => void ): Promise<QueryChainMakerBlockTransactionResponse> { return this.request("QueryChainMakerBlockTransaction", req, cb) } /** * 实例化合约 */ async InitializeChaincodeForUser( req: InitializeChaincodeForUserRequest, cb?: (error: string, rep: InitializeChaincodeForUserResponse) => void ): Promise<InitializeChaincodeForUserResponse> { return this.request("InitializeChaincodeForUser", req, cb) } /** * 版本升级 动态部署合约 */ async DeployDynamicContractHandler( req: DeployDynamicContractHandlerRequest, cb?: (error: string, rep: DeployDynamicContractHandlerResponse) => void ): Promise<DeployDynamicContractHandlerResponse> { return this.request("DeployDynamicContractHandler", req, cb) } /** * trustsql服务统一接口 */ async SrvInvoke( req: SrvInvokeRequest, cb?: (error: string, rep: SrvInvokeResponse) => void ): Promise<SrvInvokeResponse> { return this.request("SrvInvoke", req, cb) } /** * Bcos分页查询当前群组的交易信息列表 */ async GetBcosTransList( req: GetBcosTransListRequest, cb?: (error: string, rep: GetBcosTransListResponse) => void ): Promise<GetBcosTransListResponse> { return this.request("GetBcosTransList", req, cb) } /** * 版本升级 根据动态部署的合约发送交易 */ async TransByDynamicContractHandler( req: TransByDynamicContractHandlerRequest, cb?: (error: string, rep: TransByDynamicContractHandlerResponse) => void ): Promise<TransByDynamicContractHandlerResponse> { return this.request("TransByDynamicContractHandler", req, cb) } /** * 版本升级 Bcos发送交易 */ async SendTransactionHandler( req: SendTransactionHandlerRequest, cb?: (error: string, rep: SendTransactionHandlerResponse) => void ): Promise<SendTransactionHandlerResponse> { return this.request("SendTransactionHandler", req, cb) } /** * 获取合约编译日志 */ async GetChaincodeCompileLogForUser( req: GetChaincodeCompileLogForUserRequest, cb?: (error: string, rep: GetChaincodeCompileLogForUserResponse) => void ): Promise<GetChaincodeCompileLogForUserResponse> { return this.request("GetChaincodeCompileLogForUser", req, cb) } /** * 获取区块内的交易列表 */ async GetBlockTransactionListForUser( req: GetBlockTransactionListForUserRequest, cb?: (error: string, rep: GetBlockTransactionListForUserResponse) => void ): Promise<GetBlockTransactionListForUserResponse> { return this.request("GetBlockTransactionListForUser", req, cb) } /** * 查看当前网络下的所有区块列表,分页展示 */ async GetBlockList( req: GetBlockListRequest, cb?: (error: string, rep: GetBlockListResponse) => void ): Promise<GetBlockListResponse> { return this.request("GetBlockList", req, cb) } /** * 查询交易 */ async Query( req: QueryRequest, cb?: (error: string, rep: QueryResponse) => void ): Promise<QueryResponse> { return this.request("Query", req, cb) } /** * 版本升级 Bcos分页查询当前群组下的区块列表 */ async GetBlockListHandler( req: GetBlockListHandlerRequest, cb?: (error: string, rep: GetBlockListHandlerResponse) => void ): Promise<GetBlockListHandlerResponse> { return this.request("GetBlockListHandler", req, cb) } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/serversMappers"; import * as Parameters from "../models/parameters"; import { PostgreSQLFlexibleManagementClientContext } from "../postgreSQLFlexibleManagementClientContext"; /** Class representing a Servers. */ export class Servers { private readonly client: PostgreSQLFlexibleManagementClientContext; /** * Create a Servers. * @param {PostgreSQLFlexibleManagementClientContext} client Reference to the service client. */ constructor(client: PostgreSQLFlexibleManagementClientContext) { this.client = client; } /** * Creates a new server. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param parameters The required parameters for creating or updating a server. * @param [options] The optional parameters * @returns Promise<Models.ServersCreateResponse> */ create(resourceGroupName: string, serverName: string, parameters: Models.Server, options?: msRest.RequestOptionsBase): Promise<Models.ServersCreateResponse> { return this.beginCreate(resourceGroupName,serverName,parameters,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ServersCreateResponse>; } /** * Updates an existing server. The request body can contain one to many of the properties present * in the normal server definition. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param parameters The required parameters for updating a server. * @param [options] The optional parameters * @returns Promise<Models.ServersUpdateResponse> */ update(resourceGroupName: string, serverName: string, parameters: Models.ServerForUpdate, options?: msRest.RequestOptionsBase): Promise<Models.ServersUpdateResponse> { return this.beginUpdate(resourceGroupName,serverName,parameters,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ServersUpdateResponse>; } /** * Deletes a server. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(resourceGroupName: string, serverName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginDeleteMethod(resourceGroupName,serverName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Gets information about a server. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param [options] The optional parameters * @returns Promise<Models.ServersGetResponse> */ get(resourceGroupName: string, serverName: string, options?: msRest.RequestOptionsBase): Promise<Models.ServersGetResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param callback The callback */ get(resourceGroupName: string, serverName: string, callback: msRest.ServiceCallback<Models.Server>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, serverName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Server>): void; get(resourceGroupName: string, serverName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Server>, callback?: msRest.ServiceCallback<Models.Server>): Promise<Models.ServersGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, serverName, options }, getOperationSpec, callback) as Promise<Models.ServersGetResponse>; } /** * List all the servers in a given resource group. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param [options] The optional parameters * @returns Promise<Models.ServersListByResourceGroupResponse> */ listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.ServersListByResourceGroupResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param callback The callback */ listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.ServerListResult>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param options The optional parameters * @param callback The callback */ listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ServerListResult>): void; listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ServerListResult>, callback?: msRest.ServiceCallback<Models.ServerListResult>): Promise<Models.ServersListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec, callback) as Promise<Models.ServersListByResourceGroupResponse>; } /** * List all the servers in a given subscription. * @param [options] The optional parameters * @returns Promise<Models.ServersListResponse> */ list(options?: msRest.RequestOptionsBase): Promise<Models.ServersListResponse>; /** * @param callback The callback */ list(callback: msRest.ServiceCallback<Models.ServerListResult>): void; /** * @param options The optional parameters * @param callback The callback */ list(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ServerListResult>): void; list(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ServerListResult>, callback?: msRest.ServiceCallback<Models.ServerListResult>): Promise<Models.ServersListResponse> { return this.client.sendOperationRequest( { options }, listOperationSpec, callback) as Promise<Models.ServersListResponse>; } /** * Restarts a server. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ restart(resourceGroupName: string, serverName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginRestart(resourceGroupName,serverName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Starts a server. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ start(resourceGroupName: string, serverName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginStart(resourceGroupName,serverName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Stops a server. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ stop(resourceGroupName: string, serverName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginStop(resourceGroupName,serverName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Creates a new server. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param parameters The required parameters for creating or updating a server. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreate(resourceGroupName: string, serverName: string, parameters: Models.Server, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, serverName, parameters, options }, beginCreateOperationSpec, options); } /** * Updates an existing server. The request body can contain one to many of the properties present * in the normal server definition. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param parameters The required parameters for updating a server. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginUpdate(resourceGroupName: string, serverName: string, parameters: Models.ServerForUpdate, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, serverName, parameters, options }, beginUpdateOperationSpec, options); } /** * Deletes a server. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(resourceGroupName: string, serverName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, serverName, options }, beginDeleteMethodOperationSpec, options); } /** * Restarts a server. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginRestart(resourceGroupName: string, serverName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, serverName, options }, beginRestartOperationSpec, options); } /** * Starts a server. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginStart(resourceGroupName: string, serverName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, serverName, options }, beginStartOperationSpec, options); } /** * Stops a server. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginStop(resourceGroupName: string, serverName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, serverName, options }, beginStopOperationSpec, options); } /** * List all the servers in a given resource group. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.ServersListByResourceGroupNextResponse> */ listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ServersListByResourceGroupNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ServerListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ServerListResult>): void; listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ServerListResult>, callback?: msRest.ServiceCallback<Models.ServerListResult>): Promise<Models.ServersListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByResourceGroupNextOperationSpec, callback) as Promise<Models.ServersListByResourceGroupNextResponse>; } /** * List all the servers in a given subscription. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.ServersListNextResponse> */ listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ServersListNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ServerListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ServerListResult>): void; listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ServerListResult>, callback?: msRest.ServiceCallback<Models.ServerListResult>): Promise<Models.ServersListNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listNextOperationSpec, callback) as Promise<Models.ServersListNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForPostgreSql/flexibleServers/{serverName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.serverName ], queryParameters: [ Parameters.apiVersion2 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.Server }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listByResourceGroupOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForPostgreSql/flexibleServers", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion2 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ServerListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/providers/Microsoft.DBForPostgreSql/flexibleServers", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion2 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ServerListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginCreateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForPostgreSql/flexibleServers/{serverName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.serverName ], queryParameters: [ Parameters.apiVersion2 ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.Server, required: true } }, responses: { 200: { bodyMapper: Mappers.Server }, 201: { bodyMapper: Mappers.Server }, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForPostgreSql/flexibleServers/{serverName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.serverName ], queryParameters: [ Parameters.apiVersion2 ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.ServerForUpdate, required: true } }, responses: { 200: { bodyMapper: Mappers.Server }, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForPostgreSql/flexibleServers/{serverName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.serverName ], queryParameters: [ Parameters.apiVersion2 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginRestartOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForPostgreSql/flexibleServers/{serverName}/restart", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.serverName ], queryParameters: [ Parameters.apiVersion2 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginStartOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForPostgreSql/flexibleServers/{serverName}/start", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.serverName ], queryParameters: [ Parameters.apiVersion2 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginStopOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForPostgreSql/flexibleServers/{serverName}/stop", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.serverName ], queryParameters: [ Parameters.apiVersion2 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listByResourceGroupNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], queryParameters: [ Parameters.apiVersion2 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ServerListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], queryParameters: [ Parameters.apiVersion2 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ServerListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
import * as tf from '@tensorflow/tfjs'; import { PoseNet } from '@tensorflow-models/posenet'; import { util } from '@tensorflow/tfjs'; import { TensorContainer } from '@tensorflow/tfjs-core/dist/tensor_types'; import { CustomCallbackArgs } from '@tensorflow/tfjs'; import { CustomPoseNet, Metadata, loadPoseNet } from './custom-posenet'; import * as seedrandom from 'seedrandom'; import { Initializer } from '@tensorflow/tfjs-layers/dist/initializers'; const VALIDATION_FRACTION = 0.15; export interface TrainingParameters { denseUnits: number; epochs: number; learningRate: number; batchSize: number; } interface Sample { data: Float32Array; label: number[]; } // tslint:disable-next-line:no-any // const isTensor = (c: any): c is tf.Tensor => // typeof c.dataId === 'object' && c.shape === 'object'; /** * Converts an integer into its one-hot representation and returns * the data as a JS Array. */ function flatOneHot(label: number, numClasses: number) { const labelOneHot = new Array(numClasses).fill(0) as number[]; labelOneHot[label] = 1; return labelOneHot; } /** * Shuffle an array of Float32Array or Samples using Fisher-Yates algorithm * Takes an optional seed value to make shuffling predictable */ function fisherYates(array: Float32Array[] | Sample[], seed?: seedrandom.prng) { const length = array.length; // need to clone array or we'd be editing original as we goo const shuffled = array.slice(); for (let i = (length - 1); i > 0; i -= 1) { let randomIndex ; if (seed) { randomIndex = Math.floor(seed() * (i + 1)); } else { randomIndex = Math.floor(Math.random() * (i + 1)); } [shuffled[i], shuffled[randomIndex]] = [shuffled[randomIndex],shuffled[i]]; } return shuffled; } export class TeachablePoseNet extends CustomPoseNet { /** * Training and validation datasets */ private trainDataset: tf.data.Dataset<TensorContainer>; private validationDataset: tf.data.Dataset<TensorContainer>; private __stopTrainingResolve: () => void; // private __stopTrainingReject: (error: Error) => void; // Number of total samples // private totalSamples = 0; // Array of all the examples collected public examples: Float32Array[][] = []; // Optional seed to make shuffling of data predictable private seed: seedrandom.prng; /** * has the teachable model been trained? */ public get isTrained() { return !!this.model && this.model.layers && this.model.layers.length > 2; } /** * has the dataset been prepared with all labels and samples processed? */ public get isPrepared() { return !!this.trainDataset; } /** * how many classes are in the dataset? */ public get numClasses() { return this._metadata.labels.length; } constructor(public model: tf.LayersModel, public posenetModel: PoseNet, metadata: Partial<Metadata>) { super(model, posenetModel, metadata); } /** * Add a sample of data under the provided className * @param className the classification this example belongs to * @param sample the image / tensor that belongs in this classification */ // public async addExample(className: number, sample: HTMLCanvasElement | tf.Tensor) { public async addExample(className: number, sample: Float32Array) { // TODO: Do I need to normalize or flip image? // const cap = isTensor(sample) ? sample : capture(sample); // const example = this.posenet.predict(cap) as tf.Tensor; // const embeddingsArray = await this.predictPosenet(sample); // save samples of each class separately this.examples[className].push(sample); // increase our sample counter // this.totalSamples++; } /** * Classify a pose output with your trained model. Return all results * @param image the input image / Tensor to classify against your model */ public async predict(poseOutput: Float32Array) { if (!this.model) { throw new Error('Model has not been trained yet, called train() first'); } return super.predict(poseOutput); } /** * Classify a pose output with your trained model. Return topK results * @param image the input image / Tensor to classify against your model * @param maxPredictions how many of the top results do you want? defautls to 3 */ public async predictTopK(poseOutput: Float32Array, maxPredictions = 3) { if (!this.model) { throw new Error('Model has not been trained yet, called train() first'); } return super.predictTopK(poseOutput, maxPredictions); } /** * process the current examples provided to calculate labels and format * into proper tf.data.Dataset */ public prepare() { for (const classes in this.examples){ if (classes.length === 0) { throw new Error('Add some examples before training'); } } const datasets = this.convertToTfDataset(); this.trainDataset = datasets.trainDataset; this.validationDataset = datasets.validationDataset; } /** * Process the examples by first shuffling randomly per class, then adding * one-hot labels, then splitting into training/validation datsets, and finally * sorting one last time */ private convertToTfDataset() { // first shuffle each class individually // TODO: we could basically replicate this by insterting randomly for (let i = 0; i < this.examples.length; i++) { this.examples[i] = fisherYates(this.examples[i], this.seed) as Float32Array[]; } // then break into validation and test datasets let trainDataset: Sample[] = []; let validationDataset: Sample[] = []; // for each class, add samples to train and validation dataset for (let i = 0; i < this.examples.length; i++) { const y = flatOneHot(i, this.numClasses); const classLength = this.examples[i].length; const numValidation = Math.ceil(VALIDATION_FRACTION * classLength); const numTrain = classLength - numValidation; const classTrain = this.examples[i].slice(0, numTrain).map((dataArray) => { return { data: dataArray, label: y }; }); const classValidation = this.examples[i].slice(numTrain).map((dataArray) => { return { data: dataArray, label: y }; }); trainDataset = trainDataset.concat(classTrain); validationDataset = validationDataset.concat(classValidation); } // finally shuffle both train and validation datasets trainDataset = fisherYates(trainDataset, this.seed) as Sample[]; validationDataset = fisherYates(validationDataset, this.seed) as Sample[]; const trainX = tf.data.array(trainDataset.map(sample => sample.data)); const validationX = tf.data.array(validationDataset.map(sample => sample.data)); const trainY = tf.data.array(trainDataset.map(sample => sample.label)); const validationY = tf.data.array(validationDataset.map(sample => sample.label)); // return tf.data dataset objects return { trainDataset: tf.data.zip({ xs: trainX, ys: trainY}), validationDataset: tf.data.zip({ xs: validationX, ys: validationY}) }; } /** * Saving `model`'s topology and weights as two files * (`my-model-1.json` and `my-model-1.weights.bin`) as well as * a `metadata.json` file containing metadata such as text labels to be * downloaded from browser. * @param handlerOrURL An instance of `IOHandler` or a URL-like, * scheme-based string shortcut for `IOHandler`. * @param config Options for saving the model. * @returns A `Promise` of `SaveResult`, which summarizes the result of * the saving, such as byte sizes of the saved artifacts for the model's * topology and weight values. */ public async save(handlerOrURL: tf.io.IOHandler | string, config?: tf.io.SaveConfig): Promise<tf.io.SaveResult> { return this.model.save(handlerOrURL, config); } /** * Train your data into a new model and join it with mobilenet * @param params the parameters for the model / training * @param callbacks provide callbacks to receive training events */ public async train(params: TrainingParameters, callbacks: CustomCallbackArgs = {}) { // Add callback for onTrainEnd in case of early stop const originalOnTrainEnd = callbacks.onTrainEnd || (() => {}); callbacks.onTrainEnd = (logs: tf.Logs) => { if (this.__stopTrainingResolve) { this.__stopTrainingResolve(); this.__stopTrainingResolve = null; } originalOnTrainEnd(logs); }; // Rest of train function if (!this.isPrepared) { this.prepare(); } const numLabels = this.getLabels().length; util.assert( numLabels === this.numClasses, () => `Can not train, has ${numLabels} labels and ${this.numClasses} classes`); // Inputs for posenet const inputSize = this.examples[0][1].length; // in case we need to use a seed for predictable training let varianceScaling; if (this.seed) { varianceScaling = tf.initializers.varianceScaling({ seed: 3.14}) as Initializer; } else { varianceScaling = tf.initializers.varianceScaling({}) as Initializer; } this.model = tf.sequential({ layers: [ // Layer 1. tf.layers.dense({ inputShape: [inputSize], units: params.denseUnits, activation: 'relu', kernelInitializer: varianceScaling, // 'varianceScaling' useBias: true }), // Layer 2 dropout tf.layers.dropout({rate: 0.5}), // Layer 3. The number of units of the last layer should correspond // to the number of classes we want to predict. tf.layers.dense({ units: this.numClasses, kernelInitializer: varianceScaling, // 'varianceScaling' useBias: false, activation: 'softmax' }) ] }); // const optimizer = tf.train.adam(params.learningRate); const optimizer = tf.train.rmsprop(params.learningRate); this.model.compile({ optimizer, loss: 'categoricalCrossentropy', metrics: ['accuracy'] }); if (!(params.batchSize > 0)) { throw new Error( `Batch size is 0 or NaN. Please choose a non-zero fraction` ); } const trainData = this.trainDataset.batch(params.batchSize); const validationData = this.validationDataset.batch(params.batchSize); // For debugging: check for shuffle or result from trainDataset /* await trainDataset.forEach((e: tf.Tensor[]) => { console.log(e); // @ts-ignore let data = e.ys.dataSync() as Float32Array; console.log(data); }); */ await this.model.fitDataset(trainData, { epochs: params.epochs, validationData, callbacks }); optimizer.dispose(); // cleanup return this.model; } /* * Setup the exampls array to hold samples per class */ public prepareDataset() { for (let i = 0; i < this.numClasses; i++) { this.examples[i] = []; } } public stopTraining() { const promise = new Promise((resolve, reject) => { this.model.stopTraining = true; this.__stopTrainingResolve = resolve; // this.__stopTrainingReject = reject; }); return promise; } public dispose() { this.model.dispose(); super.dispose(); } public setLabel(index: number, label: string) { this._metadata.labels[index] = label; } public setLabels(labels: string[]) { this._metadata.labels = labels; this.prepareDataset(); } public getLabel(index: number) { return this._metadata.labels[index]; } public getLabels() { return this._metadata.labels; } public setName(name: string) { this._metadata.modelName = name; } public getName() { return this._metadata.modelName; } /* * Calculate each class accuracy using the validation dataset */ public async calculateAccuracyPerClass() { const validationXs = this.validationDataset.mapAsync(async (dataset: TensorContainer) => { return (dataset as { xs: TensorContainer, ys: TensorContainer}).xs; }); const validationYs = this.validationDataset.mapAsync(async (dataset: TensorContainer) => { return (dataset as { xs: TensorContainer, ys: TensorContainer}).ys; }); // we need to split our validation data into batches in case it is too large to fit in memory const batchSize = Math.min(validationYs.size, 32); const iterations = Math.ceil(validationYs.size / batchSize); const batchesX = validationXs.batch(batchSize); const batchesY = validationYs.batch(batchSize); const itX = await batchesX.iterator(); const itY = await batchesY.iterator(); const allX = []; const allY = []; for (let i = 0; i < iterations; i++) { // 1. get the prediction values in batches const batchedXTensor = await itX.next(); const batchedXPredictionTensor = (this.model.predict(batchedXTensor.value as tf.Tensor)) as tf.Tensor; const argMaxX = batchedXPredictionTensor.argMax(1); // Returns the indices of the max values along an axis allX.push(argMaxX); // 2. get the ground truth label values in batches const batchedYTensor = await itY.next(); // Returns the indices of the max values along an axis const argMaxY = (batchedYTensor.value as tf.Tensor).argMax(1); allY.push(argMaxY); // 3. dispose of all our tensors (batchedXTensor.value as tf.Tensor).dispose(); batchedXPredictionTensor.dispose(); (batchedYTensor.value as tf.Tensor).dispose(); } // concatenate all the results of the batches const reference = tf.concat(allY); // this is the ground truth const predictions = tf.concat(allX); // this is the prediction our model is guessing // only if we concatenated more than one tensor for preference and reference if (iterations !== 1) { for (let i = 0; i < allX.length; i++) { allX[i].dispose(); allY[i].dispose(); } } return { reference, predictions }; } /* * optional seed for predictable shuffling of dataset */ public setSeed(seed: string) { this.seed = seedrandom(seed); } } export async function createTeachable(metadata: Partial<Metadata>) { const posenetModel = await loadPoseNet(metadata.modelSettings); return new TeachablePoseNet(tf.sequential(), posenetModel, metadata); }
the_stack
import fs = require("fs"); import http = require("http"); import os = require("os"); import path = require("path"); import zlib = require("zlib"); import child_process = require("child_process"); import AuthorizationHandler = require("./AuthorizationHandler"); import Logging = require("./Logging"); import Config = require("./Config") import Contracts = require("../Declarations/Contracts"); import Constants = require("../Declarations/Constants"); import AutoCollectHttpDependencies = require("../AutoCollection/HttpDependencies"); import Statsbeat = require("../AutoCollection/Statsbeat"); import Util = require("./Util"); import { URL } from "url"; class Sender { private static TAG = "Sender"; private static ICACLS_PATH = `${process.env.systemdrive}/windows/system32/icacls.exe`; private static POWERSHELL_PATH = `${process.env.systemdrive}/windows/system32/windowspowershell/v1.0/powershell.exe`; private static ACLED_DIRECTORIES: { [id: string]: boolean } = {}; private static ACL_IDENTITY: string = null; private static OS_FILE_PROTECTION_CHECKED = false; // the amount of time the SDK will wait between resending cached data, this buffer is to avoid any throttling from the service side public static WAIT_BETWEEN_RESEND = 60 * 1000; // 1 minute public static MAX_BYTES_ON_DISK = 50 * 1024 * 1024; // 50 mb public static MAX_CONNECTION_FAILURES_BEFORE_WARN = 5; public static CLEANUP_TIMEOUT = 60 * 60 * 1000; // 1 hour public static FILE_RETEMPTION_PERIOD = 7 * 24 * 60 * 60 * 1000; // 7 days public static TEMPDIR_PREFIX: string = "appInsights-node"; public static OS_PROVIDES_FILE_PROTECTION = false; public static USE_ICACLS = os.type() === "Windows_NT"; private _config: Config; private _statsbeat: Statsbeat; private _onSuccess: (response: string) => void; private _onError: (error: Error) => void; private _getAuthorizationHandler: (config: Config) => AuthorizationHandler; private _enableDiskRetryMode: boolean; private _numConsecutiveFailures: number; private _numConsecutiveRedirects: number; private _resendTimer: NodeJS.Timer | null; private _fileCleanupTimer: NodeJS.Timer; private _redirectedHost: string = null; private _tempDir: string; protected _resendInterval: number; protected _maxBytesOnDisk: number; constructor(config: Config, getAuthorizationHandler?: (config: Config) => AuthorizationHandler, onSuccess?: (response: string) => void, onError?: (error: Error) => void, statsbeat?: Statsbeat) { this._config = config; this._onSuccess = onSuccess; this._onError = onError; this._statsbeat = statsbeat; this._enableDiskRetryMode = false; this._resendInterval = Sender.WAIT_BETWEEN_RESEND; this._maxBytesOnDisk = Sender.MAX_BYTES_ON_DISK; this._numConsecutiveFailures = 0; this._numConsecutiveRedirects = 0; this._resendTimer = null; this._getAuthorizationHandler = getAuthorizationHandler; this._fileCleanupTimer = null; // tmpdir is /tmp for *nix and USERDIR/AppData/Local/Temp for Windows this._tempDir = path.join(os.tmpdir(), Sender.TEMPDIR_PREFIX + this._config.instrumentationKey); } private static _checkFileProtection() { if (!Sender.OS_PROVIDES_FILE_PROTECTION && !Sender.OS_FILE_PROTECTION_CHECKED) { Sender.OS_FILE_PROTECTION_CHECKED = true; // Node's chmod levels do not appropriately restrict file access on Windows // Use the built-in command line tool ICACLS on Windows to properly restrict // access to the temporary directory used for disk retry mode. if (Sender.USE_ICACLS) { // This should be async - but it's currently safer to have this synchronous // This guarantees we can immediately fail setDiskRetryMode if we need to try { Sender.OS_PROVIDES_FILE_PROTECTION = fs.existsSync(Sender.ICACLS_PATH); } catch (e) { } if (!Sender.OS_PROVIDES_FILE_PROTECTION) { Logging.warn(Sender.TAG, "Could not find ICACLS in expected location! This is necessary to use disk retry mode on Windows.") } } else { // chmod works everywhere else Sender.OS_PROVIDES_FILE_PROTECTION = true; } } } /** * Enable or disable offline mode */ public setDiskRetryMode(value: boolean, resendInterval?: number, maxBytesOnDisk?: number) { if (!Sender.OS_FILE_PROTECTION_CHECKED && value) { Sender._checkFileProtection(); // Only check file protection when disk retry is enabled } this._enableDiskRetryMode = Sender.OS_PROVIDES_FILE_PROTECTION && value; if (typeof resendInterval === 'number' && resendInterval >= 0) { this._resendInterval = Math.floor(resendInterval); } if (typeof maxBytesOnDisk === 'number' && maxBytesOnDisk >= 0) { this._maxBytesOnDisk = Math.floor(maxBytesOnDisk); } if (value && !Sender.OS_PROVIDES_FILE_PROTECTION) { this._enableDiskRetryMode = false; Logging.warn(Sender.TAG, "Ignoring request to enable disk retry mode. Sufficient file protection capabilities were not detected.") } if (this._enableDiskRetryMode) { if (this._statsbeat) { this._statsbeat.addFeature(Constants.StatsbeatFeature.DISK_RETRY); } // Starts file cleanup task if (!this._fileCleanupTimer) { this._fileCleanupTimer = setTimeout(() => { this._fileCleanupTask(); }, Sender.CLEANUP_TIMEOUT); this._fileCleanupTimer.unref(); } } else { if (this._statsbeat) { this._statsbeat.removeFeature(Constants.StatsbeatFeature.DISK_RETRY); } if (this._fileCleanupTimer) { clearTimeout(this._fileCleanupTimer); } } } public async send(envelopes: Contracts.EnvelopeTelemetry[], callback?: (v: string) => void) { if (envelopes) { var endpointUrl = this._redirectedHost || this._config.endpointUrl; var endpointHost = new URL(endpointUrl).hostname; // todo: investigate specifying an agent here: https://nodejs.org/api/http.html#http_class_http_agent var options = { method: "POST", withCredentials: false, headers: <{ [key: string]: string }>{ "Content-Type": "application/x-json-stream" } }; let authHandler = this._getAuthorizationHandler ? this._getAuthorizationHandler(this._config) : null; if (authHandler) { if (this._statsbeat) { this._statsbeat.addFeature(Constants.StatsbeatFeature.AAD_HANDLING); } try { // Add bearer token await authHandler.addAuthorizationHeader(options); } catch (authError) { let errorMsg = "Failed to get AAD bearer token for the Application. Error:" + authError.toString(); // If AAD auth fails do not send to Breeze if (typeof callback === "function") { callback(errorMsg); } this._storeToDisk(envelopes); Logging.warn(Sender.TAG, errorMsg); return; } } let batch: string = ""; envelopes.forEach(envelope => { var payload: string = this._stringify(envelope); if (typeof payload !== "string") { return; } batch += payload + "\n"; }); // Remove last \n if (batch.length > 0) { batch = batch.substring(0, batch.length - 1); } let payload: Buffer = Buffer.from ? Buffer.from(batch) : new Buffer(batch); zlib.gzip(payload, (err, buffer) => { var dataToSend = buffer; if (err) { Logging.warn(err); dataToSend = payload; // something went wrong so send without gzip options.headers["Content-Length"] = payload.length.toString(); } else { options.headers["Content-Encoding"] = "gzip"; options.headers["Content-Length"] = buffer.length.toString(); } Logging.info(Sender.TAG, options); // Ensure this request is not captured by auto-collection. (<any>options)[AutoCollectHttpDependencies.disableCollectionRequestOption] = true; let startTime = +new Date(); var requestCallback = (res: http.ClientResponse) => { res.setEncoding("utf-8"); //returns empty if the data is accepted var responseString = ""; res.on("data", (data: string) => { responseString += data; }); res.on("end", () => { let endTime = +new Date(); let duration = endTime - startTime; this._numConsecutiveFailures = 0; if (this._enableDiskRetryMode) { // try to send any cached events if the user is back online if (res.statusCode === 200) { if (!this._resendTimer) { this._resendTimer = setTimeout(() => { this._resendTimer = null; this._sendFirstFileOnDisk() }, this._resendInterval); this._resendTimer.unref(); } } else if (this._isRetriable(res.statusCode)) { try { if (this._statsbeat) { this._statsbeat.countRetry(Constants.StatsbeatNetworkCategory.Breeze, endpointHost); if (res.statusCode === 429) { this._statsbeat.countThrottle(Constants.StatsbeatNetworkCategory.Breeze, endpointHost); } } const breezeResponse = JSON.parse(responseString) as Contracts.BreezeResponse; let filteredEnvelopes: Contracts.EnvelopeTelemetry[] = []; breezeResponse.errors.forEach(error => { if (this._isRetriable(error.statusCode)) { filteredEnvelopes.push(envelopes[error.index]); } }); if (filteredEnvelopes.length > 0) { this._storeToDisk(filteredEnvelopes); } } catch (ex) { this._storeToDisk(envelopes); // Retriable status code with not valid Breeze response } } } // Redirect handling if (res.statusCode === 307 || // Temporary Redirect res.statusCode === 308) { // Permanent Redirect this._numConsecutiveRedirects++; // To prevent circular redirects if (this._numConsecutiveRedirects < 10) { // Try to get redirect header const locationHeader = res.headers["location"] ? res.headers["location"].toString() : null; if (locationHeader) { this._redirectedHost = locationHeader; // Send to redirect endpoint as HTTPs library doesn't handle redirect automatically this.send(envelopes, callback); } } else { if (this._statsbeat) { this._statsbeat.countException(Constants.StatsbeatNetworkCategory.Breeze, endpointHost); } if (typeof callback === "function") { callback("Error sending telemetry because of circular redirects."); } } } else { if (this._statsbeat) { this._statsbeat.countRequest(Constants.StatsbeatNetworkCategory.Breeze, endpointHost, duration, res.statusCode === 200); } this._numConsecutiveRedirects = 0; if (typeof callback === "function") { callback(responseString); } Logging.info(Sender.TAG, responseString); if (typeof this._onSuccess === "function") { this._onSuccess(responseString); } } }); }; var req = Util.makeRequest(this._config, endpointUrl, options, requestCallback); req.on("error", (error: Error) => { // todo: handle error codes better (group to recoverable/non-recoverable and persist) this._numConsecutiveFailures++; if (this._statsbeat) { this._statsbeat.countException(Constants.StatsbeatNetworkCategory.Breeze, endpointHost); } // Only use warn level if retries are disabled or we've had some number of consecutive failures sending data // This is because warn level is printed in the console by default, and we don't want to be noisy for transient and self-recovering errors // Continue informing on each failure if verbose logging is being used if (!this._enableDiskRetryMode || this._numConsecutiveFailures > 0 && this._numConsecutiveFailures % Sender.MAX_CONNECTION_FAILURES_BEFORE_WARN === 0) { let notice = "Ingestion endpoint could not be reached. This batch of telemetry items has been lost. Use Disk Retry Caching to enable resending of failed telemetry. Error:"; if (this._enableDiskRetryMode) { notice = `Ingestion endpoint could not be reached ${this._numConsecutiveFailures} consecutive times. There may be resulting telemetry loss. Most recent error:`; } Logging.warn(Sender.TAG, notice, Util.dumpObj(error)); } else { let notice = "Transient failure to reach ingestion endpoint. This batch of telemetry items will be retried. Error:"; Logging.info(Sender.TAG, notice, Util.dumpObj(error)) } this._onErrorHelper(error); if (typeof callback === "function") { if (error) { callback(Util.dumpObj(error)); } else { callback("Error sending telemetry"); } } if (this._enableDiskRetryMode) { this._storeToDisk(envelopes); } }); req.write(dataToSend); req.end(); }); } } public saveOnCrash(envelopes: Contracts.EnvelopeTelemetry[]) { if (this._enableDiskRetryMode) { this._storeToDiskSync(this._stringify(envelopes)); } } private _isRetriable(statusCode: number) { return ( statusCode === 206 || // Retriable statusCode === 401 || // Unauthorized statusCode === 403 || // Forbidden statusCode === 408 || // Timeout statusCode === 429 || // Throttle statusCode === 439 || // Quota statusCode === 500 || // Server Error statusCode === 503 // Server Unavilable ); } private _runICACLS(args: string[], callback: (err: Error) => void) { var aclProc = child_process.spawn(Sender.ICACLS_PATH, args, <any>{ windowsHide: true }); aclProc.on("error", (e: Error) => callback(e)); aclProc.on("close", (code: number, signal: string) => { return callback(code === 0 ? null : new Error(`Setting ACL restrictions did not succeed (ICACLS returned code ${code})`)); }); } private _runICACLSSync(args: string[]) { // Some very old versions of Node (< 0.11) don't have this if (child_process.spawnSync) { var aclProc = child_process.spawnSync(Sender.ICACLS_PATH, args, <any>{ windowsHide: true }); if (aclProc.error) { throw aclProc.error; } else if (aclProc.status !== 0) { throw new Error(`Setting ACL restrictions did not succeed (ICACLS returned code ${aclProc.status})`); } } else { throw new Error("Could not synchronously call ICACLS under current version of Node.js"); } } private _getACLIdentity(callback: (error: Error, identity: string) => void) { if (Sender.ACL_IDENTITY) { return callback(null, Sender.ACL_IDENTITY); } var psProc = child_process.spawn(Sender.POWERSHELL_PATH, ["-Command", "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name"], <any>{ windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] // Needed to prevent hanging on Win 7 }); let data = ""; psProc.stdout.on("data", (d: string) => data += d); psProc.on("error", (e: Error) => callback(e, null)); psProc.on("close", (code: number, signal: string) => { Sender.ACL_IDENTITY = data && data.trim(); return callback( code === 0 ? null : new Error(`Getting ACL identity did not succeed (PS returned code ${code})`), Sender.ACL_IDENTITY); }); } private _getACLIdentitySync() { if (Sender.ACL_IDENTITY) { return Sender.ACL_IDENTITY; } // Some very old versions of Node (< 0.11) don't have this if (child_process.spawnSync) { var psProc = child_process.spawnSync(Sender.POWERSHELL_PATH, ["-Command", "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name"], <any>{ windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] // Needed to prevent hanging on Win 7 }); if (psProc.error) { throw psProc.error; } else if (psProc.status !== 0) { throw new Error(`Getting ACL identity did not succeed (PS returned code ${psProc.status})`); } Sender.ACL_IDENTITY = psProc.stdout && psProc.stdout.toString().trim(); return Sender.ACL_IDENTITY; } else { throw new Error("Could not synchronously get ACL identity under current version of Node.js"); } } private _getACLArguments(directory: string, identity: string) { return [directory, "/grant", "*S-1-5-32-544:(OI)(CI)F", // Full permission for Administrators "/grant", `${identity}:(OI)(CI)F`, // Full permission for current user "/inheritance:r"]; // Remove all inherited permissions } private _applyACLRules(directory: string, callback: (err: Error) => void) { if (!Sender.USE_ICACLS) { return callback(null); } // For performance, only run ACL rules if we haven't already during this session if (Sender.ACLED_DIRECTORIES[directory] === undefined) { // Avoid multiple calls race condition by setting ACLED_DIRECTORIES to false for this directory immediately // If batches are being failed faster than the processes spawned below return, some data won't be stored to disk // This is better than the alternative of potentially infinitely spawned processes Sender.ACLED_DIRECTORIES[directory] = false; // Restrict this directory to only current user and administrator access this._getACLIdentity((err, identity) => { if (err) { Sender.ACLED_DIRECTORIES[directory] = false; // false is used to cache failed (vs undefined which is "not yet tried") return callback(err); } else { this._runICACLS(this._getACLArguments(directory, identity), (err) => { Sender.ACLED_DIRECTORIES[directory] = !err; return callback(err); }); } }); } else { return callback(Sender.ACLED_DIRECTORIES[directory] ? null : new Error("Setting ACL restrictions did not succeed (cached result)")); } } private _applyACLRulesSync(directory: string) { if (Sender.USE_ICACLS) { // For performance, only run ACL rules if we haven't already during this session if (Sender.ACLED_DIRECTORIES[directory] === undefined) { this._runICACLSSync(this._getACLArguments(directory, this._getACLIdentitySync())); Sender.ACLED_DIRECTORIES[directory] = true; // If we get here, it succeeded. _runIACLSSync will throw on failures return; } else if (!Sender.ACLED_DIRECTORIES[directory]) { // falsy but not undefined throw new Error("Setting ACL restrictions did not succeed (cached result)"); } } } private _confirmDirExists(directory: string, callback: (err: NodeJS.ErrnoException) => void): void { fs.lstat(directory, (err, stats) => { if (err && err.code === 'ENOENT') { fs.mkdir(directory, (err) => { if (err && err.code !== 'EEXIST') { // Handle race condition by ignoring EEXIST callback(err); } else { this._applyACLRules(directory, callback); } }); } else if (!err && stats.isDirectory()) { this._applyACLRules(directory, callback); } else { callback(err || new Error("Path existed but was not a directory")); } }); } /** * Computes the size (in bytes) of all files in a directory at the root level. Asynchronously. */ private _getShallowDirectorySize(directory: string, callback: (err: NodeJS.ErrnoException, size: number) => void) { // Get the directory listing fs.readdir(directory, (err, files) => { if (err) { return callback(err, -1); } let error: NodeJS.ErrnoException = null; let totalSize = 0; let count = 0; if (files.length === 0) { callback(null, 0); return; } // Query all file sizes for (let i = 0; i < files.length; i++) { fs.stat(path.join(directory, files[i]), (err, fileStats) => { count++; if (err) { error = err; } else { if (fileStats.isFile()) { totalSize += fileStats.size; } } if (count === files.length) { // Did we get an error? if (error) { callback(error, -1); } else { callback(error, totalSize); } } }); } }); } /** * Computes the size (in bytes) of all files in a directory at the root level. Synchronously. */ private _getShallowDirectorySizeSync(directory: string): number { let files = fs.readdirSync(directory); let totalSize = 0; for (let i = 0; i < files.length; i++) { totalSize += fs.statSync(path.join(directory, files[i])).size; } return totalSize; } /** * Stores the payload as a json file on disk in the temp directory */ private _storeToDisk(envelopes: Contracts.EnvelopeTelemetry[]) { // This will create the dir if it does not exist // Default permissions on *nix are directory listing from other users but no file creations Logging.info(Sender.TAG, "Checking existence of data storage directory: " + this._tempDir); this._confirmDirExists(this._tempDir, (error) => { if (error) { Logging.warn(Sender.TAG, "Error while checking/creating directory: " + (error && error.message)); this._onErrorHelper(error); return; } this._getShallowDirectorySize(this._tempDir, (err, size) => { if (err || size < 0) { Logging.warn(Sender.TAG, "Error while checking directory size: " + (err && err.message)); this._onErrorHelper(err); return; } else if (size > this._maxBytesOnDisk) { Logging.warn(Sender.TAG, "Not saving data due to max size limit being met. Directory size in bytes is: " + size); return; } //create file - file name for now is the timestamp, a better approach would be a UUID but that //would require an external dependency var fileName = new Date().getTime() + ".ai.json"; var fileFullPath = path.join(this._tempDir, fileName); // Mode 600 is w/r for creator and no read access for others (only applies on *nix) // For Windows, ACL rules are applied to the entire directory (see logic in _confirmDirExists and _applyACLRules) Logging.info(Sender.TAG, "saving data to disk at: " + fileFullPath); fs.writeFile(fileFullPath, this._stringify(envelopes), { mode: 0o600 }, (error) => this._onErrorHelper(error)); }); }); } /** * Stores the payload as a json file on disk using sync file operations * this is used when storing data before crashes */ private _storeToDiskSync(payload: any) { try { Logging.info(Sender.TAG, "Checking existence of data storage directory: " + this._tempDir); if (!fs.existsSync(this._tempDir)) { fs.mkdirSync(this._tempDir); } // Make sure permissions are valid this._applyACLRulesSync(this._tempDir); let dirSize = this._getShallowDirectorySizeSync(this._tempDir); if (dirSize > this._maxBytesOnDisk) { Logging.info(Sender.TAG, "Not saving data due to max size limit being met. Directory size in bytes is: " + dirSize); return; } //create file - file name for now is the timestamp, a better approach would be a UUID but that //would require an external dependency var fileName = new Date().getTime() + ".ai.json"; var fileFullPath = path.join(this._tempDir, fileName); // Mode 600 is w/r for creator and no access for anyone else (only applies on *nix) Logging.info(Sender.TAG, "saving data before crash to disk at: " + fileFullPath); fs.writeFileSync(fileFullPath, payload, { mode: 0o600 }); } catch (error) { Logging.warn(Sender.TAG, "Error while saving data to disk: " + (error && error.message)); this._onErrorHelper(error); } } /** * Check for temp telemetry files * reads the first file if exist, deletes it and tries to send its load */ private _sendFirstFileOnDisk(): void { fs.exists(this._tempDir, (exists: boolean) => { if (exists) { fs.readdir(this._tempDir, (error, files) => { if (!error) { files = files.filter(f => path.basename(f).indexOf(".ai.json") > -1); if (files.length > 0) { var firstFile = files[0]; var filePath = path.join(this._tempDir, firstFile); fs.readFile(filePath, (error, buffer) => { if (!error) { // delete the file first to prevent double sending fs.unlink(filePath, (error) => { if (!error) { try { let envelopes: Contracts.EnvelopeTelemetry[] = JSON.parse(buffer.toString()); this.send(envelopes); } catch (error) { Logging.warn("Failed to read persisted file", error); } } else { this._onErrorHelper(error); } }); } else { this._onErrorHelper(error); } }); } } else { this._onErrorHelper(error); } }); } }); } private _onErrorHelper(error: Error): void { if (typeof this._onError === "function") { this._onError(error); } } private _stringify(payload: any) { try { return JSON.stringify(payload); } catch (error) { Logging.warn("Failed to serialize payload", error, payload); } } private _fileCleanupTask() { fs.exists(this._tempDir, (exists: boolean) => { if (exists) { fs.readdir(this._tempDir, (error, files) => { if (!error) { files = files.filter(f => path.basename(f).indexOf(".ai.json") > -1); if (files.length > 0) { files.forEach(file => { // Check expiration let fileCreationDate: Date = new Date(parseInt(file.split(".ai.json")[0])); let expired = new Date(+(new Date()) - Sender.FILE_RETEMPTION_PERIOD) > fileCreationDate; if (expired) { var filePath = path.join(this._tempDir, file); fs.unlink(filePath, (error) => { if (error) { this._onErrorHelper(error); } }); } }); } } else { this._onErrorHelper(error); } }); } }); } } export = Sender;
the_stack
import { PointModel } from '../primitives/point-model'; import { NodeModel } from './node-model'; import { Rect } from '../primitives/rect'; import { Diagram } from '../diagram'; import { DiagramElement } from '../core/elements/diagram-element'; import { PathElement } from '../core/elements/path-element'; import { SnapConstraints } from '../enum/enum'; import { Connector } from './connector'; import { Node, Selector } from '../objects/node'; import { SelectorModel } from '../objects/node-model'; import { Gridlines } from '../diagram/grid-lines'; import { SnapSettingsModel } from '../diagram/grid-lines-model'; import { getBounds } from './../utility/base-util'; import { SpatialSearch } from '../interaction/spatial-search/spatial-search'; import { Quad } from '../interaction/spatial-search/quad'; import { randomId } from './../utility/base-util'; import { DiagramScroller, TransformFactor } from '../interaction/scroller'; import { DiagramRenderer } from '../rendering/renderer'; import { LineAttributes, PathAttributes } from '../rendering/canvas-interface'; import { getAdornerLayerSvg } from './../utility/dom-util'; import { isSelected } from '../interaction/actions'; import { TextElement } from '../core/elements/text-element'; import { DiagramHtmlElement } from '../core/elements/html-element'; import { Container } from '../core/containers/container'; /** * Snapping */ export class Snapping { private line: LineAttributes[] = []; private diagram: Diagram; private render: DiagramRenderer; constructor(diagram: Diagram) { this.diagram = diagram; } /** @private */ public canSnap(): boolean { return (this.diagram.snapSettings.constraints & (SnapConstraints.SnapToObject | SnapConstraints.SnapToLines)) !== 0; } private getWrapperObject(selectedObject: SelectorModel, nameTable: {}): Container { if (selectedObject.nodes && selectedObject.nodes.length > 0 && (this.diagram.snapSettings.constraints & SnapConstraints.SnapToLines || this.diagram.snapSettings.constraints & SnapConstraints.SnapToObject)) { for (let i: number = 0; i < selectedObject.nodes.length; i++) { if (((selectedObject.nodes[i].shape.type === "SwimLane" || (selectedObject.nodes[i] as Node).isLane) || (selectedObject.nodes[i] as Node).parentId !== '' && nameTable[((selectedObject.nodes[i] as Node).parentId)] && nameTable[((selectedObject.nodes[i] as Node).parentId)].isLane) && nameTable['helper']) { return nameTable['helper'].wrapper; } else { return selectedObject.wrapper; } } } return selectedObject.wrapper; }; public setSnapLineColor():string { return this.diagram.snapSettings.snapLineColor; } /** * Snap to object * * @private */ public snapPoint( diagram: Diagram, selectedObject: SelectorModel, towardsLeft: boolean, towardsTop: boolean, delta: PointModel, startPoint: PointModel, endPoint: PointModel): PointModel { const snapSettings: SnapSettingsModel = this.diagram.snapSettings; const zoomFactor: number = this.diagram.scroller.currentZoom; const offset: PointModel = { x: 0, y: 0 }; let wrapper: Container; wrapper = this.getWrapperObject(selectedObject, diagram.nameTable); const bounds: Rect = getBounds(wrapper); const horizontallysnapped: Snap = { snapped: false, offset: 0 }; const verticallysnapped: Snap = { snapped: false, offset: 0 }; if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToObject) { //let snapLine: SVGElement; const snapLine: SVGElement = document.createElementNS('http://www.w3.org/2000/svg', 'g'); snapLine.setAttribute('id', '_SnappingLines'); snapLine.setAttribute('shapeRendering', 'crispEdges'); this.getAdornerLayerSvg().appendChild(snapLine); this.snapObject( diagram, selectedObject, snapLine, horizontallysnapped, verticallysnapped, delta, startPoint === endPoint); } //original position const left: number = bounds.x + delta.x; const top: number = bounds.y + delta.y; const right: number = bounds.x + bounds.width + delta.x; const bottom: number = bounds.y + bounds.height + delta.y; let scaledIntervals: number[] = (snapSettings.verticalGridlines as Gridlines).scaledIntervals; //snapped positions const roundedRight: number = this.round(right, scaledIntervals, zoomFactor); const roundedLeft: number = this.round(left, scaledIntervals, zoomFactor); scaledIntervals = (snapSettings.horizontalGridlines as Gridlines).scaledIntervals; const roundedTop: number = this.round(top, scaledIntervals, zoomFactor); const roundedBottom: number = this.round(bottom, scaledIntervals, zoomFactor); //currentposition const currentright: number = bounds.x + bounds.width; const currentbottom: number = bounds.y + bounds.height; if (!horizontallysnapped.snapped) { if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToVerticalLines) { if (Math.abs(delta.x) >= 1) { if (towardsLeft) { if (Math.abs(roundedRight - currentright) > Math.abs(roundedLeft - bounds.x)) { offset.x += roundedLeft - bounds.x; } else { offset.x += roundedRight - currentright; } } else { if (Math.abs(roundedRight - currentright) < Math.abs(roundedLeft - bounds.x)) { offset.x += roundedRight - currentright; } else { offset.x += roundedLeft - bounds.x; } } } } else { offset.x = endPoint.x - startPoint.x; } } else { if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToObject) { offset.x = horizontallysnapped.offset; } else { offset.x = endPoint.x - startPoint.x; } } if (!verticallysnapped.snapped) { if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToHorizontalLines) { if (Math.abs(delta.y) >= 1) { if (towardsTop) { if (Math.abs(roundedBottom - currentbottom) > Math.abs(roundedTop - bounds.y)) { offset.y += roundedTop - bounds.y; } else { offset.y += roundedBottom - currentbottom; } } else { if (Math.abs(roundedBottom - currentbottom) < Math.abs(roundedTop - bounds.y)) { offset.y += roundedBottom - currentbottom; } else { offset.y += roundedTop - bounds.y; } } } } else { offset.y = endPoint.y - startPoint.y; } } else { offset.y = verticallysnapped.offset; } return offset; } /** * @private */ public round(value: number, snapIntervals: number[], scale: number): number { if (scale === 1) { scale = Math.pow(2, Math.floor(Math.log(scale) / Math.log(2))); } else { scale = scale; } let cutoff: number = 0; let i: number = 0; for (i = 0; i < snapIntervals.length; i++) { cutoff += snapIntervals[i]; } cutoff /= scale; const quotient: number = Math.floor(Math.abs(value) / cutoff); let bal: number = value % cutoff; let prev: number = quotient * cutoff; if (prev !== value) { if (value >= 0) { for (i = 0; i < snapIntervals.length; i++) { if (bal <= snapIntervals[i] / scale) { return prev + (bal < (snapIntervals[i] / (2 * scale)) ? 0 : snapIntervals[i] / scale); } else { prev += snapIntervals[i] / scale; bal -= snapIntervals[i] / scale; } } } else { prev = prev * -1; for (i = snapIntervals.length - 1; i >= 0; i--) { if (Math.abs(bal) <= snapIntervals[i] / scale) { return prev - (Math.abs(bal) < (snapIntervals[i] / (2 * scale)) ? 0 : snapIntervals[i] / scale); } else { prev -= snapIntervals[i] / scale; bal += snapIntervals[i] / scale; } } } } return value; } //Snap to Object private snapObject( diagram: Diagram, selectedObject: SelectorModel, g: SVGElement, horizontalSnap: Snap, verticalSnap: Snap, delta: PointModel, ended: boolean): void { let lengthX: number = null; let lengthY: number; let hTarget: SnapObject; let vTarget: SnapObject; const scroller: DiagramScroller = this.diagram.scroller; const snapSettings: SnapSettingsModel = this.diagram.snapSettings; const objectsAtLeft: Objects[] = []; const objectsAtRight: Objects[] = []; const objectsAtTop: Objects[] = []; const objectsAtBottom: Objects[] = []; let wrapper: Container; wrapper = this.getWrapperObject(selectedObject, diagram.nameTable); const bounds: Rect = getBounds(wrapper); const scale: number = diagram.scroller.currentZoom; const hoffset: number = -scroller.horizontalOffset; const voffset: number = -scroller.verticalOffset; const snapObjDistance: number = snapSettings.snapObjectDistance / scale; let viewPort: Rect = new Rect(0, 0, scroller.viewPortWidth, scroller.viewPortHeight); const hIntersectRect: Rect = new Rect( hoffset / scale, (bounds.y - snapObjDistance - 5), viewPort.width / scale, (bounds.height + 2 * snapObjDistance + 10)); const vIntersectRect: Rect = new Rect( (bounds.x - snapObjDistance - 5), voffset / scale, (bounds.width + 2 * snapObjDistance + 10), viewPort.height / scale); viewPort = new Rect( hoffset / scale, voffset / scale, viewPort.width / scale, viewPort.height / scale); let nodes: DiagramElement[] = this.findNodes(diagram.spatialSearch, selectedObject, vIntersectRect, viewPort); let i: number; let target: DiagramElement; let targetBounds: Rect; const nameTable: NodeModel = diagram.nameTable; for (i = 0; i < nodes.length; i++) { target = nodes[i]; if (this.canBeTarget(diagram, target)) { if (!(this.diagram.nameTable[target.id] instanceof Connector) && this.canConsider(nameTable, selectedObject, target)) { targetBounds = target.bounds; if (targetBounds.height + targetBounds.y < delta.y + bounds.y) { objectsAtTop.push({ obj: target, distance: Math.abs(bounds.y + delta.y - targetBounds.y - targetBounds.height) }); } else if (targetBounds.y > bounds.y + delta.y + bounds.height) { objectsAtBottom.push({ obj: target, distance: Math.abs(bounds.y + delta.y + bounds.height - targetBounds.y) }); } if (lengthX == null || lengthX > Math.abs(targetBounds.y - bounds.y - delta.y)) { if (Math.abs(targetBounds.x + targetBounds.width / 2 - (bounds.x + bounds.width / 2 + delta.x)) <= snapObjDistance) { hTarget = this.createSnapObject(targetBounds, bounds, 'centerX'); lengthX = Math.abs(targetBounds.y - bounds.y); } else if (Math.abs(targetBounds.x + targetBounds.width - (bounds.x + bounds.width + delta.x)) <= snapObjDistance) { hTarget = this.createSnapObject(targetBounds, bounds, 'right'); lengthX = Math.abs(targetBounds.y - bounds.y); } else if (Math.abs(targetBounds.x - (bounds.x + delta.x)) <= snapObjDistance) { hTarget = this.createSnapObject(targetBounds, bounds, 'left'); lengthX = Math.abs(targetBounds.y - bounds.y); } else if (Math.abs(targetBounds.x - (bounds.x + bounds.width + delta.x)) <= snapObjDistance) { hTarget = this.createSnapObject(targetBounds, bounds, 'rightLeft'); lengthX = Math.abs(targetBounds.y - bounds.y); } else if (Math.abs(targetBounds.x + targetBounds.width - (bounds.x + delta.x)) <= snapObjDistance) { hTarget = this.createSnapObject(targetBounds, bounds, 'leftRight'); lengthX = Math.abs(targetBounds.y - bounds.y); } } } } } nodes = this.findNodes(diagram.spatialSearch, selectedObject, hIntersectRect, viewPort); for (let j: number = 0; j < nodes.length; j++) { target = nodes[j]; if (this.canBeTarget(diagram, target)) { if (!(this.diagram.nameTable[target.id] instanceof Connector) && this.canConsider(nameTable, selectedObject, target)) { targetBounds = target.bounds; if (targetBounds.x + targetBounds.width < bounds.x + delta.x) { objectsAtLeft[objectsAtLeft.length] = { obj: target, distance: Math.abs((bounds.x + delta.x) - targetBounds.x - targetBounds.width) }; } if (targetBounds.x > bounds.x + delta.x + bounds.width) { objectsAtRight[objectsAtRight.length] = { obj: target, distance: Math.abs(bounds.x + delta.x + bounds.width - targetBounds.x) }; } if (lengthY == null || lengthY > Math.abs(targetBounds.x - bounds.x - delta.x)) { if (Math.abs(targetBounds.y + targetBounds.height / 2 - (bounds.y + bounds.height / 2 + delta.y)) <= snapObjDistance) { vTarget = this.createSnapObject(targetBounds, bounds, 'centerY'); lengthY = Math.abs(targetBounds.x - bounds.x); } else if (Math.abs(targetBounds.y - bounds.y - delta.y) <= snapObjDistance) { vTarget = this.createSnapObject(targetBounds, bounds, 'top'); lengthY = Math.abs(targetBounds.x - bounds.x); } else if (Math.abs(targetBounds.y + targetBounds.height - (bounds.y + bounds.height + delta.y)) <= snapObjDistance) { vTarget = this.createSnapObject(targetBounds, bounds, 'bottom'); lengthY = Math.abs(targetBounds.x - bounds.x); } else if (Math.abs(targetBounds.y + targetBounds.height - bounds.y - delta.y) <= snapObjDistance) { vTarget = this.createSnapObject(targetBounds, bounds, 'topBottom'); lengthY = Math.abs(targetBounds.x - bounds.x); } else if (Math.abs(targetBounds.y - (bounds.y + bounds.height + delta.y)) <= snapObjDistance) { vTarget = this.createSnapObject(targetBounds, bounds, 'bottomTop'); lengthY = Math.abs(targetBounds.x - bounds.x); } } } } } this.createGuidelines(diagram, hTarget, vTarget, g, horizontalSnap, verticalSnap, ended); if (!horizontalSnap.snapped) { this.createHSpacingLines( diagram, g, selectedObject, objectsAtLeft, objectsAtRight, horizontalSnap, verticalSnap, ended, delta, snapObjDistance); } if (!verticalSnap.snapped) { this.createVSpacingLines( diagram, g, selectedObject, objectsAtTop, objectsAtBottom, horizontalSnap, verticalSnap, ended, delta, snapObjDistance); } } /** * @private */ public snapConnectorEnd(point: PointModel): PointModel { const snapSettings: SnapSettingsModel = this.diagram.snapSettings; const zoomFactor: number = this.diagram.scroller.currentZoom; if (snapSettings.constraints & SnapConstraints.SnapToLines) { point.x = this.round(point.x, (snapSettings.verticalGridlines as Gridlines).scaledIntervals, zoomFactor); point.y = this.round(point.y, (snapSettings.horizontalGridlines as Gridlines).scaledIntervals, zoomFactor); } return point; } private canBeTarget(diagram: Diagram, node: NodeModel): boolean { node = this.diagram.nameTable[node.id]; return !(isSelected(this.diagram, node, false)); } private snapSize( diagram: Diagram, horizontalSnap: Snap, verticalSnap: Snap, snapLine: SVGElement, deltaX: number, deltaY: number, selectedObject: SelectorModel, ended: boolean): void { let lengthX: number; let lengthY: number; const snapSettings: SnapSettingsModel = this.diagram.snapSettings; const scroller: DiagramScroller = this.diagram.scroller; let hTarget: SnapObject; let vTarget: SnapObject; const bounds: Rect = getBounds(selectedObject.wrapper); const nameTable: NodeModel = diagram.nameTable; const sameWidth: SnapSize[] = []; const sameHeight: SnapSize[] = []; const scale: number = diagram.scroller.currentZoom; const hoffset: number = -scroller.horizontalOffset; const voffset: number = -scroller.verticalOffset; const snapObjDistance: number = snapSettings.snapObjectDistance / scale; let viewPort: Rect = new Rect(0, 0, scroller.viewPortWidth, scroller.viewPortHeight); const hintersectedrect: Rect = new Rect( hoffset / scale, (bounds.y - 5) / scale, viewPort.width / scale, (bounds.height + 10) / scale); const vintersectedrect: Rect = new Rect( (bounds.x - 5) / scale, voffset / scale, (bounds.width + 10) / scale, viewPort.height / scale); viewPort = new Rect( hoffset / scale, voffset / scale, viewPort.width / scale, viewPort.height / scale); const nodesInView: DiagramElement[] = []; let nodes: DiagramElement[] = this.findNodes(diagram.spatialSearch, selectedObject, vintersectedrect, viewPort, nodesInView); let i: number; let target: DiagramElement; let targetBounds: Rect; for (i = 0; i < nodes.length; i++) { target = nodes[i]; if (this.canConsider(nameTable, selectedObject, target) && !(this.diagram.nameTable[target.id] instanceof Connector)) { targetBounds = target.bounds; if (lengthX == null || lengthX > Math.abs(targetBounds.y - bounds.y)) { if (horizontalSnap.left) { if (Math.abs(bounds.x + deltaX - targetBounds.x) <= snapObjDistance) { hTarget = this.createSnapObject(targetBounds, bounds, 'left'); lengthX = Math.abs(targetBounds.y - bounds.y); } else if (Math.abs(bounds.x + deltaX - targetBounds.x - targetBounds.width) <= snapObjDistance) { hTarget = this.createSnapObject(targetBounds, bounds, 'leftRight'); lengthX = Math.abs(targetBounds.y - bounds.y); } } else if (horizontalSnap.right) { if (Math.abs(bounds.x + deltaX + bounds.width - targetBounds.x - targetBounds.width) <= snapObjDistance) { hTarget = this.createSnapObject(targetBounds, bounds, 'right'); lengthX = Math.abs(targetBounds.y - bounds.y); } else if (Math.abs(bounds.x + deltaX + bounds.width - targetBounds.x) <= snapObjDistance) { hTarget = this.createSnapObject(targetBounds, bounds, 'rightLeft'); lengthX = Math.abs(targetBounds.y - bounds.y); } } } } } nodes = this.findNodes(diagram.spatialSearch, selectedObject, hintersectedrect, viewPort); for (let i: number = 0; i < nodes.length; i++) { const target: DiagramElement = nodes[i]; if (this.canConsider(nameTable, selectedObject, target) && !(this.diagram.nameTable[target.id] instanceof Connector)) { const targetBounds: Rect = target.bounds; if (lengthY == null || lengthY > Math.abs(targetBounds.x - bounds.x)) { if (verticalSnap.top) { if (Math.abs(bounds.y + deltaY - targetBounds.y) <= snapObjDistance) { vTarget = this.createSnapObject(targetBounds, bounds, 'top'); lengthY = Math.abs(targetBounds.x - bounds.x); } else if (Math.abs(bounds.y + deltaY - targetBounds.y - targetBounds.height) <= snapObjDistance) { vTarget = this.createSnapObject(targetBounds, bounds, 'topBottom'); lengthY = Math.abs(targetBounds.x - bounds.x); } } else if (verticalSnap.bottom) { if (Math.abs(bounds.y + bounds.height + deltaY - targetBounds.y - targetBounds.height) <= snapObjDistance) { vTarget = this.createSnapObject(targetBounds, bounds, 'bottom'); lengthY = Math.abs(targetBounds.x - bounds.x); } else if (Math.abs(bounds.y + bounds.height + deltaY - targetBounds.y) <= snapObjDistance) { vTarget = this.createSnapObject(targetBounds, bounds, 'bottomTop'); lengthY = Math.abs(targetBounds.x - bounds.x); } } } } } for (i = 0; i < nodesInView.length; i++) { target = nodesInView[i]; if (this.canConsider(nameTable, selectedObject, target)) { const targetBounds: Rect = target.bounds; let delta: number = horizontalSnap.left ? -deltaX : deltaX; const difference: number = Math.abs(bounds.width + delta - targetBounds.width); let actualDiff: number; if (difference <= snapObjDistance) { actualDiff = horizontalSnap.left ? -targetBounds.width + bounds.width : targetBounds.width - bounds.width; sameWidth[sameWidth.length] = { source: target, difference: difference, offset: actualDiff }; } delta = verticalSnap.top ? -deltaY : deltaY; const dify: number = Math.abs(bounds.height + delta - targetBounds.height); if (dify <= snapObjDistance) { actualDiff = verticalSnap.top ? -targetBounds.height + bounds.height : targetBounds.height - bounds.height; sameHeight[sameHeight.length] = { source: target, difference: dify, offset: actualDiff }; } } } let g: SVGElement; if (!diagram.getTool) { const g: SVGElement = this.createGuidelines(diagram, hTarget, vTarget, snapLine, horizontalSnap, verticalSnap, ended); } if (!horizontalSnap.snapped && sameWidth.length > 0 && (horizontalSnap.left || horizontalSnap.right)) { this.addSameWidthLines(diagram, snapLine, sameWidth, horizontalSnap, ended, selectedObject); } if (!verticalSnap.snapped && sameHeight.length > 0 && (verticalSnap.top || verticalSnap.bottom)) { this.addSameHeightLines(diagram, snapLine, sameHeight, verticalSnap, ended, selectedObject); } } /** * Snap to object on top * * @private */ public snapTop( horizontalSnap: Snap, verticalSnap: Snap, snapLine: SVGElement, deltaX: number, deltaY: number, shape: SelectorModel, ended: boolean, initialBoundsT: Rect): number { let dify: number = deltaY; verticalSnap.top = true; let y: number; horizontalSnap.left = horizontalSnap.right = false; const zoomFactor: number = this.diagram.scroller.currentZoom; //let initialBoundsT: Rect = new Rect(shape.offsetX, shape.offsetY, shape.width, shape.height); if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToObject && !shape.rotateAngle) { //(!this.selectedObject.isLane && !this.selectedObject.isSwimlane)) { y = initialBoundsT.y - initialBoundsT.height * shape.pivot.y + deltaY - (shape.offsetY - shape.height * shape.pivot.y); this.snapSize(this.diagram, horizontalSnap, verticalSnap, snapLine, deltaX, y, this.diagram.selectedItems, ended); } if (!verticalSnap.snapped) { if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToHorizontalLines) { const top: number = initialBoundsT.y - initialBoundsT.height * shape.pivot.y; const actualTop: number = top + deltaY; const roundedTop: number = this.round( actualTop, (this.diagram.snapSettings.horizontalGridlines as Gridlines).scaledIntervals, zoomFactor); dify = roundedTop - top; } } else { dify = (deltaY - y) + verticalSnap.offset; } return dify; } /** * Snap to object on right * * @private */ public snapRight( horizontalSnap: Snap, verticalSnap: Snap, snapLine: SVGElement, deltaX: number, deltaY: number, shape: SelectorModel, ended: boolean, initialBound: Rect): number { let difx: number = deltaX; let x: number; horizontalSnap.right = true; verticalSnap.top = verticalSnap.bottom = false; const zoomFactor: number = this.diagram.scroller.currentZoom; //let initialBound: Rect = new Rect(shape.offsetX, shape.offsetY, shape.width, shape.height); if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToObject && !shape.rotateAngle) { //(!this.selectedObject.isLane && !this.selectedObject.isSwimlane)) { x = initialBound.x + initialBound.width * (1 - shape.pivot.x) + deltaX - (shape.offsetX + shape.width * (1 - shape.pivot.x)); this.snapSize(this.diagram, horizontalSnap, verticalSnap, snapLine, x, deltaY, this.diagram.selectedItems, ended); } if (!horizontalSnap.snapped) { if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToVerticalLines) { const right: number = initialBound.x + initialBound.width * (1 - shape.pivot.x); const actualRight: number = right + deltaX; const roundedRight: number = this.round( actualRight, (this.diagram.snapSettings.verticalGridlines as Gridlines).scaledIntervals, zoomFactor); difx = roundedRight - right; } } else { difx = (deltaX - x) + horizontalSnap.offset; } return difx; } /** * Snap to object on left * * @private */ public snapLeft( horizontalSnap: Snap, verticalSnap: Snap, snapLine: SVGElement, deltaX: number, deltaY: number, shape: SelectorModel, ended: boolean, initialBoundsB: Rect): number { let difx: number = deltaX; let x: number = 0; horizontalSnap.left = true; verticalSnap.top = verticalSnap.bottom = false; const zoomFactor: number = this.diagram.scroller.currentZoom; //let initialBoundsB: Rect = new Rect(shape.offsetX, shape.offsetY, shape.width, shape.height); if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToObject && !shape.rotateAngle) { //(!this.selectedObject.isLane && !this.selectedObject.isSwimlane)) { x = initialBoundsB.x - initialBoundsB.width * shape.pivot.x + deltaX - (shape.offsetX - shape.width * shape.pivot.x); this.snapSize(this.diagram, horizontalSnap, verticalSnap, snapLine, x, deltaY, this.diagram.selectedItems, ended); } if (!horizontalSnap.snapped) { if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToVerticalLines) { const left: number = initialBoundsB.x - initialBoundsB.width * shape.pivot.x; const actualLeft: number = left + deltaX; const roundedLeft: number = this.round( actualLeft, (this.diagram.snapSettings.horizontalGridlines as Gridlines).scaledIntervals, zoomFactor); difx = roundedLeft - left; } } else { difx = (deltaX - x) + horizontalSnap.offset; } return difx; } /** * Snap to object on bottom * * @private */ public snapBottom( horizontalSnap: Snap, verticalSnap: Snap, snapLine: SVGElement, deltaX: number, deltaY: number, shape: SelectorModel | DiagramElement, ended: boolean, initialRect: Rect): number { let dify: number = deltaY; verticalSnap.bottom = true; horizontalSnap.left = horizontalSnap.right = false; const zoomFactor: number = this.diagram.scroller.currentZoom; let y: number = 0; //let initialRect: Rect = new Rect(shape.offsetX, shape.offsetY, shape.width, shape.height); if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToObject && !shape.rotateAngle) { //(!this.selectedObject.isLane && !this.selectedObject.isSwimlane)) { y = initialRect.y + initialRect.height * (1 - shape.pivot.y) + deltaY - (shape.offsetY + shape.height * (1 - shape.pivot.y)); this.snapSize(this.diagram, horizontalSnap, verticalSnap, snapLine, deltaX, y, this.diagram.selectedItems, ended); } // eslint-disable-next-line max-len const bounds: Rect = ((shape instanceof TextElement) || (shape instanceof DiagramHtmlElement)) ? getBounds(shape as DiagramElement) : getBounds((shape as SelectorModel).wrapper); if (!verticalSnap.snapped) { if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToHorizontalLines) { const bottom: number = initialRect.y + initialRect.height * (1 - shape.pivot.y); const actualBottom: number = bottom + deltaY; const roundedBottom: number = this.round( actualBottom, (this.diagram.snapSettings.horizontalGridlines as Gridlines).scaledIntervals, zoomFactor); dify = roundedBottom - bottom; } } else { dify = (deltaY - y) + verticalSnap.offset; } return dify; } //To create the same width and same size lines private createGuidelines( diagram: Diagram, hTarget: SnapObject, vTarget: SnapObject, snapLine: SVGElement, horizontalSnap: Snap, verticalSnap: Snap, ended: boolean): SVGElement { if (hTarget) { horizontalSnap.offset = hTarget.offsetX; horizontalSnap.snapped = true; if (!ended) { if (hTarget.type === 'sideAlign') { this.renderAlignmentLines(hTarget.start, hTarget.end, snapLine, diagram.scroller.transform); } else { this.renderAlignmentLines(hTarget.start, hTarget.end, snapLine, diagram.scroller.transform); } } } if (vTarget) { verticalSnap.offset = vTarget.offsetY; verticalSnap.snapped = true; if (!ended) { if (vTarget.type === 'sideAlign') { this.renderAlignmentLines(vTarget.start, vTarget.end, snapLine, diagram.scroller.transform); } else { this.renderAlignmentLines(vTarget.start, vTarget.end, snapLine, diagram.scroller.transform); } } } return snapLine; } //To create the alignment lines private renderAlignmentLines( start: PointModel, end: PointModel, svg: SVGElement, transform: TransformFactor): void { start = { x: (start.x + transform.tx) * transform.scale, y: (start.y + transform.ty) * transform.scale }; end = { x: (end.x + transform.tx) * transform.scale, y: (end.y + transform.ty) * transform.scale }; const line1: LineAttributes = { stroke:this.setSnapLineColor(), strokeWidth: 1, startPoint: { x: start.x, y: start.y }, endPoint: { x: end.x, y: end.y }, fill:this.setSnapLineColor(), dashArray: '', width: 1, x: 0, y: 0, height: 0, angle: 0, pivotX: 0, pivotY: 0, visible: true, opacity: 1, id: randomId() }; let i: number = 0; this.line.push(line1); for (i = 0; i < this.line.length; i++) { this.diagram.diagramRenderer.drawLine(svg, this.line.pop()); } } //To create Horizontal spacing lines private createHSpacingLines( diagram: Diagram, g: SVGElement, shape: SelectorModel, objectsAtLeft: Objects[], objectsAtRight: Objects[], horizontalSnap: Snap, verticalSnap: Snap, ended: boolean, delta: PointModel, snapObjDistance: number): void { let top: number = 0; this.sortByDistance(objectsAtLeft, 'distance', true); this.sortByDistance(objectsAtRight, 'distance', true); const equallySpaced: Objects[] = []; let bounds: Rect; if (diagram.selectedObject.helperObject) { bounds = getBounds(diagram.selectedObject.helperObject.wrapper); } else { bounds = getBounds(shape.wrapper); } let nearestleft: Rect; let nearestright: Rect; let targetBounds: Rect; let equaldistance: number; if (objectsAtLeft.length > 0) { equallySpaced[equallySpaced.length] = objectsAtLeft[0]; nearestleft = ((objectsAtLeft[0].obj).bounds); top = nearestleft.y; if (objectsAtLeft.length > 1) { targetBounds = ((objectsAtLeft[1].obj).bounds); equaldistance = nearestleft.x - targetBounds.x - targetBounds.width; if (Math.abs(equaldistance - objectsAtLeft[0].distance) <= snapObjDistance) { top = this.findEquallySpacedNodesAtLeft(objectsAtLeft, equaldistance, top, equallySpaced); } else { equaldistance = objectsAtLeft[0].distance; } } else { equaldistance = objectsAtLeft[0].distance; } } this.sortByDistance(equallySpaced, 'distance'); equallySpaced[equallySpaced.length] = { obj: shape as DiagramElement, distance: 0 }; top = bounds.y < top || !top ? bounds.y : top; if (objectsAtRight.length > 0) { let dist: number; nearestright = ((objectsAtRight[0].obj).bounds); top = nearestright.y < top ? nearestright.y : top; if (objectsAtRight.length > 1) { targetBounds = ((objectsAtRight[1].obj).bounds); dist = targetBounds.x - nearestright.x - nearestright.width; } if (objectsAtLeft.length > 0) { if (Math.abs(objectsAtRight[0].distance - objectsAtLeft[0].distance) <= snapObjDistance) { const adjustablevalue: number = Math.abs(objectsAtRight[0].distance - objectsAtLeft[0].distance) / 2; (objectsAtRight[0].distance < objectsAtLeft[0].distance) ? equaldistance -= adjustablevalue : equaldistance += adjustablevalue; equallySpaced[equallySpaced.length] = objectsAtRight[0]; } else if (objectsAtLeft.length === 1) { nearestleft = undefined; equallySpaced.splice(0, 1); equallySpaced[equallySpaced.length] = objectsAtRight[0]; equaldistance = dist; } } else { equaldistance = dist; equallySpaced[equallySpaced.length] = objectsAtRight[0]; } if (objectsAtRight.length > 1 && nearestright.x + nearestright.width < targetBounds.x) { top = this.findEquallySpacedNodesAtRight(objectsAtRight, dist, top, equallySpaced, snapObjDistance); } } if (equallySpaced.length > 2) { this.addHSpacingLines(diagram, g, equallySpaced, ended, top); let deltaHorizontal: number = 0; if (ended) { deltaHorizontal = delta.x; } if (nearestleft) { horizontalSnap.offset = equaldistance - Math.abs(bounds.x + deltaHorizontal - nearestleft.x - nearestleft.width) + deltaHorizontal; } else if (nearestright) { horizontalSnap.offset = Math.abs(bounds.x + bounds.width + deltaHorizontal - nearestright.x) - equaldistance + deltaHorizontal; } horizontalSnap.snapped = true; } } //To create vertical spacing lines private createVSpacingLines( diagram: Diagram, g: SVGElement, shape: SelectorModel, objectsAtTop: Objects[], objectsAtBottom: Objects[], horizontalSnap: Snap, verticalSnap: Snap, ended: boolean, delta: PointModel, snapObjDistance: number): void { let right: number = 0; this.sortByDistance(objectsAtTop, 'distance', true); this.sortByDistance(objectsAtBottom, 'distance', true); const equallySpaced: Objects[] = []; let wrapper: Container; wrapper = this.getWrapperObject(shape, diagram.nameTable); const bounds: Rect = getBounds(wrapper); let nearesttop: Rect; let nearestbottom: Rect; let targetBounds: Rect; let equaldistance: number; if (objectsAtTop.length > 0) { equallySpaced[equallySpaced.length] = objectsAtTop[0]; nearesttop = ((objectsAtTop[0].obj).bounds); right = nearesttop.x + nearesttop.width; if (objectsAtTop.length > 1) { targetBounds = ((objectsAtTop[1].obj).bounds); equaldistance = nearesttop.y - targetBounds.y - targetBounds.height; if (Math.abs(equaldistance - objectsAtTop[0].distance) <= snapObjDistance) { right = this.findEquallySpacedNodesAtTop(objectsAtTop, equaldistance, right, equallySpaced); } else { equaldistance = objectsAtTop[0].distance; } } else { equaldistance = objectsAtTop[0].distance; } } this.sortByDistance(equallySpaced, 'distance'); equallySpaced[equallySpaced.length] = { obj: shape as DiagramElement, distance: 0 }; right = bounds.x + bounds.width > right || !right ? bounds.x + bounds.width : right; let dist: number; if (objectsAtBottom.length > 0) { nearestbottom = ((objectsAtBottom[0].obj).bounds); right = nearestbottom.x + nearestbottom.width > right ? nearestbottom.x + nearestbottom.width : right; if (objectsAtBottom.length > 1) { targetBounds = ((objectsAtBottom[1].obj).bounds); dist = targetBounds.y - nearestbottom.y - nearestbottom.height; } if (objectsAtTop.length > 0) { if (Math.abs(objectsAtBottom[0].distance - objectsAtTop[0].distance) <= snapObjDistance) { const adjustablevalue: number = Math.abs(objectsAtBottom[0].distance - objectsAtTop[0].distance) / 2; (objectsAtBottom[0].distance < objectsAtTop[0].distance) ? equaldistance -= adjustablevalue : equaldistance += adjustablevalue; equallySpaced[equallySpaced.length] = objectsAtBottom[0]; } else if (objectsAtTop.length === 1) { nearesttop = undefined; equallySpaced.splice(0, 1); equallySpaced[equallySpaced.length] = objectsAtBottom[0]; equaldistance = dist; } } else { equaldistance = dist; equallySpaced[equallySpaced.length] = objectsAtBottom[0]; } if (objectsAtBottom.length > 1 && targetBounds.y > nearestbottom.y + nearestbottom.height) { right = this.findEquallySpacedNodesAtBottom(objectsAtBottom, dist, right, equallySpaced, snapObjDistance); } } if (equallySpaced.length > 2) { this.addVSpacingLines(diagram, g, equallySpaced, ended, right); let deltaVertical: number = 0; if (ended) { deltaVertical = delta.y; } if (nearesttop) { verticalSnap.offset = equaldistance - Math.abs(bounds.y + deltaVertical - nearesttop.y - nearesttop.height) + deltaVertical; } else if (nearestbottom) { verticalSnap.offset = Math.abs(bounds.y + bounds.height + deltaVertical - nearestbottom.y) - equaldistance + deltaVertical; } verticalSnap.snapped = true; } } //Add the Horizontal spacing lines private addHSpacingLines(diagram: Diagram, g: SVGElement, equallySpaced: Objects[], ended: boolean, top: number): void { let i: number; let start: PointModel; let end: PointModel; if (!ended) { for (i = 0; i < equallySpaced.length - 1; i++) { const crnt: Rect = equallySpaced[i].obj instanceof Selector ? getBounds(((equallySpaced[i].obj) as SelectorModel).wrapper) : ((equallySpaced[i].obj).bounds); const next: Rect = equallySpaced[i + 1].obj instanceof Selector ? getBounds(((equallySpaced[i + 1].obj) as SelectorModel).wrapper) : ((equallySpaced[i + 1].obj).bounds); start = { x: crnt.x + crnt.width, y: top - 15 }; end = { x: next.x, y: top - 15 }; this.renderSpacingLines( start, end, g, this.getAdornerLayerSvg(), diagram.scroller.transform); } } } //Add the vertical spacing lines private addVSpacingLines(diagram: Diagram, g: SVGElement, equallySpacedObjects: Objects[], ended: boolean, right: number): void { let start: PointModel; let end: PointModel; if (!ended) { for (let i: number = 0; i < equallySpacedObjects.length - 1; i++) { const crnt: Rect = equallySpacedObjects[i].obj instanceof Selector ? getBounds(((equallySpacedObjects[i].obj) as SelectorModel).wrapper) : ((equallySpacedObjects[i].obj).bounds); const next: Rect = equallySpacedObjects[i + 1].obj instanceof Selector ? getBounds(((equallySpacedObjects[i + 1].obj) as SelectorModel).wrapper) : ((equallySpacedObjects[i + 1].obj).bounds); start = { x: right + 15, y: crnt.y + crnt.height }; end = { x: right + 15, y: next.y }; this.renderSpacingLines( start, end, g, this.getAdornerLayerSvg(), diagram.scroller.transform); } } } //To add same width lines private addSameWidthLines( diagram: Diagram, snapLine: SVGElement, sameWidths: SnapSize[], horizontalSnap: Snap, ended: boolean, shape: SelectorModel): void { this.sortByDistance(sameWidths, 'offset'); let bounds: Rect = getBounds(shape.wrapper); const target: SnapSize = sameWidths[0]; let startPt: PointModel; let endPt: PointModel; const targetBounds: Rect = ((target.source) as DiagramElement).bounds; const sameSizes: SnapSize[] = []; sameSizes.push(sameWidths[0]); let i: number; let crntbounds: Rect; for (i = 1; i < sameWidths.length; i++) { crntbounds = ((sameWidths[i].source) as DiagramElement).bounds; if (crntbounds.width === targetBounds.width) { sameSizes.push(sameWidths[i]); } } if (!ended) { startPt = { x: bounds.x + target.offset, y: bounds.y - 15 }; endPt = { x: bounds.x + bounds.width + target.offset, y: bounds.y - 15 }; this.renderSpacingLines( startPt, endPt, snapLine, this.getAdornerLayerSvg(), diagram.scroller.transform); for (i = 0; i < sameSizes.length; i++) { bounds = ((sameSizes[i].source) as DiagramElement).bounds; startPt = { x: bounds.x, y: bounds.y - 15 }; endPt = { x: bounds.x + bounds.width, y: bounds.y - 15 }; this.renderSpacingLines( startPt, endPt, snapLine, this.getAdornerLayerSvg(), diagram.scroller.transform); } } horizontalSnap.offset = target.offset; horizontalSnap.snapped = true; } //To add same height lines private addSameHeightLines( diagram: Diagram, snapLine: SVGElement, sameHeights: SnapSize[], verticalSnap: Snap, ended: boolean, shape: SelectorModel): void { this.sortByDistance(sameHeights, 'offset'); let bounds: Rect = getBounds(shape.wrapper); const target: SnapSize = sameHeights[0]; const targetBounds: Rect = ((target.source) as DiagramElement).bounds; let start: PointModel; let end: PointModel; const sameSizes: SnapSize[] = []; sameSizes.push(sameHeights[0]); let i: number; let crntbounds: Rect; for (i = 0; i < sameHeights.length; i++) { crntbounds = ((sameHeights[i].source) as DiagramElement).bounds; if (crntbounds.height === targetBounds.height) { sameSizes.push(sameHeights[i]); } } if (!ended) { start = { x: bounds.x + bounds.width + 15, y: bounds.y + target.offset }; end = { x: bounds.x + bounds.width + 15, y: bounds.y + target.offset + bounds.height }; this.renderSpacingLines( start, end, snapLine, this.getAdornerLayerSvg(), diagram.scroller.transform); for (i = 0; i < sameSizes.length; i++) { bounds = ((sameSizes[i].source) as DiagramElement).bounds; start = { x: bounds.x + bounds.width + 15, y: bounds.y }; end = { x: bounds.x + bounds.width + 15, y: bounds.y + bounds.height }; this.renderSpacingLines( start, end, snapLine, this.getAdornerLayerSvg(), diagram.scroller.transform); } } verticalSnap.offset = target.offset; verticalSnap.snapped = true; } //Render spacing lines private renderSpacingLines( start: PointModel, end: PointModel, snapLine: SVGElement, svg: HTMLCanvasElement | SVGElement, transform: TransformFactor): void { let d: string; let d1: string; let line1: LineAttributes; const element: PathElement = new PathElement(); const options: PathAttributes = {} as PathAttributes; start = { x: (start.x + transform.tx) * transform.scale, y: (start.y + transform.ty) * transform.scale }; end = { x: (end.x + transform.tx) * transform.scale, y: (end.y + transform.ty) * transform.scale }; if (start.x === end.x) { d = 'M' + (start.x - 5) + ' ' + (start.y + 5) + 'L' + start.x + ' ' + start.y + 'L' + (start.x + 5) + ' ' + (start.y + 5) + 'z' + 'M' + (end.x - 5) + ' ' + (end.y - 5) + ' L' + end.x + ' ' + end.y + ' L' + (end.x + 5) + ' ' + (end.y - 5) + 'z'; line1 = { startPoint: { x: start.x - 8, y: start.y - 1 }, endPoint: { x: start.x + 8, y: start.y - 1 }, stroke: this.setSnapLineColor(), strokeWidth: 1, fill: this.setSnapLineColor(), dashArray: '', width: 1, x: 0, y: 0, height: 0, angle: 0, pivotX: 0, pivotY: 0, visible: true, opacity: 1, id: randomId() }; element.data = d; options.data = element.data; options.angle = 0; options.pivotX = 0; options.pivotY = 0; options.x = 0; options.y = 0; options.height = 0; options.width = 1; options.id = randomId(); this.diagram.diagramRenderer.drawPath(snapLine, options as PathAttributes); this.line.push(line1); this.diagram.diagramRenderer.drawLine(snapLine, this.line.pop()); line1 = { startPoint: { x: end.x - 8, y: end.y + 1 }, endPoint: { x: end.x + 8, y: end.y + 1 }, stroke:this.setSnapLineColor(), strokeWidth: 1, fill: this.setSnapLineColor(), dashArray: '', width: 1, x: 0, y: 0, height: 0, angle: 0, pivotX: 0, pivotY: 0, visible: true, opacity: 1, id: this.getAdornerLayerSvg().id + 'spacing' }; this.line.push(line1); this.diagram.diagramRenderer.drawLine(snapLine, this.line.pop()); } else { d = 'M' + (start.x + 5) + ' ' + (start.y + 5) + ' L' + start.x + ' ' + start.y + ' L' + (start.x + 5) + ' ' + (start.y - 5) + 'z' + 'M' + (end.x - 5) + ' ' + (end.y - 5) + ' L' + end.x + ' ' + end.y + ' L' + (end.x - 5) + ' ' + (end.y + 5) + 'z'; element.data = d; options.data = d; options.angle = 0; options.pivotX = 0; options.pivotY = 0; options.x = 0; options.y = 0; options.height = 0; options.width = 1; options.id = randomId(); this.diagram.diagramRenderer.drawPath(snapLine, options); line1 = { visible: true, opacity: 1, id: randomId(), startPoint: { x: start.x - 1, y: start.y - 8 }, endPoint: { x: start.x - 1, y: start.y + 8 }, stroke: this.setSnapLineColor(), strokeWidth: 1, fill: this.setSnapLineColor(), dashArray: '0', width: 1, x: 0, y: 0, height: 0, angle: 0, pivotX: 0, pivotY: 0 }; this.line.push(line1); this.diagram.diagramRenderer.drawLine(snapLine, this.line.pop()); line1 = { width: 1, x: 0, y: 0, height: 0, angle: 0, pivotX: 0, pivotY: 0, visible: true, opacity: 1, id: randomId(), startPoint: { x: end.x + 1, y: end.y - 8 }, endPoint: { x: end.x + 1, y: end.y + 8 }, stroke: this.setSnapLineColor(), strokeWidth: 1, fill: this.setSnapLineColor(), dashArray: '0' }; this.line.push(line1); this.diagram.diagramRenderer.drawLine(snapLine, this.line.pop()); } line1 = { startPoint: { x: start.x, y: start.y }, endPoint: { x: end.x, y: end.y }, stroke: this.setSnapLineColor(), strokeWidth: 1, fill:this.setSnapLineColor(), dashArray: '0', width: 1, x: 0, y: 0, height: 0, angle: 0, pivotX: 0, pivotY: 0, visible: true, opacity: 1, id: randomId() }; this.line.push(line1); this.diagram.diagramRenderer.drawLine(snapLine, this.line.pop()); } /** * To Create Snap object with position, initial bounds, and final bounds \ * * @returns { void } To Create Snap object with position, initial bounds, and final bounds .\ * @param {Diagram} targetBounds - provide the targetBounds value. * @param {Rect} bounds - provide the angle value. * @param {string} snap - provide the angle value. * @private */ public createSnapObject(targetBounds: Rect, bounds: Rect, snap: string): SnapObject { let snapObject: SnapObject; switch (snap) { case 'left': snapObject = { start: { x: (targetBounds.x), y: Math.min(targetBounds.y, bounds.y) }, end: { x: (targetBounds.x), y: Math.max(targetBounds.y + targetBounds.height, bounds.y + bounds.height) }, offsetX: targetBounds.x - bounds.x, offsetY: 0, type: 'sideAlign' }; break; case 'right': snapObject = { type: 'sideAlign', start: { x: (targetBounds.x + targetBounds.width), y: Math.min(targetBounds.y, bounds.y) }, offsetX: targetBounds.x + targetBounds.width - bounds.x - bounds.width, offsetY: 0, end: { x: (targetBounds.x + targetBounds.width), y: Math.max(targetBounds.y + targetBounds.height, bounds.y + bounds.height) } }; break; case 'top': snapObject = { offsetY: targetBounds.y - bounds.y, offsetX: 0, type: 'sideAlign', start: { x: (Math.min(targetBounds.x, bounds.x)), y: targetBounds.y }, end: { x: (Math.max(targetBounds.x + targetBounds.width, bounds.x + bounds.width)), y: targetBounds.y } }; break; case 'bottom': snapObject = { type: 'sideAlign', offsetY: targetBounds.y + targetBounds.height - bounds.y - bounds.height, offsetX: 0, end: { x: (Math.max(targetBounds.x + targetBounds.width, bounds.x + bounds.width)), y: targetBounds.y + targetBounds.height }, start: { x: (Math.min(targetBounds.x, bounds.x)), y: targetBounds.y + targetBounds.height } }; break; case 'topBottom': snapObject = { start: { x: (Math.min(targetBounds.x, bounds.x)), y: targetBounds.y + targetBounds.height }, end: { x: (Math.max(targetBounds.x + targetBounds.width, bounds.x + bounds.width)), y: targetBounds.y + targetBounds.height }, offsetY: targetBounds.y + targetBounds.height - bounds.y, offsetX: 0, type: 'sideAlign' }; break; case 'bottomTop': snapObject = { start: { x: (Math.min(targetBounds.x, bounds.x)), y: targetBounds.y }, end: { x: (Math.max(targetBounds.x + targetBounds.width, bounds.x + bounds.width)), y: targetBounds.y }, offsetY: targetBounds.y - bounds.y - bounds.height, offsetX: 0, type: 'sideAlign' }; break; case 'leftRight': snapObject = { start: { x: (targetBounds.x + targetBounds.width), y: Math.min(targetBounds.y, bounds.y) }, end: { x: (targetBounds.x + targetBounds.width), y: Math.max(targetBounds.y + targetBounds.height, bounds.y + bounds.height) }, offsetX: targetBounds.x + targetBounds.width - bounds.x, offsetY: 0, type: 'sideAlign' }; break; case 'rightLeft': snapObject = { start: { x: (targetBounds.x), y: (Math.min(targetBounds.y, bounds.y)) }, end: { x: (targetBounds.x), y: Math.max(targetBounds.y + targetBounds.height, bounds.y + bounds.height) }, offsetX: targetBounds.x - bounds.x - bounds.width, offsetY: 0, type: 'sideAlign' }; break; case 'centerX': snapObject = { start: { x: (targetBounds.x + targetBounds.width / 2), y: (Math.min(targetBounds.y, bounds.y)) }, end: { x: (targetBounds.x + targetBounds.width / 2), y: Math.max(targetBounds.y + targetBounds.height, bounds.y + bounds.height) }, offsetX: targetBounds.x + targetBounds.width / 2 - (bounds.x + bounds.width / 2), offsetY: 0, type: 'centerAlign' }; break; case 'centerY': snapObject = { start: { x: (Math.min(targetBounds.x, bounds.x)), y: targetBounds.y + targetBounds.height / 2 }, end: { x: (Math.max(targetBounds.x + targetBounds.width, bounds.x + bounds.width)), y: targetBounds.y + targetBounds.height / 2 }, offsetY: targetBounds.y + targetBounds.height / 2 - (bounds.y + bounds.height / 2), offsetX: 0, type: 'centerAlign' }; break; } return snapObject; } /** * Calculate the snap angle \ * * @returns { void } Calculate the snap angle .\ * @param {Diagram} diagram - provide the diagram value. * @param {number} angle - provide the angle value. * @private */ public snapAngle(diagram: Diagram, angle: number): number { const snapSettings: SnapSettingsModel = this.diagram.snapSettings; const snapAngle: number = snapSettings.snapAngle; const width: number = angle % (snapAngle || 0); if (width >= (snapAngle / 2)) { return angle + snapAngle - width; } else { return angle - width; } } //Check whether the node to be snapped or not. private canConsider(nameTable: NodeModel, selectedObject: SelectorModel, target: DiagramElement): boolean { const consider: boolean = false; if (this.diagram.selectedItems.nodes.length && this.diagram.selectedItems.nodes[0].id === (target as NodeModel).id) { return false; } else { return true; } } //Find the total number of nodes in diagram using SpatialSearch private findNodes( spatialSearch: SpatialSearch, node: SelectorModel, child: Rect, viewPort?: Rect, nodesInView?: DiagramElement[]): DiagramElement[] { const nodes: DiagramElement[] = []; let nd: DiagramElement; let bounds: Rect; const quads: Quad[] = spatialSearch.findQuads(nodesInView ? viewPort : child); for (let i: number = 0; i < quads.length; i++) { const quad: Quad = quads[i]; if (quad.objects.length > 0) { for (let j: number = 0; j < quad.objects.length; j++) { nd = quad.objects[j] as DiagramElement; if (!(this.diagram.nameTable[nd.id] instanceof Connector) && nd.visible && !(this.diagram.nameTable[nd.id].shape.type === 'SwimLane') && !(this.diagram.nameTable[nd.id].isLane) && !(this.diagram.nameTable[nd.id].isPhase) && !(this.diagram.nameTable[nd.id].isHeader) && nd.id != 'helper') { bounds = getBounds(nd); if (nodes.indexOf(nd) === -1 && this.intersectsRect(child, bounds)) { nodes.push(nd); } if (nodesInView && nodesInView.indexOf(nd) && this.intersectsRect(viewPort, bounds)) { nodesInView.push(nd); } } } } } return nodes; } private intersectsRect(child: Rect, bounds: Rect): boolean { return ((((bounds.x < (child.x + child.width)) && (child.x < (bounds.x + bounds.width))) && (bounds.y < (child.y + child.height))) && (child.y < (bounds.y + bounds.height))); } private getAdornerLayerSvg(): SVGSVGElement { return this.diagram.diagramRenderer.adornerSvgLayer; } /** * To remove grid lines on mouse move and mouse up \ * * @returns { void } To remove grid lines on mouse move and mouse up .\ * @param {Diagram} diagram - provide the source value. * @private */ public removeGuidelines(diagram: Diagram): void { const selectionRect: SVGElement = (this.getAdornerLayerSvg() as SVGSVGElement).getElementById('_SnappingLines') as SVGElement; const line: SVGElement = (this.getAdornerLayerSvg() as SVGSVGElement).getElementById('pivotLine') as SVGElement; if (selectionRect) { selectionRect.parentNode.removeChild(selectionRect); } if (line) { line.parentNode.removeChild(line); } } //Sort the objects by its distance private sortByDistance(obj: (Objects | SnapSize)[], value: string, ascending?: boolean): void { let i: number; let j: number; let temp: (Objects | SnapSize); if (ascending) { for (i = 0; i < obj.length; i++) { for (j = i + 1; j < obj.length; j++) { if (obj[i][value] > obj[j][value]) { temp = obj[i]; obj[i] = obj[j]; obj[j] = temp; } } } } else { for (i = 0; i < obj.length; i++) { for (j = i + 1; j < obj.length; j++) { if (obj[i][value] < obj[j][value]) { temp = obj[i]; obj[i] = obj[j]; obj[j] = temp; } } } } } //To find nodes that are equally placed at left of the selected node private findEquallySpacedNodesAtLeft(objectsAtLeft: Objects[], equalDistance: number, top: number, equallySpaced: Objects[]): number { let prevBounds: Rect; let targetBounds: Rect; let dist: number; let i: number; for (i = 1; i < objectsAtLeft.length; i++) { prevBounds = ((objectsAtLeft[i - 1].obj).bounds); targetBounds = ((objectsAtLeft[i].obj).bounds); dist = prevBounds.x - targetBounds.x - targetBounds.width; if (Math.abs(dist - equalDistance) <= 1) { equallySpaced[equallySpaced.length] = objectsAtLeft[i]; if (targetBounds.y < top) { top = targetBounds.y; } } else { break; } } return top; } //To find nodes that are equally placed at right of the selected node private findEquallySpacedNodesAtRight( objectsAtRight: Objects[], equalDistance: number, top: number, equallySpaced: Objects[], snapObjDistance: number): number { const actualDistance: number = objectsAtRight[0].distance; let target: DiagramElement; let targetBounds: Rect; let prevBounds: Rect; let dist: number; if (Math.abs(equalDistance - actualDistance) <= snapObjDistance) { for (let i: number = 0; i < objectsAtRight.length - 1; i++) { target = objectsAtRight[i].obj; targetBounds = ((objectsAtRight[i + 1].obj).bounds); prevBounds = (target.bounds); dist = targetBounds.x - prevBounds.x - prevBounds.width; if (Math.abs(dist - equalDistance) <= 1) { equallySpaced[equallySpaced.length] = objectsAtRight[i + 1]; if (prevBounds.y < top) { top = prevBounds.y; } } else { break; } } } return top; } private findEquallySpacedNodesAtTop(objectsAtTop: Objects[], equalDistance: number, right: number, equallySpaced: Objects[]): number { let prevBounds: Rect; let targetBounds: Rect; let dist: number; for (let i: number = 1; i < objectsAtTop.length; i++) { prevBounds = ((objectsAtTop[i - 1].obj).bounds); targetBounds = ((objectsAtTop[i].obj).bounds); dist = prevBounds.y - targetBounds.y - targetBounds.height; if (Math.abs(dist - equalDistance) <= 1) { equallySpaced[equallySpaced.length] = objectsAtTop[i]; if (targetBounds.x + targetBounds.width > right) { right = targetBounds.x + targetBounds.width; } } else { break; } } return right; } //To find nodes that are equally placed at bottom of the selected node private findEquallySpacedNodesAtBottom( objectsAtBottom: Objects[], equalDistance: number, right: number, equallySpaced: Objects[], snapObjDistance: number): number { const actualDistance: number = objectsAtBottom[0].distance; let target: DiagramElement; let targetBounds: Rect; let prevBounds: Rect; let dist: number; if (Math.abs(equalDistance - actualDistance) <= snapObjDistance) { for (let i: number = 0; i < objectsAtBottom.length - 1; i++) { target = objectsAtBottom[i].obj; targetBounds = ((objectsAtBottom[i + 1].obj).bounds); prevBounds = (target.bounds); dist = targetBounds.y - prevBounds.y - prevBounds.height; if (Math.abs(dist - equalDistance) <= 1) { equallySpaced[equallySpaced.length] = objectsAtBottom[i + 1]; if (prevBounds.x + prevBounds.width > right) { right = prevBounds.x + prevBounds.width; } } else { break; } } } return right; } /** * To get Adoner layer to draw snapLine * * @private */ public getLayer(): SVGElement { let snapLine: SVGElement; if (this.diagram.snapSettings.constraints & SnapConstraints.SnapToObject) { snapLine = document.createElementNS('http://www.w3.org/2000/svg', 'g'); snapLine.setAttribute('id', '_SnappingLines'); snapLine.setAttribute('shapeRendering', 'crispEdges'); this.getAdornerLayerSvg().appendChild(snapLine); } return snapLine; } /** * Constructor for the snapping module * * @private */ // constructor() { // //constructs the snapping module // } /** *To destroy the ruler * * @returns {void} To destroy the ruler */ public destroy(): void { /** * Destroys the snapping module */ } /** * Core method to return the component name. * * @returns {string} Core method to return the component name. * @private */ protected getModuleName(): string { /** * Returns the module name */ return 'Snapping'; } } export interface Snap { snapped: boolean; offset: number; left?: boolean; bottom?: boolean; right?: boolean; top?: boolean; } /** * @private */ export interface SnapObject { start: PointModel; end: PointModel; offsetX: number; offsetY: number; type: string; } /** * @private */ export interface Objects { obj: DiagramElement; distance: number; } /** * @private */ export interface SnapSize { source: NodeModel; difference: number; offset: number; }
the_stack
import { equals } from "../../../Data/Eq" import { flip, thrush } from "../../../Data/Function" import { fmap } from "../../../Data/Functor" import { set } from "../../../Data/Lens" import { append, appendStr, elem, filter, find, flength, groupByKey, intercalate, List, map, replaceStr, subscriptF } from "../../../Data/List" import { altF_, any, bind, bindF, catMaybes, elemF, ensure, fromJust, fromMaybe, isJust, isNothing, Just, liftM2, listToMaybe, maybe, Maybe, Nothing, thenF } from "../../../Data/Maybe" import { elems, lookup, lookupF, OrderedMap, sdelete } from "../../../Data/OrderedMap" import { Record } from "../../../Data/Record" import { AdvantageId as AdvantageIdEnum, DisadvantageId as DisadvantageIdEnum, SpecialAbilityId as SpecialAbilityIdEnum } from "../../Constants/Ids" import { AdvantageId, DisadvantageId, SpecialAbilityId } from "../../Constants/Ids.gen" import { ActiveObjectWithId } from "../../Models/ActiveEntries/ActiveObjectWithId" import { ActivatableCombinedName, ActivatableCombinedNameL } from "../../Models/View/ActivatableCombinedName" import { ActivatableNameCostSafeCostL } from "../../Models/View/ActivatableNameCost" import { ActiveActivatable, ActiveActivatableA_, ActiveActivatableL } from "../../Models/View/ActiveActivatable" import { Advantage } from "../../Models/Wiki/Advantage" import { Skill } from "../../Models/Wiki/Skill" import { Application } from "../../Models/Wiki/sub/Application" import { SelectOption } from "../../Models/Wiki/sub/SelectOption" import { StaticData, StaticDataRecord } from "../../Models/Wiki/WikiModel" import { Activatable, ActivatableSkillEntry, EntryWithCategory, SID, SkillishEntry } from "../../Models/Wiki/wikiTypeHelpers" import { mdash } from "../Chars" import { composeL } from "../compose" import { formatList, translate } from "../I18n" import { prefixSA } from "../IDUtils" import { ifElse } from "../ifElse" import { toRoman } from "../NumberUtils" import { pipe, pipe_ } from "../pipe" import { sortStrings } from "../sortBy" import { isNumber, isString, misStringM } from "../typeCheckUtils" import { getWikiEntry, isActivatableWikiEntry, isSkillishWikiEntry } from "../WikiUtils" import { findSelectOption, getSelectOptionName } from "./selectionUtils" const SDA = StaticData.A const AOWIA = ActiveObjectWithId.A const AAA_ = ActiveActivatableA_ const AAL = Advantage.AL const SA = Skill.A const SAL = Skill.AL const SOA = SelectOption.A const AA = Application.A /** * Returns the name of the given object. If the object is a string, it returns * the string. */ export const getFullName = (obj: string | Record<ActiveActivatable>): string => { if (typeof obj === "string") { return obj } return AAA_.name (obj) } /** * Accepts the full special ability name and returns only the text between * parentheses. If no parentheses were found, returns an empty string. */ export const getBracketedNameFromFullName = (full_name: string): string => { const result = /\((?<subname>.+)\)/u .exec (full_name) if (result === null || result .groups === undefined) { return "" } return result .groups .subname } /** * A lot of entries have customization options: Text input, select option or * both. This function creates a string that can be appended to the `name` * property of the respective record to create the full active name. */ const getEntrySpecificNameAddition = (staticData: StaticDataRecord) => (wiki_entry: Activatable) => (hero_entry: Record<ActiveObjectWithId>): Maybe<string> => { switch (AOWIA.id (hero_entry)) { // Entry with Skill selection (string id) case AdvantageId.aptitude: case AdvantageId.exceptionalSkill: case AdvantageId.exceptionalCombatTechnique: case AdvantageId.weaponAptitude: case DisadvantageId.incompetent: case SpecialAbilityId.adaptionZauber: case SpecialAbilityId.favoriteSpellwork: case SpecialAbilityId.forschungsgebiet: case SpecialAbilityId.expertenwissen: case SpecialAbilityId.wissensdurst: case SpecialAbilityId.recherchegespuer: case SpecialAbilityId.lieblingsliturgie: return pipe ( AOWIA.sid, misStringM, bindF (getWikiEntry (staticData)), bindF<EntryWithCategory, SkillishEntry> (ensure (isSkillishWikiEntry)), fmap (SAL.name) ) (hero_entry) case AdvantageId.hatredOf: return pipe ( AOWIA.sid, findSelectOption (wiki_entry), liftM2 ((type: string | number) => (frequency: Record<SelectOption>) => `${type} (${SOA.name (frequency)})`) (AOWIA.sid2 (hero_entry)) ) (hero_entry) case DisadvantageId.personalityFlaw: return pipe ( AOWIA.sid, getSelectOptionName (wiki_entry), fmap ((option_name: string) => maybe (option_name) // if there is additional input, add to name ((specialInput: string | number) => `${option_name}: ${specialInput}`) (pipe ( AOWIA.sid, // Check if the select option allows // additional input bindF<SID, number> ( ensure ( (x): x is number => isNumber (x) && elem (x) (List (7, 8)) ) ), bindF (() => AOWIA.sid2 (hero_entry)) ) (hero_entry))) ) (hero_entry) case SpecialAbilityId.skillSpecialization: return pipe ( AOWIA.sid, misStringM, bindF (lookupF (SDA.skills (staticData))), bindF (skill => pipe ( AOWIA.sid2, // If input string use input misStringM, // Otherwise lookup application name altF_ (() => pipe ( SA.applications, find<Record<Application>> (pipe ( Application.AL.id, elemF (AOWIA.sid2 (hero_entry)) )), fmap (AA.name) ) (skill)), // Merge skill name and application name fmap (appl => `${SA.name (skill)}: ${appl}`) ) (hero_entry)) ) (hero_entry) case SpecialAbilityId.exorzist: return pipe_ ( hero_entry, AOWIA.tier, Maybe.product, ensure (equals (1)), thenF (AOWIA.sid (hero_entry)), findSelectOption (wiki_entry), fmap (SOA.name) ) case prefixSA (SpecialAbilityId.spellEnhancement): case prefixSA (SpecialAbilityId.chantEnhancement): return pipe ( AOWIA.sid, findSelectOption (wiki_entry), bindF (ext => pipe ( bindF ((target_id: string) => { const acc = AOWIA.id (hero_entry) === prefixSA (SpecialAbilityId.spellEnhancement) ? SDA.spells : SDA.liturgicalChants return lookupF<string, ActivatableSkillEntry> (acc (staticData)) (target_id) }), fmap ( (target_entry: ActivatableSkillEntry) => `${SAL.name (target_entry)}: ${SOA.name (ext)}` ) ) (SOA.target (ext))) ) (hero_entry) case SpecialAbilityId.traditionSavant: return pipe ( AOWIA.sid, misStringM, bindF (lookupF (SDA.skills (staticData))), fmap (SA.name) ) (hero_entry) case SpecialAbilityId.languageSpecializations: return pipe ( SDA.specialAbilities, lookup<string> (SpecialAbilityId.language), bindF (pipe ( findSelectOption, thrush (AOWIA.sid (hero_entry)) )), bindF (lang => pipe ( AOWIA.sid2, bindF ( ifElse<string | number, string> (isString) <Maybe<string>> (Just) (spec_id => bind (SOA.specializations (lang)) (subscriptF (spec_id - 1))) ), fmap (spec => `${SOA.name (lang)}: ${spec}`) ) (hero_entry)) ) (staticData) case SpecialAbilityId.fachwissen: { const getApp = (getSid: (r: Record<ActiveObjectWithId>) => Maybe<string | number>) => pipe ( SA.applications, filter (pipe (AA.prerequisite, isNothing)), find (pipe (AA.id, elemF (getSid (hero_entry)))), fmap (AA.name) ) return pipe_ ( hero_entry, AOWIA.sid, misStringM, bindF (lookupF (SDA.skills (staticData))), bindF (skill => pipe_ ( List ( getApp (AOWIA.sid2) (skill), getApp (AOWIA.sid3) (skill) ), catMaybes, ensure (xs => flength (xs) === 2), fmap (pipe ( sortStrings (staticData), formatList ("conjunction") (staticData), apps => `${SA.name (skill)}: ${apps}` )) )) ) } case SpecialAbilityId.handwerkskunst: case SpecialAbilityId.kindDerNatur: case SpecialAbilityId.koerperlichesGeschick: case SpecialAbilityId.sozialeKompetenz: case SpecialAbilityId.universalgenie: { return pipe_ ( List (AOWIA.sid (hero_entry), AOWIA.sid2 (hero_entry), AOWIA.sid3 (hero_entry)), map (getSelectOptionName (wiki_entry)), catMaybes, sortStrings (staticData), intercalate (", "), Just ) } default: { const current_sid = AOWIA.sid (hero_entry) const current_sid2 = AOWIA.sid2 (hero_entry) // Text input if (isJust (AAL.input (wiki_entry)) && any (isString) (current_sid)) { return current_sid } // Select option and text input if (isJust (AAL.select (wiki_entry)) && isJust (AAL.input (wiki_entry)) && isJust (current_sid) && any (isString) (current_sid2)) { const name1 = fromMaybe ("") (getSelectOptionName (wiki_entry) (current_sid)) const name2 = fromJust (current_sid2) return Just (`${name1}: ${name2}`) } // Plain select option if (isJust (AAL.select (wiki_entry))) { return getSelectOptionName (wiki_entry) (current_sid) } return Nothing } } } const addSndinParenthesis = (snd: string) => replaceStr (")") (`: ${snd})`) /** * Some entries cannot use the default `name` property from wiki entries. The * value returned by may not use the default `name` property. For all entries * that do not need to handle a specific display format, the default `name` * property is used. */ const getEntrySpecificNameReplacements = (staticData: StaticDataRecord) => (wiki_entry: Activatable) => (hero_entry: Record<ActiveObjectWithId>) => (mname_add: Maybe<string>): string => { const def = fromMaybe (AAL.name (wiki_entry)) const maybeMap = (f: (x: string) => string) => maybe (AAL.name (wiki_entry)) (f) (mname_add) switch (AAL.id (wiki_entry)) { case AdvantageId.immunityToPoison: case AdvantageId.immunityToDisease: return maybeMap ( name_add => `${translate (staticData) ("advantagesdisadvantages.immunityto")} ${name_add}` ) case AdvantageId.hatredOf: return maybeMap ( name_add => `${translate (staticData) ("advantagesdisadvantages.hatredfor")} ${name_add}` ) case DisadvantageId.afraidOf: return maybeMap ( name_add => `${translate (staticData) ("advantagesdisadvantages.afraidof")} ${name_add}` ) case DisadvantageId.principles: case DisadvantageId.obligations: return def (liftM2 ((level: number) => (name_add: string) => `${AAL.name (wiki_entry)} ${toRoman (level)} (${name_add})`) (AOWIA.tier (hero_entry)) (mname_add)) case SpecialAbilityId.gebieterDesAspekts: return maybeMap (name_add => `${AAL.name (wiki_entry)} ${name_add}`) case SpecialAbilityId.traditionArcaneBard: case SpecialAbilityId.traditionArcaneDancer: case SpecialAbilityId.traditionSavant: { return maybeMap (flip (addSndinParenthesis) (AAL.name (wiki_entry))) } default: return maybeMap (name_add => `${AAL.name (wiki_entry)} (${name_add})`) } } /** * Returns name, splitted and combined, of advantage/disadvantage/special * ability as a Maybe (in case the wiki entry does not exist). * @param instance The ActiveObject with origin id. * @param wiki The current hero's state. * @param l10n The locale-dependent messages. */ export const getName = (staticData: StaticDataRecord) => (hero_entry: Record<ActiveObjectWithId>): Maybe<Record<ActivatableCombinedName>> => pipe ( AOWIA.id, getWikiEntry (staticData), bindF<EntryWithCategory, Activatable> (ensure (isActivatableWikiEntry)), fmap ((wiki_entry: Activatable) => { const maddName = getEntrySpecificNameAddition (staticData) (wiki_entry) (hero_entry) const fullName = getEntrySpecificNameReplacements (staticData) (wiki_entry) (hero_entry) (maddName) return ActivatableCombinedName ({ name: fullName, baseName: AAL.name (wiki_entry), addName: maddName, }) }) ) (hero_entry) const extractCustom = ( id: string, groupedEntries: OrderedMap<string, List<Record<ActiveActivatable>>> ) => pipe_ ( groupedEntries, lookup (id), maybe (List<List<Record<ActiveActivatable>>> ()) (map (active => List (set (composeL ( ActiveActivatableL.nameAndCost, ActivatableNameCostSafeCostL.naming, ActivatableCombinedNameL.name )) (fromMaybe (mdash) (AAA_.addName (active))) (active)))) ) /** * `compressList :: L10n -> [ActiveActivatable] -> String` * * Takes a list of active Activatables and merges them together. Used to display * lists of Activatables on character sheet. */ export const compressList = (staticData: StaticDataRecord) => (xs: List<Record<ActiveActivatable>>): string => { const groupedEntries = groupByKey<Record<ActiveActivatable>, string> (AAA_.id) (xs) const customAdvantages = extractCustom (AdvantageIdEnum.CustomAdvantage, groupedEntries) const customDisadvantages = extractCustom (DisadvantageIdEnum.CustomDisadvantage, groupedEntries) const customSpecialAbilities = extractCustom (SpecialAbilityIdEnum.CustomSpecialAbility, groupedEntries) const grouped_xs = pipe_ ( groupedEntries, sdelete <string> (AdvantageIdEnum.CustomAdvantage), sdelete <string> (DisadvantageIdEnum.CustomDisadvantage), sdelete <string> (SpecialAbilityIdEnum.CustomSpecialAbility), elems, append (customAdvantages), append (customDisadvantages), append (customSpecialAbilities), ) return pipe ( map ( ifElse<List<Record<ActiveActivatable>>> (xs_group => flength (xs_group) === 1) (pipe (listToMaybe, maybe ("") (AAA_.name))) (xs_group => pipe ( map ((x: Record<ActiveActivatable>) => { const levelPart = pipe ( AAA_.level, fmap (pipe (toRoman, appendStr (" "))), fromMaybe ("") ) (x) const selectOptionPart = fromMaybe ("") (AAA_.addName (x)) return selectOptionPart + levelPart }), sortStrings (staticData), intercalate (", "), x => ` (${x})`, x => maybe ("") ((r: Record<ActiveActivatable>) => AAA_.baseName (r) + x) (listToMaybe (xs_group)) ) (xs_group)) ), sortStrings (staticData), intercalate (", ") ) (grouped_xs) }
the_stack
import {DebugProtocol} from "vscode-debugprotocol"; import { Breakpoint, InitializedEvent, LoggingDebugSession, Scope, StackFrame, Source, Thread, OutputEvent, TerminatedEvent, StoppedEvent, Variable, Handles, ThreadEvent } from "vscode-debugadapter"; import * as childProcess from "child_process"; import * as path from "path"; import * as fs from "fs"; import {Message} from "./message"; import {LaunchConfig, isCustomProgramConfig} from "./launchConfig"; interface MessageHandler<T extends LuaDebug.Message = LuaDebug.Message> { (msg: T): void; } const enum ScopeType { Local = 1, Upvalue, Global } const enum OutputCategory { StdOut = "stdout", StdErr = "stderr", Command = "command", Request = "request", // eslint-disable-next-line @typescript-eslint/no-shadow Message = "message", Info = "info", Error = "error" } // const mainThreadId = 1; const maxStackCount = 100; const metatableDisplayName = "[[metatable]]"; const tableLengthDisplayName = "[[length]]"; const envVariable = "LOCAL_LUA_DEBUGGER_VSCODE"; const filePathEnvVariable = "LOCAL_LUA_DEBUGGER_FILEPATH"; const scriptRootsEnvVariable: LuaDebug.ScriptRootsEnv = "LOCAL_LUA_DEBUGGER_SCRIPT_ROOTS"; const breakInCoroutinesEnv: LuaDebug.BreakInCoroutinesEnv = "LOCAL_LUA_DEBUGGER_BREAK_IN_COROUTINES"; function getEnvKey(env: NodeJS.ProcessEnv, searchKey: string) { const upperSearchKey = searchKey.toUpperCase(); for (const key in env) { if (key.toUpperCase() === upperSearchKey) { return key; } } return searchKey; } function sortVariables(a: Variable, b: Variable): number { const aIsBracketted = a.name.startsWith("[["); const bIsBracketted = b.name.startsWith("[["); if (aIsBracketted !== bIsBracketted) { return aIsBracketted ? -1 : 1; } const aAsNum = Number(a.name); const bAsNum = Number(b.name); const aIsNum = !isNaN(aAsNum); const bIsNum = !isNaN(bAsNum); if (aIsNum !== bIsNum) { return aIsNum ? -1 : 1; } else if (aIsNum && bIsNum) { return aAsNum - bAsNum; } let aName = a.name.replace("[", " "); let bName = b.name.replace("[", " "); const aNameLower = aName.toLowerCase(); const bNameLower = bName.toLowerCase(); if (aNameLower !== bNameLower) { aName = aNameLower; bName = bNameLower; } if (aName === bName) { return 0; } else if (aName < bName) { return -1; } else { return 1; } } function parseFrameId(frameId: number) { return {threadId: Math.floor(frameId / maxStackCount) + 1, frame: frameId % maxStackCount + 1}; } function makeFrameId(threadId: number, frame: number) { return (threadId - 1) * maxStackCount + (frame - 1); } export class LuaDebugSession extends LoggingDebugSession { private readonly fileBreakpoints: { [file: string]: DebugProtocol.SourceBreakpoint[] | undefined } = {}; private config?: LaunchConfig; private process: childProcess.ChildProcess | null = null; private outputText = ""; private onConfigurationDone?: () => void; private readonly messageHandlerQueue: MessageHandler[] = []; private readonly variableHandles = new Handles<string>(ScopeType.Global + 1); private breakpointsPending = false; private autoContinueNext = false; private readonly activeThreads = new Map<number, Thread>(); private isRunning = false; public constructor() { super("lldebugger-log.txt"); } protected initializeRequest( response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments ): void { this.showOutput("initializeRequest", OutputCategory.Request); if (typeof response.body === "undefined") { response.body = {}; } response.body.supportsConfigurationDoneRequest = true; response.body.supportsEvaluateForHovers = true; response.body.supportsSetVariable = true; response.body.supportsTerminateRequest = true; response.body.supportsConditionalBreakpoints = true; this.sendResponse(response); this.sendEvent(new InitializedEvent()); } protected configurationDoneRequest( response: DebugProtocol.ConfigurationDoneResponse, args: DebugProtocol.ConfigurationDoneArguments ): void { this.showOutput("configurationDoneRequest", OutputCategory.Request); super.configurationDoneRequest(response, args); if (typeof this.onConfigurationDone !== "undefined") { this.onConfigurationDone(); } } protected async launchRequest( response: DebugProtocol.LaunchResponse, args: DebugProtocol.LaunchRequestArguments & LaunchConfig ): Promise<void> { this.config = args; this.autoContinueNext = this.config.stopOnEntry !== true; this.showOutput("launchRequest", OutputCategory.Request); await this.waitForConfiguration(); //Setup process if (!path.isAbsolute(this.config.cwd)) { this.config.cwd = path.resolve(this.config.workspacePath, this.config.cwd); } const cwd = this.config.cwd; const processOptions/* : child_process.SpawnOptions */ = { env: Object.assign({}, process.env), cwd, shell: true }; if (typeof this.config.env !== "undefined") { for (const key in this.config.env) { const envKey = getEnvKey(processOptions.env, key); processOptions.env[envKey] = this.config.env[key]; } } //Set an environment variable so the debugger can detect the attached extension processOptions.env[envVariable] = "1"; processOptions.env[filePathEnvVariable] = `${this.config.extensionPath}${path.sep}debugger${path.sep}lldebugger.lua`; //Pass options via environment variables if (typeof this.config.scriptRoots !== "undefined") { processOptions.env[scriptRootsEnvVariable] = this.config.scriptRoots.join(";"); } if (typeof this.config.breakInCoroutines !== "undefined") { processOptions.env[breakInCoroutinesEnv] = this.config.breakInCoroutines ? "1" : "0"; } //Append lua path so it can find debugger script this.updateLuaPath("LUA_PATH_5_2", processOptions.env, false); this.updateLuaPath("LUA_PATH_5_3", processOptions.env, false); this.updateLuaPath("LUA_PATH_5_4", processOptions.env, false); this.updateLuaPath("LUA_PATH", processOptions.env, true); //Launch process let processExecutable: string; let processArgs: string[]; if (isCustomProgramConfig(this.config.program)) { processExecutable = `"${this.config.program.command}"`; processArgs = typeof this.config.args !== "undefined" ? this.config.args : []; } else { processExecutable = `"${this.config.program.lua}"`; const programArgs = (typeof this.config.args !== "undefined") ? `, ${this.config.args.map(a => `[[${a}]]`)}` : ""; processArgs = [ "-e", "\"require('lldebugger').runFile(" + `[[${this.config.program.file}]],` + "true," + `{[-1]=[[${this.config.program.lua}]],[0]=[[${this.config.program.file}]]${programArgs}}` + ")\"" ]; } this.process = childProcess.spawn(processExecutable, processArgs, processOptions); this.showOutput( `launching \`${processExecutable} ${processArgs.join(" ")}\` from "${cwd}"`, OutputCategory.Info ); //Process callbacks this.assert(this.process.stdout).on("data", data => { void this.onDebuggerOutput(data, false); }); this.assert(this.process.stderr).on("data", data => { void this.onDebuggerOutput(data, true); }); this.process.on("close", (code, signal) => this.onDebuggerTerminated(`${code !== null ? code : signal}`)); this.process.on("disconnect", () => this.onDebuggerTerminated("disconnected")); this.process.on( "error", err => this.onDebuggerTerminated( `Failed to launch \`${processExecutable} ${processArgs.join(" ")}\` from "${cwd}": ${err}`, OutputCategory.Error ) ); this.process.on("exit", (code, signal) => this.onDebuggerTerminated(`${code !== null ? code : signal}`)); this.isRunning = true; this.showOutput("process launched", OutputCategory.Info); this.sendResponse(response); } protected async setBreakPointsRequest( response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments ): Promise<void> { this.showOutput("setBreakPointsRequest", OutputCategory.Request); const filePath = args.source.path as string; if (this.process !== null && !this.isRunning) { const oldBreakpoints = this.fileBreakpoints[filePath]; if (typeof oldBreakpoints !== "undefined") { for (const breakpoint of oldBreakpoints) { await this.deleteBreakpoint(filePath, breakpoint); } } if (typeof args.breakpoints !== "undefined") { for (const breakpoint of args.breakpoints) { await this.setBreakpoint(filePath, breakpoint); } } } else { this.breakpointsPending = true; } this.fileBreakpoints[filePath] = args.breakpoints; const breakpoints: Breakpoint[] = (typeof args.breakpoints !== "undefined") ? args.breakpoints.map(breakpoint => new Breakpoint(true, breakpoint.line)) : []; response.body = {breakpoints}; this.sendResponse(response); } protected async threadsRequest(response: DebugProtocol.ThreadsResponse): Promise<void> { this.showOutput("threadsRequest", OutputCategory.Request); const msg = await this.waitForCommandResponse("threads"); if (msg.type === "threads") { //Remove dead threads const activeThreadIds = [...this.activeThreads.keys()]; for (const activeId of activeThreadIds) { if (!msg.threads.some(({id}) => activeId === id)) { this.sendEvent(new ThreadEvent("exited", activeId)); this.activeThreads.delete(activeId); } } //Create new threads const newThreads = msg.threads.filter(({id}) => !this.activeThreads.has(id)); for (const {id, name} of newThreads) { this.activeThreads.set(id, new Thread(id, name)); } response.body = {threads: [...this.activeThreads.values()]}; } else { response.success = false; } this.sendResponse(response); } protected async stackTraceRequest( response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments ): Promise<void> { this.showOutput( `stackTraceRequest ${args.startFrame}/${args.levels} (thread ${args.threadId})`, OutputCategory.Request ); const msg = await this.waitForCommandResponse(`thread ${args.threadId}`); const startFrame = typeof args.startFrame !== "undefined" ? args.startFrame : 0; const maxLevels = typeof args.levels !== "undefined" ? args.levels : maxStackCount; if (msg.type === "stack") { const frames: DebugProtocol.StackFrame[] = []; const endFrame = Math.min(startFrame + maxLevels, msg.frames.length); for (let i = startFrame; i < endFrame; ++i) { const frame = msg.frames[i]; let source: Source | undefined; let line = frame.line; let column = 1; //Needed for exception display: https://github.com/microsoft/vscode/issues/46080 //Mapped source if (typeof frame.mappedLocation !== "undefined") { const mappedPath = this.resolvePath(frame.mappedLocation.source); if (typeof mappedPath !== "undefined") { source = new Source(path.basename(mappedPath), mappedPath); line = frame.mappedLocation.line; column = frame.mappedLocation.column; } } //Un-mapped source const sourcePath = this.resolvePath(frame.source); if (typeof source === "undefined" && typeof sourcePath !== "undefined") { source = new Source(path.basename(frame.source), sourcePath); } //Function name let frameFunc = typeof frame.func !== "undefined" ? frame.func : "???"; if (typeof sourcePath === "undefined") { frameFunc += ` ${frame.source}`; } const frameId = makeFrameId(args.threadId, i + 1); const stackFrame: DebugProtocol.StackFrame = new StackFrame(frameId, frameFunc, source, line, column); stackFrame.presentationHint = typeof sourcePath === "undefined" ? "subtle" : "normal"; frames.push(stackFrame); } response.body = {stackFrames: frames, totalFrames: msg.frames.length}; } else { response.success = false; } this.sendResponse(response); } protected async scopesRequest( response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments ): Promise<void> { this.showOutput("scopesRequest", OutputCategory.Request); const {threadId, frame} = parseFrameId(args.frameId); await this.waitForCommandResponse(`thread ${threadId}`); await this.waitForCommandResponse(`frame ${frame}`); const scopes: Scope[] = [ new Scope("Locals", ScopeType.Local, false), new Scope("Upvalues", ScopeType.Upvalue, false), new Scope("Globals", ScopeType.Global, false) ]; response.body = {scopes}; this.sendResponse(response); } protected async variablesRequest( response: DebugProtocol.VariablesResponse, args: DebugProtocol.VariablesArguments ): Promise<void> { let cmd: string | undefined; let baseName: string | undefined; switch (args.variablesReference) { case ScopeType.Local: cmd = "locals"; this.showOutput("variablesRequest locals", OutputCategory.Request); break; case ScopeType.Upvalue: cmd = "ups"; this.showOutput("variablesRequest ups", OutputCategory.Request); break; case ScopeType.Global: cmd = "globals"; this.showOutput("variablesRequest globals", OutputCategory.Request); break; default: baseName = this.assert(this.variableHandles.get(args.variablesReference)); cmd = `props ${baseName}`; if (typeof args.filter !== "undefined") { cmd += ` ${args.filter}`; if (typeof args.start !== "undefined") { const start = Math.max(args.start, 1); cmd += ` ${start}`; if (typeof args.count !== "undefined") { const count = args.start + args.count - start; cmd += ` ${count}`; } } } else { cmd += " all"; } this.showOutput( `variablesRequest ${baseName} ${args.filter} ${args.start}/${args.count}`, OutputCategory.Request ); break; } const vars = await this.waitForCommandResponse(cmd); const variables: Variable[] = []; if (vars.type === "variables") { for (const variable of vars.variables) { variables.push(this.buildVariable(variable, variable.name)); } } else if (vars.type === "properties") { for (const variable of vars.properties) { const refName = typeof baseName === "undefined" ? variable.name : `${baseName}[${variable.name}]`; variables.push(this.buildVariable(variable, refName)); } if (typeof vars.metatable !== "undefined" && typeof baseName !== "undefined") { variables.push(this.buildVariable(vars.metatable, `getmetatable(${baseName})`, metatableDisplayName)); } if (typeof vars.length !== "undefined") { const value: LuaDebug.Value = {type: "number", value: vars.length.toString()}; variables.push(this.buildVariable(value, `#${baseName}`, tableLengthDisplayName)); } } else { response.success = false; } variables.sort(sortVariables); response.body = {variables}; this.sendResponse(response); } protected continueRequest(response: DebugProtocol.ContinueResponse, args: DebugProtocol.ContinueArguments): void { this.showOutput("continueRequest", OutputCategory.Request); if (this.sendCommand("cont")) { this.variableHandles.reset(); this.isRunning = true; } else { response.success = false; } this.sendResponse(response); } protected nextRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments): void { this.showOutput("nextRequest", OutputCategory.Request); if (this.sendCommand("step")) { this.variableHandles.reset(); this.isRunning = true; } else { response.success = false; } this.sendResponse(response); } protected stepInRequest(response: DebugProtocol.StepInResponse, args: DebugProtocol.StepInArguments): void { this.showOutput("stepInRequest", OutputCategory.Request); if (this.sendCommand("stepin")) { this.variableHandles.reset(); this.isRunning = true; } else { response.success = false; } this.sendResponse(response); } protected stepOutRequest(response: DebugProtocol.StepOutResponse, args: DebugProtocol.StepOutArguments): void { this.showOutput("stepOutRequest", OutputCategory.Request); if (this.sendCommand("stepout")) { this.variableHandles.reset(); this.isRunning = true; } else { response.success = false; } this.sendResponse(response); } protected async setVariableRequest( response: DebugProtocol.SetVariableResponse, args: DebugProtocol.SetVariableArguments ): Promise<void> { let msg: LuaDebug.Message; if (args.variablesReference === ScopeType.Global || args.variablesReference === ScopeType.Local || args.variablesReference === ScopeType.Upvalue ) { this.showOutput(`setVariableRequest ${args.name} = ${args.value}`, OutputCategory.Request); msg = await this.waitForCommandResponse(`exec ${args.name} = ${args.value}; return ${args.name}`); } else if (args.name === metatableDisplayName) { const name = this.variableHandles.get(args.variablesReference); this.showOutput(`setVariableRequest ${name}[[metatable]] = ${args.value}`, OutputCategory.Request); msg = await this.waitForCommandResponse(`eval setmetatable(${name}, ${args.value})`); } else if (args.name === tableLengthDisplayName) { const name = this.variableHandles.get(args.variablesReference); this.showOutput(`setVariableRequest ${name}[[length]] = ${args.value}`, OutputCategory.Request); msg = await this.waitForCommandResponse(`eval #${name}`); } else { const name = `${this.variableHandles.get(args.variablesReference)}[${args.name}]`; this.showOutput(`setVariableRequest ${name} = ${args.value}`, OutputCategory.Request); msg = await this.waitForCommandResponse(`exec ${name} = ${args.value}; return ${name}`); } const result = this.handleEvaluationResult(args.value, msg); if (!result.success) { if (typeof result.error !== "undefined") { this.showOutput(result.error, OutputCategory.Error); } response.success = false; } else { response.body = result; } this.sendResponse(response); } protected async evaluateRequest( response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments ): Promise<void> { const expression = args.expression; this.showOutput(`evaluateRequest ${expression}`, OutputCategory.Request); if (typeof args.frameId !== "undefined") { const {threadId, frame} = parseFrameId(args.frameId); await this.waitForCommandResponse(`thread ${threadId}`); await this.waitForCommandResponse(`frame ${frame}`); } const msg = await this.waitForCommandResponse(`eval ${expression}`); const result = this.handleEvaluationResult(expression, msg); if (!result.success) { if (typeof result.error !== "undefined" && args.context !== "hover") { if (args.context !== "watch") { this.showOutput(result.error, OutputCategory.Error); } response.success = false; const errorMsg = /^\[.+\]:\d+:(.+)/.exec(result.error); response.message = (errorMsg !== null && errorMsg.length > 1) ? errorMsg[1] : result.error; } } else { response.body = {result: result.value, variablesReference: result.variablesReference}; } this.sendResponse(response); } protected terminateRequest( response: DebugProtocol.TerminateResponse, args: DebugProtocol.TerminateArguments ): void { this.showOutput("terminateRequest", OutputCategory.Request); if (this.process !== null) { if (process.platform === "win32") { childProcess.spawn("taskkill", ["/pid", this.assert(this.process.pid).toString(), "/f", "/t"]); } else { this.process.kill(); } } this.isRunning = false; this.sendResponse(response); } private handleEvaluationResult( expression: string, msg: LuaDebug.Message ): {success: true; value: string; variablesReference: number} | {success: false; error?: string} { if (msg.type === "result") { const variablesReference = msg.result.type === "table" ? this.variableHandles.create(expression) : 0; const value = `${typeof msg.result.value !== "undefined" ? msg.result.value : `[${msg.result.type}]`}`; return {success: true, value, variablesReference}; } else if (msg.type === "error") { return {success: false, error: msg.error}; } else { return {success: false}; } } private buildVariable(variable: LuaDebug.Variable, refName: string): Variable; private buildVariable(value: LuaDebug.Value, refName: string, variableName: string): Variable; private buildVariable(variable: LuaDebug.Variable | LuaDebug.Value, refName: string, variableName?: string) { let valueStr: string; let ref: number | undefined; if (variable.type === "table") { ref = this.variableHandles.create(refName); valueStr = typeof variable.value !== "undefined" ? variable.value : "[table]"; } else if (typeof variable.value === "undefined") { valueStr = `[${variable.type}]`; } else { valueStr = variable.value; } const name = typeof variableName !== "undefined" ? variableName : (variable as LuaDebug.Variable).name; const indexedVariables = typeof variable.length !== "undefined" && variable.length > 0 ? variable.length + 1 : variable.length; if (variable.type === "table") { return new Variable(name, valueStr, ref, indexedVariables, 1); } else { return new Variable(name, valueStr, ref, indexedVariables); } } private assert<T>(value: T | null | undefined, message = "assertion failed"): T { if (value === null || typeof value === "undefined") { this.sendEvent(new OutputEvent(message)); throw new Error(message); } return value; } private resolvePath(filePath: string) { if (filePath.length === 0) { return; } const config = this.assert(this.config); let fullPath = path.isAbsolute(filePath) ? filePath : path.join(config.cwd, filePath); if (fs.existsSync(fullPath)) { return fullPath; } if (typeof config.scriptRoots === "undefined") { return; } for (const rootPath of config.scriptRoots) { if (path.isAbsolute(rootPath)) { fullPath = path.join(rootPath, filePath); } else { fullPath = path.join(config.cwd, rootPath, filePath); } if (fs.existsSync(fullPath)) { return fullPath; } } return; } private updateLuaPath(pathKey: string, env: NodeJS.ProcessEnv, force: boolean) { const luaPathKey = getEnvKey(env, pathKey); let luaPath = env[luaPathKey]; if (typeof luaPath === "undefined") { if (!force) { return; } luaPath = ";;"; //Retain defaults } else if (luaPath.length > 0 && !luaPath.endsWith(";")) { luaPath += ";"; } env[luaPathKey] = `${luaPath}${this.assert(this.config).extensionPath}/debugger/?.lua`; } private setBreakpoint(filePath: string, breakpoint: DebugProtocol.SourceBreakpoint) { const cmd = typeof breakpoint.condition !== "undefined" ? `break set ${filePath}:${breakpoint.line} ${breakpoint.condition}` : `break set ${filePath}:${breakpoint.line}`; return this.waitForCommandResponse(cmd); } private deleteBreakpoint(filePath: string, breakpoint: DebugProtocol.SourceBreakpoint) { return this.waitForCommandResponse(`break delete ${filePath}:${breakpoint.line}`); } private async onDebuggerStop(msg: LuaDebug.DebugBreak) { this.isRunning = false; if (this.breakpointsPending) { this.breakpointsPending = false; await this.waitForCommandResponse("break clear"); for (const filePath in this.fileBreakpoints) { const breakpoints = this.fileBreakpoints[filePath] as DebugProtocol.SourceBreakpoint[]; for (const breakpoint of breakpoints) { await this.setBreakpoint(filePath, breakpoint); } } } if (msg.breakType === "error") { this.showOutput(msg.message, OutputCategory.Error); const evt: DebugProtocol.StoppedEvent = new StoppedEvent("exception", msg.threadId, msg.message); evt.body.allThreadsStopped = true; this.sendEvent(evt); return; } if (this.autoContinueNext) { this.autoContinueNext = false; this.assert(this.sendCommand("autocont")); } else { const evt: DebugProtocol.StoppedEvent = new StoppedEvent("breakpoint", msg.threadId); evt.body.allThreadsStopped = true; this.sendEvent(evt); } } private handleDebugMessage(msg: LuaDebug.Message) { const handler = this.messageHandlerQueue.shift(); if (typeof handler !== "undefined") { handler(msg); } } private async onDebuggerOutput(data: unknown, isError: boolean) { const dataStr = `${data}`; if (isError) { this.showOutput(dataStr, OutputCategory.StdErr); return; } this.outputText += dataStr; const [messages, processed, unprocessed] = Message.parse(this.outputText); let debugBreak: LuaDebug.DebugBreak | undefined; for (const msg of messages) { this.showOutput(JSON.stringify(msg), OutputCategory.Message); if (msg.type === "debugBreak") { debugBreak = msg; } else { this.handleDebugMessage(msg); } } this.showOutput(processed, OutputCategory.StdOut); this.outputText = unprocessed; if (typeof debugBreak !== "undefined") { await this.onDebuggerStop(debugBreak); } } private onDebuggerTerminated(result: string, category = OutputCategory.Info) { if (this.process === null) { return; } this.process = null; this.isRunning = false; if (this.outputText.length > 0) { this.showOutput(this.outputText, OutputCategory.StdOut); this.outputText = ""; } this.showOutput(`debugging ended: ${result}`, category); this.sendEvent(new TerminatedEvent()); } private sendCommand(cmd: string) { if (this.process === null || this.isRunning) { return false; } this.showOutput(cmd, OutputCategory.Command); this.assert(this.process.stdin).write(`${cmd}\n`); return true; } private waitForCommandResponse(cmd: string): Promise<LuaDebug.Message> { if (this.sendCommand(cmd)) { return new Promise( resolve => { this.messageHandlerQueue.push(resolve); } ); } else { return Promise.resolve({tag: "$luaDebug", type: "error", error: "Failed to send command"}); } } private showOutput(msg: string, category: OutputCategory) { if (msg.length === 0) { return; } else if (category === OutputCategory.StdOut || category === OutputCategory.StdErr) { this.sendEvent(new OutputEvent(msg, category)); } else if (category === OutputCategory.Error) { this.sendEvent(new OutputEvent(`\n[${category}] ${msg}\n`, "stderr")); } else if (typeof this.config !== "undefined" && this.config.verbose === true) { this.sendEvent(new OutputEvent(`\n[${category}] ${msg}\n`)); } } private waitForConfiguration() { return new Promise<void>(resolve => { this.onConfigurationDone = resolve; }); } }
the_stack