text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
'use strict' import WritableFilter from '../interfaces/writable-filter' import BaseFilter from '../base-filter' import Bucket from './bucket' import { Exportable, cloneObject } from '../exportable' import { HashableInput, allocateArray, hashAsInt, hashIntAndString, randomInt } from '../utils' /** * Compute the optimal fingerprint length in bytes for a given bucket size * and a false positive rate. * @param {int} size - The filter bucket size * @param {int} rate - The error rate, i.e. 'false positive' rate, targetted by the filter * @return {int} The optimal fingerprint length in bytes * @private */ function computeFingerpintLength (size: number, rate: number): number { const f = Math.ceil(Math.log2(1 / rate) + Math.log2(2 * size)) return Math.ceil(f / 4) // because we use base 16 64-bits hashes } /** * Cuckoo filters improve on Bloom filters by supporting deletion, limited counting, * and bounded False positive rate with similar storage efficiency as a standard Bloom filter. * * Reference: Fan, B., Andersen, D. G., Kaminsky, M., & Mitzenmacher, M. D. (2014, December). Cuckoo filter: Practically better than bloom. * In Proceedings of the 10th ACM International on Conference on emerging Networking Experiments and Technologies (pp. 75-88). ACM. * @see {@link https://www.cs.cmu.edu/~dga/papers/cuckoo-conext2014.pdf} for more details about Cuckoo filters * @author Thomas Minier & Arnaud Grall */ @Exportable({ export: cloneObject('CuckooFilter', '_size', '_fingerprintLength', '_length', '_maxKicks', '_filter', '_seed'), import: (json: any) => { if ((json.type !== 'CuckooFilter') || !('_size' in json) || !('_fingerprintLength' in json) || !('_length' in json) || !('_maxKicks' in json) || !('_filter' in json) || !('_seed' in json)) { throw new Error('Cannot create a CuckooFilter from a JSON export which does not represent a cuckoo filter') } const filter = new CuckooFilter(json._size, json._fingerprintLength, json._bucketSize, json._maxKicks) filter._length = json._length filter._filter = json._filter.map((j: any) => { const bucket = new Bucket<string>(j._size) j._elements.forEach((elt: any, i: number) => { if (elt !== null) { bucket._elements[i] = elt bucket._length++ } }) return bucket }) filter.seed = json.seed return filter } }) export default class CuckooFilter extends BaseFilter implements WritableFilter<HashableInput> { private _filter: Array<Bucket<string>> private _size: number private _bucketSize: number private _fingerprintLength: number private _length: number private _maxKicks: number /** * Constructor * @param size - The filter size * @param fLength - The length of the fingerprints * @param bucketSize - The size of the buckets in the filter * @param maxKicks - (optional) The max number of kicks when resolving collision at insertion, default to 1 */ constructor (size: number, fLength: number, bucketSize: number, maxKicks: number = 500) { super() this._filter = allocateArray(size, () => new Bucket(bucketSize)) this._size = size this._bucketSize = bucketSize this._fingerprintLength = fLength this._length = 0 this._maxKicks = maxKicks } /** * Return a new optimal CuckooFilter given the number of maximum elements to store and the error rate desired * @param size - The number of items to store * @param errorRate - The desired error rate * @param bucketSize - The number of buckets desired per cell * @param maxKicks - The number of kicks done when a collision occurs * @return A Cuckoo Filter optimal for these parameters */ static create (size: number, errorRate: number, bucketSize: number = 4, maxKicks: number = 500): CuckooFilter { const fl = computeFingerpintLength(bucketSize, errorRate) const capacity = Math.ceil(size / bucketSize / 0.955) // const capacity = utils.power2(items) return new CuckooFilter(capacity, fl, bucketSize, maxKicks) } /** * Build a new optimal CuckooFilter from an iterable with a fixed error rate * @param items - Iterable used to populate the filter * @param errorRate - The error rate of the filter * @param bucketSize - The number of buckets desired per cell * @param maxKicks - The number of kicks done when a collision occurs * @return A new Cuckoo Filter filled with the iterable's elements */ static from (items: Iterable<HashableInput>, errorRate: number, bucketSize: number = 4, maxKicks: number = 500): CuckooFilter { const array = Array.from(items) const filter = CuckooFilter.create(array.length, errorRate, bucketSize, maxKicks) array.forEach(item => filter.add(item)) return filter } /** * Get the filter size */ get size (): number { return this._size } /** * Get the filter full size, i.e., the total number of cells */ get fullSize (): number { return this.size * this.bucketSize } /** * Get the filter length, i.e. the current number of elements in the filter */ get length (): number { return this._length } /** * Get the length of the fingerprints in the filter */ get fingerprintLength (): number { return this._fingerprintLength } /** * Get the size of the buckets in the filter */ get bucketSize (): number { return this._bucketSize } /** * Get the max number of kicks when resolving collision at insertion */ get maxKicks (): number { return this._maxKicks } /** * Add an element to the filter, if false is returned, it means that the filter is considered as full. * @param element - The element to add * @return True if the insertion is a success, False if the filter is full * @example * const filter = new CuckooFilter(15, 3, 2); * filter.add('alice'); * filter.add('bob'); */ add (element: HashableInput, throwError: boolean = false, destructive: boolean = false): boolean { // TODO do the recovery if return false or throw error because we altered values const locations = this._locations(element) // store fingerprint in an available empty bucket if (this._filter[locations.firstIndex].isFree()) { this._filter[locations.firstIndex].add(locations.fingerprint) } else if (this._filter[locations.secondIndex].isFree()) { this._filter[locations.secondIndex].add(locations.fingerprint) } else { // buckets are full, we must relocate one of them let index = this.random() < 0.5 ? locations.firstIndex : locations.secondIndex let movedElement: string = locations.fingerprint const logs: Array<[number, number, string | null]> = [] for (let nbTry = 0; nbTry < this._maxKicks; nbTry++) { const rndIndex = randomInt(0, this._filter[index].length - 1, this.random) const tmp = this._filter[index].at(rndIndex) logs.push([index, rndIndex, tmp]) this._filter[index].set(rndIndex, movedElement) movedElement = tmp! // movedElement = this._filter[index].set(rndswapRandom(movedElement, this._rng) const newHash = hashAsInt(movedElement!, this.seed, 64) index = Math.abs((index ^ Math.abs(newHash))) % this._filter.length // add the moved element to the bucket if possible if (this._filter[index].isFree()) { this._filter[index].add(movedElement) this._length++ return true } } if (!destructive) { // rollback all modified entries to their initial states for (let i = logs.length - 1; i >= 0; i--) { const log = logs[i] this._filter[log[0]].set(log[1], log[2]) } } // considered full if (throwError) { // rollback all operations throw new Error(`The Cuckoo Filter is full, cannot insert element "${element}"`) } else { return false } } this._length++ return true } /** * Remove an element from the filter * @param element - The element to remove * @return True if the element has been removed from the filter, False if it wasn't in the filter * @example * const filter = new CuckooFilter(15, 3, 2); * filter.add('alice'); * filter.add('bob'); * * // remove an element * filter.remove('bob'); */ remove (element: HashableInput): boolean { const locations = this._locations(element) if (this._filter[locations.firstIndex].has(locations.fingerprint)) { this._filter[locations.firstIndex].remove(locations.fingerprint) this._length-- return true } else if (this._filter[locations.secondIndex].has(locations.fingerprint)) { this._filter[locations.secondIndex].remove(locations.fingerprint) this._length-- return true } return false } /** * Test an element for membership * @param element - The element to look for in the filter * @return False if the element is definitively not in the filter, True is the element might be in the filter * @example * const filter = new CuckooFilter(15, 3, 2); * filter.add('alice'); * * console.log(filter.has('alice')); // output: true * console.log(filter.has('bob')); // output: false */ has (element: HashableInput): boolean { const locations = this._locations(element) return this._filter[locations.firstIndex].has(locations.fingerprint) || this._filter[locations.secondIndex].has(locations.fingerprint) } /** * Return the false positive rate for this cuckoo filter * @return The false positive rate */ rate (): number { const load = this._computeHashTableLoad() const c = this._fingerprintLength / load.load return Math.pow(2, Math.log2(2 * this._bucketSize) - (load.load * c)) } /** * Return the load of this filter * @return {Object} load: is the load, size is the number of entries, free is the free number of entries, used is the number of entry used */ _computeHashTableLoad () { const max = this._filter.length * this._bucketSize const used = this._filter.reduce((acc, val) => acc + val.length, 0) return { used, free: max - used, size: max, load: used / max } } /** * For a element, compute its fingerprint and the index of its two buckets * @param element - The element to hash * @return The fingerprint of the element and the index of its two buckets * @private */ _locations (element: HashableInput) { const hashes = hashIntAndString(element, this.seed, 16, 64) const hash = hashes.int if (this._fingerprintLength > hashes.string.length) { throw new Error(`The fingerprint length (${this._fingerprintLength}) is higher than the hash length (${hashes.string.length}). Please reduce the fingerprint length or report if it is an unexpected behavior.`) } const fingerprint = hashes.string.substring(0, this._fingerprintLength) const firstIndex = Math.abs(hash) const secondHash = Math.abs(hashAsInt(fingerprint, this.seed, 64)) const secondIndex = Math.abs(firstIndex ^ secondHash) const res = { fingerprint, firstIndex: firstIndex % this._size, secondIndex: secondIndex % this._size } return res } /** * Check if another Cuckoo filter is equal to this one * @param filter - The cuckoo filter to compare to this one * @return True if they are equal, false otherwise */ equals (filter: CuckooFilter): boolean { let i = 0 let res = true while (res && i < this._filter.length) { const bucket = this._filter[i] if (!filter._filter[i].equals(bucket)) { res = false } i++ } return res } }
the_stack
import { advanceTo } from 'jest-date-mock'; import spyMatchers from 'expect/build/spyMatchers'; import { Logger } from './logger'; import { LEVELS } from './constants'; advanceTo(0); expect.extend({ toMatchLog(received, arg, name = '') { return spyMatchers.toHaveBeenLastCalledWith.call( this, received, expect.objectContaining({ name, args: [arg], }) ); }, }); declare global { // eslint-disable-next-line @typescript-eslint/no-namespace namespace jest { interface Matchers<R> { toMatchLog(arg, name?): R; } } } describe('@tinkoff/logger', () => { beforeEach(() => { // Сбрасываем кеш в логгере перед каждым тестом // @ts-ignore Logger.instances = []; Logger.clear(); }); it('should have log functions for all levels and they should be binded to logger', () => { const logger = new Logger(); // @ts-ignore logger.log = jest.fn(); expect(logger.trace).toBeInstanceOf(Function); expect(logger.debug).toBeInstanceOf(Function); expect(logger.info).toBeInstanceOf(Function); expect(logger.warn).toBeInstanceOf(Function); expect(logger.error).toBeInstanceOf(Function); expect(logger.fatal).toBeInstanceOf(Function); const { error, trace } = logger; error('test-error'); // @ts-ignore expect(logger.log).toHaveBeenCalledWith(LEVELS.error, ['test-error']); trace('test-trace'); // @ts-ignore expect(logger.log).toHaveBeenCalledWith(LEVELS.trace, ['test-trace']); }); describe('reporters', () => { const reporter1 = { log: jest.fn(), }; const reporter2 = { log: jest.fn(), }; beforeEach(() => { reporter1.log.mockClear(); reporter2.log.mockClear(); }); it('reporters can be dynamically added', () => { const logger = new Logger({ name: '', level: 'error' }); logger.error({ event: 'err', message: '1' }); expect(reporter1.log).not.toHaveBeenCalled(); expect(reporter2.log).not.toHaveBeenCalled(); logger.addReporter(reporter1); logger.error({ event: 'err', message: '2' }); expect(reporter1.log).toMatchLog({ event: 'err', message: '2' }); expect(reporter2.log).not.toHaveBeenCalled(); logger.addReporter(reporter2); logger.error({ event: 'err', message: '3' }); expect(reporter1.log).toMatchLog({ event: 'err', message: '3' }); expect(reporter2.log).toMatchLog({ event: 'err', message: '3' }); }); it('reporters can be replaced', () => { const logger = new Logger({ name: '', level: 'error', reporters: [reporter1] }); logger.error('test1'); expect(reporter1.log).toMatchLog('test1'); expect(reporter2.log).not.toHaveBeenCalled(); logger.setReporters([reporter2]); logger.error('test2'); expect(reporter1.log).not.toMatchLog('test2'); expect(reporter2.log).toMatchLog('test2'); }); it('should call reporters on log', () => { const logger = new Logger({ name: '', level: 'error', reporters: [reporter1, reporter2] }); logger.info('test'); expect(reporter1.log).not.toHaveBeenCalled(); expect(reporter2.log).not.toHaveBeenCalled(); logger.error({ event: 'err', message: 'testError' }); expect(reporter1.log).toHaveBeenCalledWith({ type: 'error', level: 10, name: '', date: new Date(), args: [ { event: 'err', message: 'testError', }, ], }); expect(reporter2.log).toHaveBeenCalledWith({ type: 'error', level: 10, name: '', date: new Date(), args: [ { event: 'err', message: 'testError', }, ], }); }); }); describe('beforeReporters', () => { const reporter1 = { log: jest.fn(), }; const reporter2 = { log: jest.fn(), }; beforeEach(() => { reporter1.log.mockClear(); reporter2.log.mockClear(); }); it('beforeReporters can be dynamically added', () => { const logger = new Logger({ name: '' }); logger.error({ event: 'err', message: '1' }); expect(reporter1.log).not.toHaveBeenCalled(); expect(reporter2.log).not.toHaveBeenCalled(); logger.addBeforeReporter(reporter1); logger.error({ event: 'err', message: '2' }); expect(reporter1.log).toMatchLog({ event: 'err', message: '2' }); expect(reporter2.log).not.toHaveBeenCalled(); logger.addBeforeReporter(reporter2); logger.error({ event: 'err', message: '3' }); expect(reporter1.log).toMatchLog({ event: 'err', message: '3' }); expect(reporter2.log).toMatchLog({ event: 'err', message: '3' }); }); it('beforeReporters can be replaced', () => { const logger = new Logger({ name: '', beforeReporters: [reporter1] }); logger.error('test1'); expect(reporter1.log).toMatchLog('test1'); expect(reporter2.log).not.toHaveBeenCalled(); logger.setBeforeReporters([reporter2]); logger.error('test2'); expect(reporter1.log).not.toMatchLog('test2'); expect(reporter2.log).toMatchLog('test2'); }); it('should call beforeReporters on log', () => { const logger = new Logger({ name: '', beforeReporters: [reporter1, reporter2] }); logger.info('test'); expect(reporter1.log).toHaveBeenCalledWith({ type: 'info', level: 30, name: '', date: new Date(), args: ['test'], }); expect(reporter2.log).toHaveBeenCalledWith({ type: 'info', level: 30, name: '', date: new Date(), args: ['test'], }); logger.error({ event: 'err', message: 'testError' }); expect(reporter1.log).toHaveBeenCalledWith({ type: 'error', level: 10, name: '', date: new Date(), args: [ { event: 'err', message: 'testError', }, ], }); expect(reporter2.log).toHaveBeenCalledWith({ type: 'error', level: 10, name: '', date: new Date(), args: [ { event: 'err', message: 'testError', }, ], }); }); }); describe('filters', () => { const filter1 = { filter: jest.fn(), }; const filter2 = { filter: jest.fn(), }; beforeEach(() => { filter1.filter.mockClear(); filter2.filter.mockClear(); }); it('filters can be added dynamically', () => { const logger = new Logger({ name: '', level: 'error', filters: [filter1] }); logger.error('test1'); expect(filter1.filter).toMatchLog('test1'); expect(filter2.filter).not.toHaveBeenCalled(); logger.addFilter(filter2); logger.error('test2'); expect(filter1.filter).toMatchLog('test2'); expect(filter2.filter).toMatchLog('test2'); }); it('filters can be replaced', () => { const logger = new Logger({ name: '', level: 'error', filters: [filter1] }); logger.error('test1'); expect(filter1.filter).toMatchLog('test1'); expect(filter2.filter).not.toHaveBeenCalled(); logger.setFilters(filter2); logger.error('test2'); expect(filter1.filter).not.toMatchLog('test2'); expect(filter2.filter).toMatchLog('test2'); }); it('filters can block logs', () => { const reporter = { log: jest.fn() }; const logger = new Logger({ name: '', level: 'error', filters: [filter1, filter2], reporters: [reporter], }); logger.error('filter-test-1'); expect(filter1.filter).toMatchLog('filter-test-1'); expect(filter2.filter).toMatchLog('filter-test-1'); expect(reporter.log).toMatchLog('filter-test-1'); filter1.filter.mockImplementationOnce(() => false); logger.error('filter-test-2'); expect(filter1.filter).toMatchLog('filter-test-2'); expect(filter2.filter).not.toMatchLog('filter-test-2'); expect(reporter.log).not.toMatchLog('filter-test-2'); }); }); describe('extensions', () => { const extension1 = { extend: jest.fn((x) => x), }; const extension2 = { extend: jest.fn((x) => x), }; beforeEach(() => { extension1.extend.mockClear(); extension2.extend.mockClear(); }); it('extensions can be added dynamically', () => { const logger = new Logger({ name: '', level: 'error', extensions: [extension1] }); logger.error('test1'); expect(extension1.extend).toMatchLog('test1'); expect(extension2.extend).not.toHaveBeenCalled(); logger.addExtension(extension2); logger.error('test2'); expect(extension1.extend).toMatchLog('test2'); expect(extension2.extend).toMatchLog('test2'); }); it('extensions can be replaced', () => { const logger = new Logger({ name: '', level: 'error', extensions: [extension1] }); logger.error('test1'); expect(extension1.extend).toMatchLog('test1'); expect(extension2.extend).not.toHaveBeenCalled(); logger.setExtensions(extension2); logger.error('test2'); expect(extension1.extend).not.toMatchLog('test2'); expect(extension2.extend).toMatchLog('test2'); }); it('extensions can change logObj', () => { const reporter = { log: jest.fn() }; const logger = new Logger({ name: '', level: 'error', extensions: [extension1, extension2], reporters: [reporter], }); logger.error('extend-test-1'); expect(extension1.extend).toMatchLog('extend-test-1'); expect(extension2.extend).toMatchLog('extend-test-1'); expect(reporter.log).toMatchLog('extend-test-1'); extension1.extend.mockImplementationOnce((logObj) => ({ ...logObj, args: ['extended'], })); logger.error('extend-test-2'); expect(extension1.extend).toMatchLog('extend-test-2'); expect(extension2.extend).not.toMatchLog('extend-test-2'); expect(extension2.extend).toMatchLog('extended'); expect(reporter.log).not.toMatchLog('extend-test-2'); expect(reporter.log).toMatchLog('extended'); }); }); describe('static methods', () => { const reporter = { log: jest.fn(), }; const logger = new Logger({ name: '', reporters: [reporter] }); beforeEach(() => { Logger.clear(); reporter.log.mockClear(); }); it('setLevel', () => { logger.info('test1'); expect(reporter.log).not.toHaveBeenCalled(); Logger.setLevel('info'); logger.info('test2'); expect(reporter.log).toMatchLog('test2'); }); it('setLevel with wrong level', () => { logger.info('test1'); expect(reporter.log).not.toHaveBeenCalled(); (Logger as any).setLevel(); logger.info('test2'); expect(reporter.log).not.toHaveBeenCalled(); Logger.setLevel('random' as any); logger.info('test2'); expect(reporter.log).not.toHaveBeenCalled(); }); it('enable/disable', () => { const childLogger1 = logger.child('l-1'); const childLogger2 = logger.child('l-2'); childLogger1.info('test1-1'); expect(reporter.log).not.toMatchLog('test1-1', 'l-1'); childLogger2.info('test1-2'); expect(reporter.log).not.toMatchLog('test1-2', 'l-2'); Logger.enable('l-1'); childLogger1.info('test2-1'); expect(reporter.log).toMatchLog('test2-1', 'l-1'); childLogger2.info('test2-2'); expect(reporter.log).not.toMatchLog('test2-2', 'l-2'); Logger.enable('warn', 'l-2'); childLogger1.info('test3-1'); expect(reporter.log).toMatchLog('test3-1', 'l-1'); childLogger2.info('test3-2'); expect(reporter.log).not.toMatchLog('test3-2', 'l-2'); childLogger1.warn('test4-1'); expect(reporter.log).toMatchLog('test4-1', 'l-1'); childLogger2.warn('test4-2'); expect(reporter.log).toMatchLog('test4-2', 'l-2'); Logger.disable('l-1'); childLogger1.warn('test5-1'); expect(reporter.log).not.toMatchLog('test5-1', 'l-1'); childLogger2.warn('test5-2'); expect(reporter.log).toMatchLog('test5-2', 'l-2'); Logger.disable('l-*'); childLogger1.error('test6-1'); expect(reporter.log).not.toMatchLog('test6-1', 'l-1'); childLogger2.error('test6-2'); expect(reporter.log).not.toMatchLog('test6-2', 'l-2'); Logger.enable('l-*'); const childLogger3 = logger.child('l-3'); childLogger3.trace('test7-1'); expect(reporter.log).toMatchLog('test7-1', 'l-3'); }); }); });
the_stack
import React, { FunctionComponent, useState } from 'react' import styled from 'styled-components' import { DashboardLayout } from '../../components/dashboard/layout' import { EuiFieldNumber } from '@tensei/eui/lib/components/form' import { EuiIcon } from '@tensei/eui/lib/components/icon' import { EuiText } from '@tensei/eui/lib/components/text' import { EuiTitle } from '@tensei/eui/lib/components/title' import { EuiButtonEmpty, EuiButton, EuiButtonIcon } from '@tensei/eui/lib/components/button' import { EuiFieldSearch } from '@tensei/eui/lib/components/form/field_search' import { EuiPopover } from '@tensei/eui/lib/components/popover' import { EuiContextMenu } from '@tensei/eui/lib/components/context_menu' import { EuiFilePicker } from '@tensei/eui/lib/components/form' import { EuiFlexItem, EuiFlexGroup, EuiFlexGrid } from '@tensei/eui/lib/components/flex' import { EuiPagination } from '@tensei/eui/lib/components/pagination' import { EuiFlyout, EuiFlyoutBody, EuiFlyoutHeader } from '@tensei/eui/lib/components/flyout' import { EuiModal } from '@tensei/eui/lib/components/modal/modal' import { EuiConfirmModal } from '@tensei/eui/lib/components/modal/confirm_modal' import { EuiCard } from '@tensei/eui/lib/components/card' import { useGeneratedHtmlId } from '@tensei/eui/lib/services/accessibility' const PageWrapper = styled.div` width: 100%; padding: 40px; margin-bottom: 20px; ` const SearchAndFilterContainer = styled.div` display: flex; width: 50%; align-items: center; justify-content: space-between; margin-top: -20px; ` const AssetPopover = styled(EuiPopover)` margin-left: 10px; ` const AssetContainer = styled.div` max-width: 100%; padding: 25px 0; ` const AssetWrapper = styled.div` display: flex; align-items: center; justify-content: flex-start; flex-wrap: wrap; gap: 1.5rem; ` const AssetCard = styled(EuiCard)` width: 220px; height: 230px; ` const AssetCardImage = styled.img` display: block; background-color: ${({ theme }) => theme.colors.bgShade}; margin-bottom: 20px; ` const NumberFieldAndPagination = styled.div` display: flex; justify-content: space-between; ` const PaginationWrapper = styled.div` display: flex; justify-content: flex-end; ` const NumberFieldWrapper = styled.div` display: flex; justify-content: flex-start; ` const FieldNumber = styled(EuiFieldNumber)` width: 65px; ` const AssetFlyout = styled(EuiFlyout)` box-shadow: none; border-left: ${({ theme }) => theme.border.thin}; ` const AssetFlyoutImage = styled.img` width: 100%; height: 25vh; margin-top: 20px; ` const FlyoutHeaderWrapper = styled.div` display: flex; justify-content: space-between; margin-top: 10px; margin-bottom: -20px; ` const FlyoutBodyContent = styled.div` display: flex; justify-content: space-between; margin-top: 10px; ` const ModalWrapper = styled(EuiModal)` padding: 30px; margin-bottom: 0; ` const ModalContentWrapper = styled.div` display: flex; justify-content: space-between; margin-top: 20px; ` const ConfirmModal = styled(EuiConfirmModal)` width: 400px; height: 230px; ` export const AssetManager: FunctionComponent = () => { const [isDestroyModalVisible, setIsDestroyModalVisible] = useState(false) const [isModalVisible, setIsModalVisible] = useState(false) const [isFlyoutVisible, setIsFlyoutVisible] = useState(false) const closeDestroyModal = () => setIsDestroyModalVisible(false) const showDestroyModal = () => setIsDestroyModalVisible(true) const closeModal = () => setIsModalVisible(false) const showModal = () => setIsModalVisible(true) const simpleFlyoutTitleId = useGeneratedHtmlId({ prefix: 'simpleFlyoutTitle' }) let destroyModal if (isDestroyModalVisible) { destroyModal = ( <ConfirmModal title="Delete Media" onCancel={closeDestroyModal} onConfirm={closeDestroyModal} cancelButtonText="Cancel" confirmButtonText="Delete" buttonColor="danger" defaultFocusedButton="confirm" > <p>Are you sure you want to delete this media?</p> </ConfirmModal> ) } let modal if (isModalVisible) { modal = ( <ModalWrapper onClose={closeModal}> <EuiFilePicker multiple initialPromptText="Select or drag and drop a file" /> <ModalContentWrapper> <EuiText>Uploaded file</EuiText> <EuiButtonIcon iconType="trash" color="danger" onClick={showDestroyModal} /> </ModalContentWrapper> {destroyModal} </ModalWrapper> ) } let flyout if (isFlyoutVisible) { flyout = ( <AssetFlyout ownFocus={false} outsideClickCloses size="s" onClose={() => setIsFlyoutVisible(false)} aria-labelledby={simpleFlyoutTitleId} > <EuiFlyoutHeader hasBorder> <AssetFlyoutImage src={ 'https://images.unsplash.com/photo-1617043593449-c881f876a4b4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTJ8fHNtYXJ0JTIwd2F0Y2h8ZW58MHx8MHx8&auto=format&fit=crop&w=500&q=60' } ></AssetFlyoutImage> <FlyoutHeaderWrapper> <EuiTitle size="xs"> <h3>Information</h3> </EuiTitle> <EuiIcon size="s" type="arrowDown" /> </FlyoutHeaderWrapper> </EuiFlyoutHeader> <EuiFlyoutBody> <FlyoutBodyContent> <EuiTitle size="xs"> <h3>Title</h3> </EuiTitle> <EuiText>Smart_watch</EuiText> </FlyoutBodyContent> <FlyoutBodyContent> <EuiTitle size="xs"> <h3>Uploaded on</h3> </EuiTitle> <EuiText>2 hours ago</EuiText> </FlyoutBodyContent> <FlyoutBodyContent> <EuiTitle size="xs"> <h3>Status</h3> </EuiTitle> <EuiText>Draft</EuiText> </FlyoutBodyContent> <FlyoutBodyContent> <EuiTitle size="xs"> <h3>Created by</h3> </EuiTitle> <EuiText>John Doe</EuiText> </FlyoutBodyContent> <FlyoutBodyContent> <EuiTitle size="xs"> <h3>Size</h3> </EuiTitle> <EuiText>2.3MB</EuiText> </FlyoutBodyContent> <FlyoutBodyContent> <EuiTitle size="xs"> <h3>Dimension</h3> </EuiTitle> <EuiText>235 x 300</EuiText> </FlyoutBodyContent> <FlyoutBodyContent> <EuiTitle size="xs"> <h3>Format</h3> </EuiTitle> <EuiText>PNG</EuiText> </FlyoutBodyContent> </EuiFlyoutBody> </AssetFlyout> ) } return ( <> <DashboardLayout.Topbar> <EuiTitle size="xs"> <h3>Asset Manager</h3> </EuiTitle> <EuiButton iconType="sortUp" fill onClick={showModal}> Upload media </EuiButton> {modal} </DashboardLayout.Topbar> <DashboardLayout.Content> <PageWrapper> <SearchAndFilterContainer> <EuiFieldSearch placeholder="Search Library" /> <AssetPopover button={ <EuiButtonEmpty iconSide="right" iconType="arrowDown"> Filters </EuiButtonEmpty> } > <EuiContextMenu initialPanelId={0}></EuiContextMenu> </AssetPopover> </SearchAndFilterContainer> <AssetContainer> <EuiFlexGrid columns={4} gutterSize="m"> <EuiFlexItem> <EuiCard textAlign="left" hasBorder image="https://source.unsplash.com/400x200/?Water" title="Elastic in Water" description="Example of a card's description. Stick to one or two sentences." // footer={cardFooterContent} /> </EuiFlexItem> <EuiFlexItem> <EuiCard textAlign="left" hasBorder image="https://source.unsplash.com/400x200/?Water" title="Elastic in Water" description="Example of a card's description. Stick to one or two sentences." // footer={cardFooterContent} /> </EuiFlexItem> <EuiFlexItem> <EuiCard textAlign="left" hasBorder image="https://source.unsplash.com/400x200/?Water" title="Elastic in Water" description="Example of a card's description. Stick to one or two sentences." // footer={cardFooterContent} /> </EuiFlexItem> <EuiFlexItem> <EuiCard textAlign="left" hasBorder image="https://source.unsplash.com/400x200/?Water" title="Elastic in Water" description="Example of a card's description. Stick to one or two sentences." // footer={cardFooterContent} /> </EuiFlexItem> <EuiFlexItem> <EuiCard textAlign="left" hasBorder image="https://source.unsplash.com/400x200/?Water" title="Elastic in Water" description="Example of a card's description. Stick to one or two sentences." // footer={cardFooterContent} /> </EuiFlexItem> <EuiFlexItem> <EuiCard textAlign="left" hasBorder image="https://source.unsplash.com/400x200/?Water" title="Elastic in Water" description="Example of a card's description. Stick to one or two sentences." // footer={cardFooterContent} /> </EuiFlexItem> <EuiFlexItem> <EuiCard textAlign="left" hasBorder image="https://source.unsplash.com/400x200/?Water" title="Elastic in Water" description="Example of a card's description. Stick to one or two sentences." // footer={cardFooterContent} /> </EuiFlexItem> <EuiFlexItem> <EuiCard textAlign="left" hasBorder image="https://source.unsplash.com/400x200/?Water" title="Elastic in Water" description="Example of a card's description. Stick to one or two sentences." // footer={cardFooterContent} /> </EuiFlexItem> </EuiFlexGrid> </AssetContainer> <NumberFieldAndPagination> <NumberFieldWrapper> <FieldNumber placeholder="10" /> </NumberFieldWrapper> <PaginationWrapper> <EuiPagination aria-label="Many pages example" /> </PaginationWrapper> </NumberFieldAndPagination> </PageWrapper> </DashboardLayout.Content> </> ) }
the_stack
import type { AtomicHub } from "@effect/core/io/Hub/operations/_internal/AtomicHub" import type { Subscription } from "@effect/core/io/Hub/operations/_internal/Subscription" import { unsafeCompleteDeferred } from "@effect/core/io/Hub/operations/_internal/unsafeCompleteDeferred" import { unsafeOfferAll } from "@effect/core/io/Hub/operations/_internal/unsafeOfferAll" import { unsafePollAllQueue } from "@effect/core/io/Hub/operations/_internal/unsafePollAllQueue" /** * A `Strategy<A>` describes the protocol for how publishers and subscribers * will communicate with each other through the hub. * * @tsplus type ets/Hub/Strategy */ export interface Strategy<A> { /** * Describes how publishers should signal to subscribers that they are * waiting for space to become available in the hub. */ readonly handleSurplus: ( hub: AtomicHub<A>, subscribers: MutableHashSet<Tuple<[Subscription<A>, MutableQueue<Deferred<never, A>>]>>, as: Collection<A>, isShutdown: AtomicBoolean ) => Effect.UIO<boolean> /** * Describes any finalization logic associated with this strategy. */ readonly shutdown: Effect.UIO<void> /** * Describes how subscribers should signal to publishers waiting for space * to become available in the hub that space may be available. */ readonly unsafeOnHubEmptySpace: ( hub: AtomicHub<A>, subscribers: MutableHashSet<Tuple<[Subscription<A>, MutableQueue<Deferred<never, A>>]>> ) => void /** * Describes how subscribers waiting for additional values from the hub * should take those values and signal to publishers that they are no * longer waiting for additional values. */ readonly unsafeCompletePollers: ( hub: AtomicHub<A>, subscribers: MutableHashSet<Tuple<[Subscription<A>, MutableQueue<Deferred<never, A>>]>>, subscription: Subscription<A>, pollers: MutableQueue<Deferred<never, A>> ) => void /** * Describes how publishers should signal to subscribers waiting for * additional values from the hub that new values are available. */ readonly unsafeCompleteSubscribers: ( hub: AtomicHub<A>, subscribers: MutableHashSet<Tuple<[Subscription<A>, MutableQueue<Deferred<never, A>>]>> ) => void } /** * @tsplus type ets/Hub/StrategyOps */ export interface StrategyOps {} export const Strategy: StrategyOps = {} abstract class BaseStrategy<A> implements Strategy<A> { abstract handleSurplus( hub: AtomicHub<A>, subscribers: MutableHashSet<Tuple<[Subscription<A>, MutableQueue<Deferred<never, A>>]>>, as: Collection<A>, isShutdown: AtomicBoolean ): Effect.UIO<boolean> abstract shutdown: Effect.UIO<void> abstract unsafeOnHubEmptySpace( hub: AtomicHub<A>, subscribers: MutableHashSet<Tuple<[Subscription<A>, MutableQueue<Deferred<never, A>>]>> ): void unsafeCompletePollers( hub: AtomicHub<A>, subscribers: MutableHashSet<Tuple<[Subscription<A>, MutableQueue<Deferred<never, A>>]>>, subscription: Subscription<A>, pollers: MutableQueue<Deferred<never, A>> ): void { let keepPolling = true while (keepPolling && !subscription.isEmpty()) { const poller = pollers.poll(EmptyMutableQueue)! if (poller === EmptyMutableQueue) { const subPollerPair = Tuple(subscription, pollers) subscribers.remove(subPollerPair) if (pollers.isEmpty) { keepPolling = false } else { subscribers.add(subPollerPair) } } else { const pollResult = subscription.poll(EmptyMutableQueue) if (pollResult == EmptyMutableQueue) { unsafeOfferAll(pollers, unsafePollAllQueue(pollers).prepend(poller)) } else { unsafeCompleteDeferred(poller, pollResult) this.unsafeOnHubEmptySpace(hub, subscribers) } } } } unsafeCompleteSubscribers( hub: AtomicHub<A>, subscribers: MutableHashSet<Tuple<[Subscription<A>, MutableQueue<Deferred<never, A>>]>> ): void { for ( const { tuple: [subscription, pollers] } of subscribers ) { this.unsafeCompletePollers(hub, subscribers, subscription, pollers) } } } /** * A strategy that applies back pressure to publishers when the hub is at * capacity. This guarantees that all subscribers will receive all messages * published to the hub while they are subscribed. However, it creates the * risk that a slow subscriber will slow down the rate at which messages * are published and received by other subscribers. */ export class BackPressure<A> extends BaseStrategy<A> { publishers: MutableQueue<readonly [A, Deferred<never, boolean>, boolean]> = MutableQueue.unbounded() handleSurplus( hub: AtomicHub<A>, subscribers: MutableHashSet<Tuple<[Subscription<A>, MutableQueue<Deferred<never, A>>]>>, as: Collection<A>, isShutdown: AtomicBoolean ): Effect.UIO<boolean> { return Effect.suspendSucceedWith((_, fiberId) => { const deferred: Deferred<never, boolean> = Deferred.unsafeMake<never, boolean>(fiberId) return Effect.suspendSucceed(() => { this.unsafeOffer(as, deferred) this.unsafeOnHubEmptySpace(hub, subscribers) this.unsafeCompleteSubscribers(hub, subscribers) return isShutdown.get ? Effect.interrupt : deferred.await() }).onInterrupt(() => Effect.succeed(this.unsafeRemove(deferred))) }) } get shutdown(): Effect.UIO<void> { return Effect.Do() .bind("fiberId", () => Effect.fiberId) .bind("publishers", () => Effect.succeed(unsafePollAllQueue(this.publishers))) .tap(({ fiberId, publishers }) => Effect.forEachParDiscard( publishers, ([_, deferred, last]) => last ? deferred.interruptAs(fiberId) : Effect.unit ) ) .asUnit() } unsafeOnHubEmptySpace( hub: AtomicHub<A>, subscribers: MutableHashSet<Tuple<[Subscription<A>, MutableQueue<Deferred<never, A>>]>> ): void { let keepPolling = true while (keepPolling && !hub.isFull()) { const publisher = this.publishers.poll(EmptyMutableQueue)! if (publisher === EmptyMutableQueue) { keepPolling = false } else { const published = hub.publish(publisher[0]) if (published && publisher[2]) { unsafeCompleteDeferred(publisher[1], true) } else if (!published) { unsafeOfferAll( this.publishers, unsafePollAllQueue(this.publishers).prepend(publisher) ) } this.unsafeCompleteSubscribers(hub, subscribers) } } } private unsafeOffer(as: Collection<A>, deferred: Deferred<never, boolean>): void { const it = as[Symbol.iterator]() let curr = it.next() if (!curr.done) { let next while ((next = it.next()) && !next.done) { this.publishers.offer([curr.value, deferred, false] as const) curr = next } this.publishers.offer([curr.value, deferred, true] as const) } } private unsafeRemove(deferred: Deferred<never, boolean>): void { unsafeOfferAll( this.publishers, unsafePollAllQueue(this.publishers).filter(([_, a]) => a !== deferred) ) } } /** * A strategy that drops new messages when the hub is at capacity. This * guarantees that a slow subscriber will not slow down the rate at which * messages are published. However, it creates the risk that a slow * subscriber will slow down the rate at which messages are received by * other subscribers and that subscribers may not receive all messages * published to the hub while they are subscribed. */ export class Dropping<A> extends BaseStrategy<A> { handleSurplus( _hub: AtomicHub<A>, _subscribers: MutableHashSet<Tuple<[Subscription<A>, MutableQueue<Deferred<never, A>>]>>, _as: Collection<A>, _isShutdown: AtomicBoolean ): Effect.UIO<boolean> { return Effect.succeed(false) } shutdown: Effect.UIO<void> = Effect.unit unsafeOnHubEmptySpace( _hub: AtomicHub<A>, _subscribers: MutableHashSet<Tuple<[Subscription<A>, MutableQueue<Deferred<never, A>>]>> ): void { // } } /** * A strategy that adds new messages and drops old messages when the hub is * at capacity. This guarantees that a slow subscriber will not slow down * the rate at which messages are published and received by other * subscribers. However, it creates the risk that a slow subscriber will * not receive some messages published to the hub while it is subscribed. */ export class Sliding<A> extends BaseStrategy<A> { private unsafeSlidingPublish(hub: AtomicHub<A>, as: Collection<A>): void { const it = as[Symbol.iterator]() let next = it.next() if (!next.done && hub.capacity > 0) { let a = next.value let loop = true while (loop) { hub.slide() const pub = hub.publish(a) if (pub && (next = it.next()) && !next.done) { a = next.value } else if (pub) { loop = false } } } } handleSurplus( hub: AtomicHub<A>, subscribers: MutableHashSet<Tuple<[Subscription<A>, MutableQueue<Deferred<never, A>>]>>, as: Collection<A>, _isShutdown: AtomicBoolean ): Effect.UIO<boolean> { return Effect.succeed(() => { this.unsafeSlidingPublish(hub, as) this.unsafeCompleteSubscribers(hub, subscribers) return true }) } shutdown: Effect.UIO<void> = Effect.unit unsafeOnHubEmptySpace( _hub: AtomicHub<A>, _subscribers: MutableHashSet<Tuple<[Subscription<A>, MutableQueue<Deferred<never, A>>]>> ): void { // } } /** * @tsplus static ets/Hub/StrategyOps BackPressure */ export function backPressureStrategy<A>(): Strategy<A> { return new BackPressure<A>() } /** * @tsplus static ets/Hub/StrategyOps Dropping */ export function droppingStrategy<A>(): Strategy<A> { return new Dropping<A>() } /** * @tsplus static ets/Hub/StrategyOps Sliding */ export function slidingStrategy<A>(): Strategy<A> { return new Sliding<A>() }
the_stack
import ESTree from 'estree' import { Tree } from './Tree' import { NodeTypes } from './ast' import { Context, LLVMContext, X86Context } from '../environment/context' import { Kind } from '../environment/Environment' import { get_X86_MASM_Math_Logic_Map, get_X86_MASM_SysCall_Map, identifierCompile } from '../backend/x86Assemble' import { opAcMap } from './util' import { LLVMNamePointer } from '../environment/LLVM-Environment' import { llvmIdentifierCompile, get_LLVM_SysCall_Map} from '../backend/llvmAssemble' const X86_MASM_Math_Logic_Map = get_X86_MASM_Math_Logic_Map(dispatchExpressionCompile) const X86_MASM_SysCall_Map = get_X86_MASM_SysCall_Map(dispatchExpressionCompile) const LLVM_SysCall_Map = get_LLVM_SysCall_Map(dispatchExpressionLLVMCompile) const nullFn = () => { console.log('Null function called!!!') } const internal = { console } export class Literal extends Tree { ast!: ESTree.Literal constructor(ast: ESTree.Literal) { super(ast) } toCode(): string { if (this.ast.value) { return this.ast.value.toString(); } return '' } evaluate() { return this.ast.value } compile(context: X86Context, depth: number = 0) { if (Number.isInteger(this.ast.value)) { context.emit(depth, `PUSH ${this.ast.value}`); } } llvmCompile(context: LLVMContext, useNamePointer: LLVMNamePointer) { // If numeric literal, store to useNamePointer register by adding 0. if (Number.isInteger(this.ast.value)) { context.emit(1, `%${useNamePointer.value} = add i64 ${this.ast.value}, 0`); } } } export class Identifier extends Tree { constructor(ast: ESTree.Identifier) { super(ast) } toCode(): string { return this.ast.name } evaluate(context: Context) { return context.env.get(this.ast.name) } compile(context: X86Context, depth: number = 0) { identifierCompile(this.ast, context, depth) } llvmCompile(context: LLVMContext, useNamePointer: LLVMNamePointer) { llvmIdentifierCompile(this.ast, context, useNamePointer) } } export class BinaryExpression extends Tree { ast!: ESTree.BinaryExpression; constructor(ast: ESTree.BinaryExpression) { super(ast) } evaluate(context: Context): boolean | number { return opAcMap[this.ast.operator](dispatchExpressionEvaluation(this.ast.left, context), dispatchExpressionEvaluation(this.ast.right, context)) } compile(context: X86Context, depth: number = 0) { return X86_MASM_Math_Logic_Map[this.ast.operator](this.ast, context, depth) } llvmCompile(context: LLVMContext, resultNamePointer: LLVMNamePointer) { let llvmOperatorMap = { '+': 'add', '-': 'sub', '*': 'mul', '/': 'udiv', '%': 'urem', '<': 'icmp slt', '>': 'icmp sgt', '==': 'icmp eq', '===': 'icmp eq', }; const arg1 = context.env.scope.symbol(); const arg2 = context.env.scope.symbol(); dispatchExpressionLLVMCompile(this.ast.left, context, arg1) dispatchExpressionLLVMCompile(this.ast.right, context, arg2) context.emit( 1, `%${resultNamePointer.value} = ${llvmOperatorMap[this.ast.operator]} ${arg1.type} %${arg1.value}, %${arg2.value}`); } } export class AssignmentExpression extends Tree { ast!: ESTree.AssignmentExpression constructor(ast: ESTree.AssignmentExpression) { super(ast) } toCode(): string { return 'assignment expression code!' } evaluate(context: Context) { if (this.ast.operator === '=') { context.env.def((<ESTree.Identifier>this.ast.left).name, dispatchExpressionEvaluation(this.ast.right, context)) } } } export class UpdateExpression extends Tree { ast!: ESTree.UpdateExpression constructor(ast: ESTree.UpdateExpression) { super(ast) } toCode(): string { return 'UpdateExpression code!' } evaluate(context: Context) { if (this.ast.operator === '++') { if (this.ast.argument.type === NodeTypes.Identifier) { context.env.def(this.ast.argument.name, context.env.get(this.ast.argument.name) + 1) } } } } export class MemberExpression extends Tree { ast!: ESTree.MemberExpression constructor(ast: ESTree.MemberExpression) { super(ast) } toCode(): string { let code: string = '' switch (this.ast.object.type) { case NodeTypes.Identifier: code += new Identifier(this.ast.object).toCode() } if (this.ast.property) { code += '.'; switch (this.ast.property.type) { case NodeTypes.Identifier: code += new Identifier(this.ast.property).toCode() } } return code; } evaluate(): Function { if (this.ast.object.type === NodeTypes.Identifier) { if (this.ast.property.type === NodeTypes.Identifier) { return internal[this.ast.object.name][this.ast.property.name] } } return nullFn } compile(context: X86Context, depth: number = 0) { } } export class CallExpression extends Tree { ast!: ESTree.CallExpression constructor(ast: ESTree.CallExpression) { super(ast) } toCode() { let code = '' switch (this.ast.callee.type) { case NodeTypes.MemberExpression: code += new MemberExpression(this.ast.callee).toCode(); break; default: throw Error('[toCode] unsupported callee type: ' + this.ast.callee.type) } code += '(' this.ast.arguments.forEach((arg) => { switch (arg.type) { case NodeTypes.Literal: code += new Literal(arg).toCode() } }); code += ')' return code; } evaluate(context: Context) { function transformArgs(args: ESTree.CallExpression['arguments'], context: Context) { return args.map((arg) => { return dispatchExpressionEvaluation(arg as ESTree.Expression, context) }) } let fn: Function = nullFn, { callee } = this.ast switch (callee.type) { case NodeTypes.MemberExpression: fn = new MemberExpression(callee).evaluate(); break; case NodeTypes.Identifier: fn = context.env.get(callee.name, Kind.FunctionDeclaration); break; } fn.apply(null, transformArgs(this.ast.arguments, context)) let ret = context.env.getReturnValue() return ret } compile(context: X86Context, depth: number = 0) { function compileCall(ast: ESTree.CallExpression, context: X86Context, depth: number = 0) { let args = ast.arguments, scope = context.env, fun = ast.callee.type === NodeTypes.Identifier ? ast.callee.name : 'undefined-function'; // Compile registers and save on the stack args.map((arg) => dispatchExpressionCompile(arg, context, depth)); const fn = scope.lookup(fun); if (fn) { context.emit(depth, `CALL ${fn.name}`); } else { throw new Error('Attempt to call undefined function: ' + fun); } if (args.length > 1) { /** * Drop the args * reset stack pointer */ context.emit(depth, `ADD RSP, ${args.length * 8}`); } if (args.length === 1) { context.emit(depth, `MOV [RSP], RAX\n`); } else { context.emit(depth, 'PUSH RAX\n'); } } switch (this.ast.callee.type) { case NodeTypes.Identifier: return compileCall(this.ast, context, depth) case NodeTypes.MemberExpression: return X86_MASM_SysCall_Map[new MemberExpression(this.ast.callee).toCode()](this.ast, context, depth); default: throw Error(`Unsupported callee type ${this.ast.callee.type} compile`); } } llvmCompile(context: LLVMContext, resultNamePointer: LLVMNamePointer) { /** * Todos enable tail call optimization * reference: https://llvm.org/docs/LangRef.html#call-instruction */ function llvmCompileCall(ast: ESTree.CallExpression, context: LLVMContext, tempNamePointer: LLVMNamePointer) { let args = ast.arguments, fun = ast.callee.type === NodeTypes.Identifier ? ast.callee.name : 'undefined-function'; const funcNamePointer = context.env.scope.get(fun); if (funcNamePointer) { const safeArgs: string = args .map((expr) => { const useNamePointer: LLVMNamePointer = context.env.scope.symbol(); dispatchExpressionLLVMCompile(expr, context, useNamePointer); return `${useNamePointer.type} %` + useNamePointer.value; }) .join(', '); const isTailCall = context.env.tail_call_enabled && context.env.tailCallTree.includes(funcNamePointer.value); const maybeTail = isTailCall ? 'tail ' : ''; let assign = funcNamePointer.type !== 'void' ? `%${tempNamePointer.value} = ` : '' if(!assign){ tempNamePointer.type = 'void' } context.emit( 1, `${assign}${maybeTail}call ${funcNamePointer.type} @${funcNamePointer.value}(${safeArgs})`, ); // if (isTailCall) { // context.emit(1, `ret ${retNamePointer.type} %${retNamePointer.value}`); // } } else { throw new Error('Attempt to call undefined function: ' + fun); } } switch (this.ast.callee.type) { case NodeTypes.Identifier: return llvmCompileCall(this.ast, context, resultNamePointer); case NodeTypes.MemberExpression: return LLVM_SysCall_Map[new MemberExpression(this.ast.callee).toCode()](this.ast, context, resultNamePointer);; default: throw Error(`Unsupported callee type ${this.ast.callee.type} compile`); } } } export class ExpressionStatement extends Tree { constructor(ast: ESTree.ExpressionStatement) { super(ast) } toCode(): string { let code = '' switch (this.ast.expression.type) { case 'CallExpression': code += new CallExpression(this.ast.expression).toCode(); break; } return code; } evaluate(context: Context) { return dispatchExpressionEvaluation(this.ast.expression, context) } compile(context: X86Context, depth: number = 0) { return dispatchExpressionCompile(this.ast.expression, context, depth) } llvmCompile(context: LLVMContext, namePointer: LLVMNamePointer) { return dispatchExpressionLLVMCompile(this.ast.expression, context, namePointer) } } export function dispatchExpressionEvaluation(expression: ESTree.Expression, context: Context): any { switch (expression.type) { case NodeTypes.Identifier: return new Identifier(expression).evaluate(context) case NodeTypes.Literal: return new Literal(expression).evaluate() case NodeTypes.BinaryExpression: return new BinaryExpression(expression).evaluate(context) case NodeTypes.CallExpression: return new CallExpression(expression).evaluate(context) case NodeTypes.AssignmentExpression: return new AssignmentExpression(expression).evaluate(context) case NodeTypes.UpdateExpression: return new UpdateExpression(expression).evaluate(context) default: throw Error('Unsupported expression ' + expression) } } export function dispatchExpressionCompile(expression: ESTree.Expression | ESTree.SpreadElement, context: X86Context, depth: number = 0) { switch (expression.type) { case NodeTypes.Identifier: return new Identifier(expression).compile(context, depth); case NodeTypes.Literal: return new Literal(expression).compile(context, depth); case NodeTypes.BinaryExpression: return new BinaryExpression(expression).compile(context, depth); case NodeTypes.CallExpression: return new CallExpression(expression).compile(context, depth) // case NodeTypes.AssignmentExpression: return new AssignmentExpression(expression).evaluate(context) // case NodeTypes.UpdateExpression: return new UpdateExpression(expression).evaluate(context) default: throw Error('Unsupported expression ' + expression) } } export function dispatchExpressionLLVMCompile(expression: ESTree.Expression | ESTree.SpreadElement, context: LLVMContext, namePointer: LLVMNamePointer) { switch (expression.type) { case NodeTypes.Identifier: return new Identifier(expression).llvmCompile(context, namePointer); case NodeTypes.Literal: return new Literal(expression).llvmCompile(context, namePointer); case NodeTypes.BinaryExpression: return new BinaryExpression(expression).llvmCompile(context, namePointer); case NodeTypes.CallExpression: return new CallExpression(expression).llvmCompile(context, namePointer) // case NodeTypes.AssignmentExpression: return new AssignmentExpression(expression).evaluate(context) // case NodeTypes.UpdateExpression: return new UpdateExpression(expression).evaluate(context) default: throw Error('Unsupported expression ' + expression) } }
the_stack
import {AcceleratedFuzzyMatcher, FuzzyMatcher} from "../../ts/matchers" import {StringDistance,EnPhoneticDistance,EnHybridDistance} from "../../ts/distance" const targetStrings = [ "Andrew Smith", "Andrew", "John B", "John C", "Jennifer", ]; interface TestContact { firstName: string; lastName: string; tele?: string; } const targets: Array<TestContact> = [ { firstName: "Andrew", lastName: "Smith", tele: "1234567", }, { firstName: "Andrew", lastName: "", }, { firstName: "John", lastName: "B", tele: "7654321", }, { firstName: "John", lastName: "C", tele: "2222222", }, { firstName: "Jennifer", lastName: "", } ]; const stringDistance = new StringDistance(); function adjustThreshold(query: string, threshold: number) { return threshold*query.length; } function simpleDistance(a: TestContact|string, b: TestContact|string) { let stringA: string; let stringB: string; if (typeof a === "string") { stringA = a; } else { stringA = a.firstName + a.lastName; } if (typeof b === "string") { stringB = b; } else { stringB = b.firstName + b.lastName; } const distance = stringDistance.distance(stringA, stringB); return distance; } describe("FuzzyMatcher", () => { test("Fuzzy matcher similar match.", () => { const matcher = new FuzzyMatcher(targetStrings, simpleDistance); expect(matcher.nearest("andru").element).toBe("Andrew"); }); test("Fuzzy matcher lower case match.", () => { const matcher = new FuzzyMatcher(targetStrings, simpleDistance); expect(matcher.nearest("andrew smith").element).toBe("Andrew Smith"); }); test("nearestWithin empty.", () => { const matcher = new FuzzyMatcher(targetStrings, simpleDistance); expect(matcher.nearestWithin("", 0.35)).toBeUndefined(); }); test("with StringDistance", () => { const matcher = new FuzzyMatcher(targetStrings, new StringDistance()); // case sensitive, "john b" is the same distance to "John B" and "John C". expect(matcher.nearest("john B").element).toBe("John B"); }); test("with StringDistance and extractor", () => { const matcher = new FuzzyMatcher(targets, new StringDistance(), (target) => `${target.firstName} ${target.lastName}`); expect(matcher.nearest("john B").element).toEqual(expect.objectContaining({ firstName: "John", lastName: "B", tele: "7654321", })); }); test("with EnPhoneticDistance", () => { const matcher = new FuzzyMatcher(targetStrings, new EnPhoneticDistance()); expect(matcher.nearest("john bee").element).toBe("John B"); }); test("with EnHybridDistance", () => { const matcher = new FuzzyMatcher(targetStrings, new EnHybridDistance(0.7)); expect(matcher.nearest("john bee").element).toBe("John B"); }); test("kNearest john.", () => { const matcher = new FuzzyMatcher(targetStrings, simpleDistance); const results = matcher.kNearest("john", 2); expect(results.length).toBe(2); expect(results).toEqual(expect.arrayContaining([ expect.objectContaining({ element: expect.stringContaining("John B"), distance: expect.any(Number) }), expect.objectContaining({ element: expect.stringContaining("John C"), distance: expect.any(Number) }) ])) }); test("kNearestWithin john.", () => { const matcher = new FuzzyMatcher(targetStrings, simpleDistance); const query = "john"; const threshold = adjustThreshold(query, 0.8); const results = matcher.kNearestWithin(query, 4, threshold); expect(results.length).toBe(2); expect(results).toEqual(expect.arrayContaining([ expect.objectContaining({ element: expect.stringContaining("John B"), distance: { asymmetricMatch: (other: any): boolean => { expect(other).toBeLessThan(threshold) return true; } } }), expect.objectContaining({ element: expect.stringContaining("John C"), distance: { asymmetricMatch: (other: any): boolean => { expect(other).toBeLessThan(threshold) return true; } } }) ])) }); test("limit 0 exact match", () => { const matcher = new FuzzyMatcher(targetStrings, simpleDistance); expect(matcher.nearestWithin("John C", 0).element).toBe("John C"); }); test("Fuzzy matcher (objects).", () => { const matcher = new FuzzyMatcher(targets, simpleDistance); expect(matcher.nearest("andrew smith").element).toEqual(expect.objectContaining({ firstName: "Andrew", lastName: "Smith", tele: "1234567", })); }); test("ctor used as function exception.", () => { expect(() => { const matcher = (FuzzyMatcher as any)(targets); }).toThrow(); }); test("Pronouncing undefined exception.", () => { expect(() => { const matcher = new FuzzyMatcher(targets, simpleDistance); matcher.nearest(undefined as any); }).toThrow(); }); }); describe("AcceleratedMatchers.FuzzyMatcher", () => { test("Accelerated Fuzzy matcher similar match.", () => { const matcher = new AcceleratedFuzzyMatcher(targetStrings, simpleDistance); expect(matcher.nearest("andru").element).toBe("Andrew"); }); test("Accelerated Fuzzy matcher lower case match.", () => { const matcher = new AcceleratedFuzzyMatcher(targetStrings, simpleDistance); expect(matcher.nearest("andrew smith").element).toBe("Andrew Smith"); }); test("nearestWithin empty.", () => { const matcher = new AcceleratedFuzzyMatcher(targetStrings, simpleDistance); const results = matcher.nearestWithin("", 0.35); expect(results).toBeUndefined(); }); test("with StringDistance", () => { const matcher = new AcceleratedFuzzyMatcher(targetStrings, new StringDistance()); // case sensitive, "john b" is the same distance to "John B" and "John C". expect(matcher.nearest("john B").element).toBe("John B"); }); test("with StringDistance and extractor", () => { const matcher = new AcceleratedFuzzyMatcher(targets, new StringDistance(), (target) => `${target.firstName} ${target.lastName}`); expect(matcher.nearest("john B").element).toEqual(expect.objectContaining({ firstName: "John", lastName: "B", tele: "7654321", })); }); test("with EnPhoneticDistance", () => { const matcher = new AcceleratedFuzzyMatcher(targetStrings, new EnPhoneticDistance()); expect(matcher.nearest("john bee").element).toBe("John B"); }); test("with EnHybridDistance", () => { const matcher = new AcceleratedFuzzyMatcher(targetStrings, new EnHybridDistance(0.7)); expect(matcher.nearest("john bee").element).toBe("John B"); }); test("kNearest john.", () => { const matcher = new AcceleratedFuzzyMatcher(targetStrings, simpleDistance); const results = matcher.kNearest("john", 2); expect(results.length).toBe(2); expect(results).toEqual(expect.arrayContaining([ expect.objectContaining({ element: expect.stringContaining("John B"), distance: expect.any(Number) }), expect.objectContaining({ element: expect.stringContaining("John C"), distance: expect.any(Number) }) ])) }); test("kNearestWithin john.", () => { const matcher = new AcceleratedFuzzyMatcher(targetStrings, simpleDistance); const query = "john"; const threshold = adjustThreshold(query, 0.8); const results = matcher.kNearestWithin(query, 4, threshold); expect(results.length).toBe(2); expect(results).toEqual(expect.arrayContaining([ expect.objectContaining({ element: expect.stringContaining("John B"), distance: { asymmetricMatch: (other: any): boolean => { expect(other).toBeLessThan(threshold) return true; } } }), expect.objectContaining({ element: expect.stringContaining("John C"), distance: { asymmetricMatch: (other: any): boolean => { expect(other).toBeLessThan(threshold) return true; } } }) ])) }); test("limit 0 exact match", () => { const matcher = new AcceleratedFuzzyMatcher(targetStrings, simpleDistance); expect(matcher.nearestWithin("John C", 0).element).toBe("John C"); }); test("Accelerated Fuzzy matcher (objects).", () => { const matcher = new AcceleratedFuzzyMatcher(targets, simpleDistance); expect(matcher.nearest("andrew smith").element).toEqual(expect.objectContaining({ firstName: "Andrew", lastName: "Smith", tele: "1234567", })); }); test("ctor used as function exception.", () => { expect(() => { const matcher = (AcceleratedFuzzyMatcher as any)(targets); }).toThrow(); }); test("Pronouncing undefined exception.", () => { expect(() => { const matcher = new AcceleratedFuzzyMatcher(targets, simpleDistance); matcher.nearest(undefined as any); }).toThrow(); }); });
the_stack
import { ColonyClient, ClientType, ExtensionClient, MotionState as NetworkMotionState, } from '@colony/colony-js'; import { bigNumberify, BigNumberish, hexStripZeros } from 'ethers/utils'; import { AddressZero } from 'ethers/constants'; import ColonyManagerClass from '~lib/ColonyManager'; import { ColonyActions, ColonyMotions, motionNameMapping, ColonyAndExtensionsEvents, Address, FormattedAction, ActionUserRoles, } from '~types/index'; import { ParsedEvent } from '~data/index'; import { ProcessedEvent } from '~data/resolvers/colonyActions'; import { ACTIONS_EVENTS, EVENTS_REQUIRED_FOR_ACTION, } from '~dashboard/ActionsPage'; import ipfs from '~context/ipfsWithFallbackContext'; import { log } from '~utils/debug'; import { getMotionRequiredStake, MotionState } from '../colonyMotions'; import { availableRoles } from '~dashboard/PermissionManagementDialog'; interface ActionValues { recipient: Address; amount: string; tokenAddress: Address; fromDomain: number; toDomain: number; oldVersion: string; newVersion: string; address: Address; roles: ActionUserRoles[]; } interface MotionValues extends ActionValues { motionNAYStake: string; motionState: MotionState; actionInitiator: string; motionDomain: number; rootHash: string; domainName: string | null; domainColor: number | null; domainPurpose: string | null; } export * from './subgraphEvents'; export * from './getAnnotationFromSubgraph'; /* * @TODO Helpers in here need to be refactored so bad... * Hope we can get a break at some point and tackle this type of stuff */ /* * Main logic for detecting a action type based on an array of "required" events */ export const getActionType = ( processedEvents: ProcessedEvent[], ): ColonyActions => { const potentialActions = {}; Object.values(EVENTS_REQUIRED_FOR_ACTION).map( (eventsWithPositions, index) => { /* * Filter the events by just the "required" ones */ const filteredParsedEvents = processedEvents.filter(({ name }) => eventsWithPositions?.includes(name), ); /* * Add to the potential actions object, both the key * and the reduced truthy/falsy value */ potentialActions[ Object.keys(EVENTS_REQUIRED_FOR_ACTION)[index] ] = eventsWithPositions ?.map((eventName, eventIndex) => { /* * Check the existance of the event */ if (filteredParsedEvents[eventIndex]) { /* * Check the correct position in the events chain */ return filteredParsedEvents[eventIndex].name === eventName; } return false; }) /* * Reduce the array of boleans to a single value */ .every((event) => !!event); return null; }, ); /* * Check if we have a possible action (the first object key that is true) */ const [potentialAction] = Object.keys(potentialActions).filter( (actionName) => potentialActions[actionName], ); return (potentialAction as ColonyActions) || ColonyActions.Generic; }; export const getAllAvailableClients = async ( colonyAddress?: Address, colonyManager?: ColonyManagerClass, ) => { if (colonyAddress && colonyManager) { return ( await Promise.all( Object.values(ClientType).map(async (clientType) => { try { return await colonyManager.getClient(clientType, colonyAddress); } catch (error) { return undefined; } }), ) ).filter((clientType) => !!clientType); } return []; }; /* * Get the events to list on the action's page, based on a map */ export const getEventsForActions = ( events: ParsedEvent[], actionType: ColonyActions | ColonyMotions, ): ParsedEvent[] => [ ...((ACTIONS_EVENTS[actionType] as ColonyAndExtensionsEvents[]) || []) ?.map((event) => events.filter(({ name }) => name === event)) .flat(), ]; export const formatEventName = ( rawEventName: string, ): ColonyAndExtensionsEvents => rawEventName.split('(')[0] as ColonyAndExtensionsEvents; const getPaymentActionValues = async ( processedEvents: ProcessedEvent[], colonyClient: ColonyClient, ): Promise<Partial<ActionValues>> => { /* * Get the additional events to fetch values from * * We don't have to worry about these events existing, as long as this * is an action event, these events will exist */ const oneTxPaymentEvent = processedEvents.find( ({ name }) => name === ColonyAndExtensionsEvents.OneTxPaymentMade, ) as ProcessedEvent; const paymentAddedEvent = processedEvents.find( ({ name }) => name === ColonyAndExtensionsEvents.PaymentAdded, ) as ProcessedEvent; const payoutClaimedEvent = processedEvents.find( ({ name }) => name === ColonyAndExtensionsEvents.PayoutClaimed, ) as ProcessedEvent; /* * Get the payment details from the payment id */ const { values: { paymentId }, } = paymentAddedEvent; /* * Fetch the rest of the values that are present directly in the events */ const { values: { amount: paymentAmount, token }, } = payoutClaimedEvent; /* * Get the agent value */ const { address, values: { agent }, } = oneTxPaymentEvent; const paymentDetails = await colonyClient.getPayment(paymentId); const fromDomain = bigNumberify(paymentDetails.domainId || 1).toNumber(); const recipient = paymentDetails.recipient || AddressZero; const paymentActionValues: { amount: string; tokenAddress: Address; fromDomain: number; recipient: Address; actionInitiator?: string; address: Address; } = { amount: bigNumberify(paymentAmount || '0').toString(), tokenAddress: token || AddressZero, fromDomain, recipient, address, }; if (agent) { paymentActionValues.actionInitiator = agent; } return paymentActionValues; }; const getDomainValuesFromIPFS = async (ipfsHash: string) => { let ipfsMetadata: any = null; let domainName = null; let domainColor = null; let domainPurpose = null; try { ipfsMetadata = await ipfs.getString(ipfsHash); } catch (error) { log.verbose( 'Could not fetch IPFS metadata for domain with hash:', ipfsHash, ); } try { if (ipfsMetadata) { const domainMetadata = JSON.parse(ipfsMetadata); domainName = domainMetadata.domainName; domainColor = domainMetadata.domainColor || null; domainPurpose = domainMetadata.domainPurpose || null; } } catch (error) { log.verbose( `Could not parse IPFS metadata for domain, using hash:`, ipfsHash, 'with object:', ipfsMetadata, ); } const domainValues: { domainName: string | null; domainColor: number | null; domainPurpose: string | null; } = { domainName, domainColor, domainPurpose, }; return domainValues; }; const getMoveFundsActionValues = async ( processedEvents: ProcessedEvent[], colonyClient: ColonyClient, ): Promise<Partial<ActionValues>> => { /* * Get the move funds event to fetch values from * * We don't have to worry about the event existing, as long as this * is an move funds event, these events will exist */ const moveFundsEvent = processedEvents.find( ({ name }) => name === ColonyAndExtensionsEvents.ColonyFundsMovedBetweenFundingPots, ) as ProcessedEvent; /* * Fetch the rest of the values that are present directly in the event */ const { address, values: { amount, fromPot, toPot, token, agent }, } = moveFundsEvent; /* * Fetch the domain ids from their respective pot ids */ const fromDomain = await colonyClient.getDomainFromFundingPot(fromPot); const toDomain = await colonyClient.getDomainFromFundingPot(toPot); const moveFundsActionValues: { amount: string; tokenAddress: Address; fromDomain: number; toDomain: number; actionInitiator?: string; address: Address; } = { amount: bigNumberify(amount || '0').toString(), tokenAddress: token || AddressZero, fromDomain: bigNumberify(fromDomain || '1').toNumber(), toDomain: bigNumberify(toDomain || '1').toNumber(), address, }; if (agent) { moveFundsActionValues.actionInitiator = agent; } return moveFundsActionValues; }; const getMintTokensActionValues = async ( processedEvents: ProcessedEvent[], colonyClient: ColonyClient, ): Promise<Partial<ActionValues>> => { const mintTokensEvent = processedEvents.find( ({ name }) => name === ColonyAndExtensionsEvents.TokensMinted, ) as ProcessedEvent; const tokenAddress = await colonyClient.getToken(); const { address, values: { who, amount, agent }, } = mintTokensEvent; const tokensMintedValues: { amount: string; tokenAddress: Address; actionInitiator?: string; recipient: Address; address: Address; } = { amount: bigNumberify(amount || '0').toString(), recipient: who, tokenAddress, address, }; if (agent) { tokensMintedValues.actionInitiator = agent; } return tokensMintedValues; }; const getCreateDomainActionValues = async ( processedEvents: ProcessedEvent[], ): Promise<Partial<ActionValues>> => { const domainAddedEvent = processedEvents.find( ({ name }) => name === ColonyAndExtensionsEvents.DomainAdded, ) as ProcessedEvent; const { address, values: { agent }, } = domainAddedEvent; const domainAction: { address: Address; fromDomain: number; actionInitiator?: string; } = { address, fromDomain: parseInt(domainAddedEvent.values.domainId.toString(), 10), }; if (agent) { domainAction.actionInitiator = agent; } return domainAction; }; const getVersionUpgradeActionValues = async ( processedEvents: ProcessedEvent[], ): Promise<Partial<ActionValues>> => { const versionUpgradeEvent = processedEvents.find( ({ name }) => name === ColonyAndExtensionsEvents.ColonyUpgraded, ) as ProcessedEvent; const { address, values: { oldVersion, newVersion, agent }, } = versionUpgradeEvent; const colonyContractUpgradeValues: { address: Address; actionInitiator?: string; oldVersion: string; newVersion: string; } = { address, oldVersion: bigNumberify(oldVersion || '0').toString(), newVersion: bigNumberify(newVersion || '0').toString(), }; if (agent) { colonyContractUpgradeValues.actionInitiator = agent; } return colonyContractUpgradeValues; }; const getColonyEditActionValues = async ( processedEvents: ProcessedEvent[], ): Promise<Partial<ActionValues>> => { let colonyDisplayName = null; let colonyAvatarHash = null; let colonyTokens = []; const colonyMetadataEvent = processedEvents.find( ({ name }) => name === ColonyAndExtensionsEvents.ColonyMetadata, ) as ProcessedEvent; const { address, values: { agent, metadata }, } = colonyMetadataEvent; /* * Fetch the colony's metadata */ let ipfsMetadata: any = null; try { ipfsMetadata = await ipfs.getString(metadata); } catch (error) { log.verbose( 'Could not fetch IPFS metadata for colony with hash:', metadata, ); } try { if (ipfsMetadata) { const { colonyDisplayName: displayName, colonyAvatarHash: avatarHash, colonyTokens: tokenAddresses, } = JSON.parse(ipfsMetadata); colonyDisplayName = displayName; colonyAvatarHash = avatarHash; colonyTokens = tokenAddresses; } } catch (error) { log.verbose( `Could not parse IPFS metadata for colony, using hash:`, metadata, 'with object:', ipfsMetadata, ); } const colonyEditValues: { address: Address; actionInitiator?: string; colonyDisplayName: string | null; colonyAvatarHash?: string | null; colonyTokens?: string[]; } = { address, colonyDisplayName, colonyAvatarHash, colonyTokens, }; if (agent) { colonyEditValues.actionInitiator = agent; } return colonyEditValues; }; const getEditDomainActionValues = async ( processedEvents: ProcessedEvent[], ): Promise<Partial<ActionValues>> => { const domainMetadataEvent = processedEvents.find( ({ name }) => name === ColonyAndExtensionsEvents.DomainMetadata, ) as ProcessedEvent; const { address, values: { agent, domainId, metadata }, } = domainMetadataEvent; const domainValues = await getDomainValuesFromIPFS(metadata); const domainMetadataValues: { address: Address; fromDomain: number; actionInitiator?: string; domainName: string | null; domainColor: number | null; domainPurpose: string | null; } = { ...domainValues, address, fromDomain: parseInt(domainId.toString(), 10), }; if (agent) { domainMetadataValues.actionInitiator = agent; } return domainMetadataValues; }; const getSetUserRolesActionValues = async ( processedEvents: ProcessedEvent[], ): Promise<Partial<ActionValues>> => { const setUserRolesEvents = processedEvents.filter( ({ name }) => name === ColonyAndExtensionsEvents.ColonyRoleSet, ) as ProcessedEvent[]; const roles: ActionUserRoles[] = setUserRolesEvents.map(({ values }) => ({ id: values.role, setTo: values.setTo, })); const { address, values: { agent, user, domainId }, } = setUserRolesEvents[0]; const userRoleAction: { address: Address; recipient: Address; roles: ActionUserRoles[]; fromDomain: number; actionInitiator?: string; } = { address, recipient: user, roles, fromDomain: parseInt(domainId.toString(), 10), }; if (agent) { userRoleAction.actionInitiator = agent; } return userRoleAction; }; const getRecoveryActionValues = async ( processedEvents: ProcessedEvent[], ): Promise<Partial<ActionValues>> => { const recoveryModeEntered = processedEvents.find( ({ name }) => name === ColonyAndExtensionsEvents.RecoveryModeEntered, ) as ProcessedEvent; const { address, values: { user }, } = recoveryModeEntered; const recoveryAction: { address: Address; actionInitiator?: string; } = { address, }; if (user) { recoveryAction.actionInitiator = user; } return recoveryAction; }; // Motions export const getMotionState = async ( motionNetworkState: NetworkMotionState, votingClient: ExtensionClient, motion, ): Promise<MotionState> => { const totalStakeFraction = await votingClient.getTotalStakeFraction(); const requiredStakes = getMotionRequiredStake( motion.skillRep, totalStakeFraction, 18, ); switch (motionNetworkState) { case NetworkMotionState.Staking: return bigNumberify(motion.stakes[1]).gte(bigNumberify(requiredStakes)) && bigNumberify(motion.stakes[0]).isZero() ? MotionState.Staked : MotionState.Staking; case NetworkMotionState.Submit: return MotionState.Voting; case NetworkMotionState.Reveal: return MotionState.Reveal; case NetworkMotionState.Closed: return MotionState.Escalation; case NetworkMotionState.Finalizable: case NetworkMotionState.Finalized: { const [nayStakes, yayStakes] = motion.stakes; /* * Both sides staked fully, we go to a vote * * @TODO We're using gte as opposed to just eq to counteract a bug on the contracts * Once that is fixed, we can switch this back to equals */ if (nayStakes.gte(requiredStakes) && yayStakes.gte(requiredStakes)) { const [nayVotes, yayVotes] = motion.votes; /* * It only passes if the yay votes outnumber the nay votes * If the votes are equal, it fails */ if (yayVotes.gt(nayVotes)) { return MotionState.Passed; } return MotionState.Failed; } /* * If we didn't get to a vote, it only passes if the Yay side stakes fully * otherwise it fails * * @TODO We're using gte as opposed to just eq to counteract a bug on the contracts * Once that is fixed, we can switch this back to equals */ if (yayStakes.gte(requiredStakes)) { return MotionState.Passed; } return MotionState.Failed; } case NetworkMotionState.Failed: return MotionState.FailedNoFinalizable; default: return MotionState.Invalid; } }; const getMotionValues = async ( processedEvents: ProcessedEvent[], votingClient: ExtensionClient, colonyClient: ColonyClient, ): Promise<Partial<MotionValues>> => { const motionCreatedEvent = processedEvents[0]; const motionId = motionCreatedEvent.values.motionId.toString(); const motion = await votingClient.getMotion(motionId); const motionNetworkState = await votingClient.getMotionState(motionId); const motionState = await getMotionState( motionNetworkState, votingClient, motion, ); const tokenAddress = await colonyClient.getToken(); const motionValues: Partial<MotionValues> = { motionNAYStake: motion.stakes[0].toString(), motionState, address: motionCreatedEvent.address, recipient: motion.altTarget, actionInitiator: motionCreatedEvent.values.creator, tokenAddress, motionDomain: motion.domainId.toNumber(), rootHash: motion.rootHash, }; return motionValues; }; const getMintTokensMotionValues = async ( processedEvents: ProcessedEvent[], votingClient: ExtensionClient, colonyClient: ColonyClient, ): Promise<Partial<MotionValues>> => { const motionCreatedEvent = processedEvents[0]; const motionId = motionCreatedEvent.values.motionId.toString(); const motion = await votingClient.getMotion(motionId); const values = colonyClient.interface.parseTransaction({ data: motion.action, }); const motionDefaultValues = await getMotionValues( processedEvents, votingClient, colonyClient, ); const mintTokensMotionValues: { amount: string; } = { ...motionDefaultValues, amount: bigNumberify(values.args[0] || '0').toString(), }; return mintTokensMotionValues; }; const getCreateDomainMotionValues = async ( processedEvents: ProcessedEvent[], votingClient: ExtensionClient, colonyClient: ColonyClient, ): Promise<Partial<MotionValues>> => { const motionCreatedEvent = processedEvents[0]; const motionId = motionCreatedEvent.values.motionId.toString(); const motion = await votingClient.getMotion(motionId); const values = colonyClient.interface.parseTransaction({ data: motion.action, }); const motionDefaultValues = await getMotionValues( processedEvents, votingClient, colonyClient, ); const domainValues = await getDomainValuesFromIPFS(values.args[3]); const createDomainMotionValues: { domainName: string | null; domainColor: number | null; domainPurpose: string | null; } = { ...motionDefaultValues, ...domainValues, }; return createDomainMotionValues; }; const getSetUserRolesMotionValues = async ( processedEvents: ProcessedEvent[], votingClient: ExtensionClient, colonyClient: ColonyClient, ): Promise<Partial<MotionValues>> => { const motionCreatedEvent = processedEvents[0]; const motionId = motionCreatedEvent.values.motionId.toString(); const motion = await votingClient.getMotion(motionId); const values = colonyClient.interface.parseTransaction({ data: motion.action, }); const motionDefaultValues = await getMotionValues( processedEvents, votingClient, colonyClient, ); const roleBitMask = parseInt(hexStripZeros(values.args[4]), 16).toString(2); const roleBitMaskArray = roleBitMask.split('').reverse(); const roles = availableRoles.map((role) => ({ id: role, setTo: roleBitMaskArray[role] === '1', })); const setUserRolesMotionValues: { recipient: Address; fromDomain: number; roles: ActionUserRoles[]; } = { ...motionDefaultValues, recipient: values.args[2], fromDomain: bigNumberify(values.args[3]).toNumber(), roles, }; return setUserRolesMotionValues; }; const getEditDomainMotionValues = async ( processedEvents: ProcessedEvent[], votingClient: ExtensionClient, colonyClient: ColonyClient, ): Promise<Partial<MotionValues>> => { const motionCreatedEvent = processedEvents[0]; const motionId = motionCreatedEvent.values.motionId.toString(); const motion = await votingClient.getMotion(motionId); const values = colonyClient.interface.parseTransaction({ data: motion.action, }); const motionDefaultValues = await getMotionValues( processedEvents, votingClient, colonyClient, ); const domainValues = await getDomainValuesFromIPFS(values.args[3]); const editDomainMotionValues: { domainName: string | null; domainColor: number | null; domainPurpose: string | null; fromDomain: number; } = { ...motionDefaultValues, ...domainValues, fromDomain: parseInt(values.args[2].toString(), 10), }; return editDomainMotionValues; }; const getColonyEditMotionValues = async ( processedEvents: ProcessedEvent[], votingClient: ExtensionClient, colonyClient: ColonyClient, ): Promise<Partial<MotionValues>> => { const motionCreatedEvent = processedEvents[0]; const motionId = motionCreatedEvent.values.motionId.toString(); const motion = await votingClient.getMotion(motionId); const values = colonyClient.interface.parseTransaction({ data: motion.action, }); const motionDefaultValues = await getMotionValues( processedEvents, votingClient, colonyClient, ); let colonyDisplayName = null; let colonyAvatarHash = null; let colonyTokens = []; let ipfsMetadata: any = null; try { ipfsMetadata = await ipfs.getString(values.args[0]); } catch (error) { log.verbose( 'Could not fetch IPFS metadata for colony with hash:', values.args[0], ); } try { if (ipfsMetadata) { const { colonyDisplayName: displayName, colonyAvatarHash: avatarHash, colonyTokens: tokenAddresses, } = JSON.parse(ipfsMetadata); colonyDisplayName = displayName; colonyAvatarHash = avatarHash; colonyTokens = tokenAddresses; } } catch (error) { log.verbose( `Could not parse IPFS metadata for colony, using hash:`, values.args[0], 'with object:', ipfsMetadata, ); } const colonyEditValues: { actionInitiator?: string; colonyDisplayName: string | null; colonyAvatarHash?: string | null; colonyTokens?: string[]; } = { ...motionDefaultValues, colonyDisplayName, colonyAvatarHash, colonyTokens, }; return colonyEditValues; }; const getPaymentMotionValues = async ( processedEvents: ProcessedEvent[], votingClient: ExtensionClient, oneTxPaymentClient: ExtensionClient, colonyClient: ColonyClient, ): Promise<Partial<MotionValues>> => { const motionCreatedEvent = processedEvents[0]; const motionId = motionCreatedEvent.values.motionId.toString(); const motion = await votingClient.getMotion(motionId); const values = oneTxPaymentClient.interface.parseTransaction({ data: motion.action, }); const motionDefaultValues = await getMotionValues( processedEvents, votingClient, colonyClient, ); const paymentMotionValues: { amount: string; tokenAddress: Address; fromDomain: number; recipient: Address; } = { ...motionDefaultValues, amount: values.args[6][0].toString(), tokenAddress: values.args[5][0], fromDomain: values.args[7].toNumber(), recipient: values.args[4][0], }; return paymentMotionValues; }; const getMoveFundsMotionValues = async ( processedEvents: ProcessedEvent[], votingClient: ExtensionClient, colonyClient: ColonyClient, ): Promise<Partial<MotionValues>> => { const motionCreatedEvent = processedEvents[0]; const motionId = motionCreatedEvent.values.motionId.toString(); const motion = await votingClient.getMotion(motionId); const values = colonyClient.interface.parseTransaction({ data: motion.action, }); const motionDefaultValues = await getMotionValues( processedEvents, votingClient, colonyClient, ); const fromDomain = await colonyClient.getDomainFromFundingPot(values.args[5]); const toDomain = await colonyClient.getDomainFromFundingPot(values.args[6]); const moveFundsMotionValues: { amount: string; tokenAddress: Address; fromDomain: number; toDomain: number; } = { ...motionDefaultValues, amount: values.args[7].toString(), tokenAddress: values.args[8], fromDomain: fromDomain.toNumber(), toDomain: toDomain.toNumber(), }; return moveFundsMotionValues; }; const getVersionUpgradeMotionValues = async ( processedEvents: ProcessedEvent[], votingClient: ExtensionClient, colonyClient: ColonyClient, ): Promise<Partial<MotionValues>> => { const motionCreatedEvent = processedEvents[0]; const motionId = motionCreatedEvent.values.motionId.toString(); const motion = await votingClient.getMotion(motionId); const values = colonyClient.interface.parseTransaction({ data: motion.action, }); const motionDefaultValues = await getMotionValues( processedEvents, votingClient, colonyClient, ); const versionUpgradeMotionValues: { newVersion: string; } = { ...motionDefaultValues, newVersion: bigNumberify(values.args[0].toString() || '0').toString(), }; return versionUpgradeMotionValues; }; export const getActionValues = async ( processedEvents: ProcessedEvent[], colonyClient: ColonyClient, votingClient: ExtensionClient, oneTxPaymentClient: ExtensionClient, actionType: ColonyActions | ColonyMotions, ): Promise<ActionValues> => { const fallbackValues = { recipient: AddressZero, fromDomain: 1, toDomain: 1, amount: '0', tokenAddress: AddressZero, newVersion: '0', oldVersion: '0', address: AddressZero, roles: [{ id: 0, setTo: false }], }; switch (actionType) { case ColonyActions.Payment: { const paymentActionValues = await getPaymentActionValues( processedEvents, colonyClient, ); return { ...fallbackValues, ...paymentActionValues, }; } case ColonyActions.MoveFunds: { const moveFundsActionValues = await getMoveFundsActionValues( processedEvents, colonyClient, ); return { ...fallbackValues, ...moveFundsActionValues, }; } case ColonyActions.MintTokens: { const mintTokensActionValues = await getMintTokensActionValues( processedEvents, colonyClient, ); return { ...fallbackValues, ...mintTokensActionValues, }; } case ColonyActions.CreateDomain: { const createDomainActionValues = await getCreateDomainActionValues( processedEvents, ); return { ...fallbackValues, ...createDomainActionValues, }; } case ColonyActions.EditDomain: { const editDomainActionValues = await getEditDomainActionValues( processedEvents, ); return { ...fallbackValues, ...editDomainActionValues, }; } case ColonyActions.VersionUpgrade: { const versionUpgradeActionValues = await getVersionUpgradeActionValues( processedEvents, ); return { ...fallbackValues, ...versionUpgradeActionValues, }; } case ColonyActions.ColonyEdit: { const colonyEditActionValues = await getColonyEditActionValues( processedEvents, ); return { ...fallbackValues, ...colonyEditActionValues, }; } case ColonyActions.SetUserRoles: { const setUserRolesActionValues = await getSetUserRolesActionValues( processedEvents, ); return { ...fallbackValues, ...setUserRolesActionValues, }; } case ColonyActions.Recovery: { const recoveryActionValues = await getRecoveryActionValues( processedEvents, ); return { ...fallbackValues, ...recoveryActionValues, }; } case ColonyMotions.MintTokensMotion: { const mintTokensMotionValues = await getMintTokensMotionValues( processedEvents, votingClient, colonyClient, ); return { ...fallbackValues, ...mintTokensMotionValues, }; } case ColonyMotions.MoveFundsMotion: { const motionValues = await getMoveFundsMotionValues( processedEvents, votingClient, colonyClient, ); return { ...fallbackValues, ...motionValues, }; } case ColonyMotions.CreateDomainMotion: { const createDomainMotionValues = await getCreateDomainMotionValues( processedEvents, votingClient, colonyClient, ); return { ...fallbackValues, ...createDomainMotionValues, }; } case ColonyMotions.EditDomainMotion: { const editDomainMotionValues = await getEditDomainMotionValues( processedEvents, votingClient, colonyClient, ); return { ...fallbackValues, ...editDomainMotionValues, }; } case ColonyMotions.SetUserRolesMotion: { const setUserRolesValues = await getSetUserRolesMotionValues( processedEvents, votingClient, colonyClient, ); return { ...fallbackValues, ...setUserRolesValues, }; } case ColonyMotions.ColonyEditMotion: { const colonyEditValues = await getColonyEditMotionValues( processedEvents, votingClient, colonyClient, ); return { ...fallbackValues, ...colonyEditValues, }; } case ColonyMotions.PaymentMotion: { const paymentValues = await getPaymentMotionValues( processedEvents, votingClient, oneTxPaymentClient, colonyClient, ); return { ...fallbackValues, ...paymentValues, }; } case ColonyMotions.VersionUpgradeMotion: { const versionUpgradeMotionValues = await getVersionUpgradeMotionValues( processedEvents, votingClient, colonyClient, ); return { ...fallbackValues, ...versionUpgradeMotionValues, }; } default: { return fallbackValues; } } }; export const getDomainsforMoveFundsActions = async ( colonyAddress: string, actions: FormattedAction[], colonyManager: any, ) => { const colonyClient = await colonyManager.getClient( ClientType.ColonyClient, colonyAddress, ); return Promise.all( actions.map(async (action) => { if (action.actionType !== ColonyActions.MoveFunds) { return action; } const fromDomain = await colonyClient.getDomainFromFundingPot( action.fromDomain, ); const toDomain = await colonyClient.getDomainFromFundingPot( action.toDomain, ); return { ...action, fromDomain: bigNumberify(fromDomain).toString(), toDomain: bigNumberify(toDomain).toString(), }; }), ); }; export const groupSetUserRolesActions = (actions): FormattedAction[] => { const groupedActions: FormattedAction[] = []; actions.forEach((actionA) => { if (actionA.actionType === ColonyActions.SetUserRoles) { if ( groupedActions.findIndex( (groupedAction) => actionA.transactionHash === groupedAction.transactionHash, ) === -1 ) { const filteredActionsByHash = actions.filter( ({ transactionHash, actionType }) => actionType === ColonyActions.SetUserRoles && actionA.transactionHash === transactionHash, ); const actionRoles = filteredActionsByHash.reduce( (roles, filteredAction) => { if (filteredAction?.roles) { return [ ...roles, { id: filteredAction?.roles[0]?.id, setTo: filteredAction?.roles[0]?.setTo, }, ]; } return roles; }, [], ); groupedActions.push({ ...actionA, roles: actionRoles, }); } } else { groupedActions.push(actionA); } }); return groupedActions; }; export const getMotionActionType = async ( votingClient: ExtensionClient, oneTxPaymentClient: ExtensionClient, colonyClient: ColonyClient, motionId: BigNumberish, ) => { const motion = await votingClient.getMotion(motionId); const values = colonyClient.interface.parseTransaction({ data: motion.action, }); if (!values) { const paymentValues = oneTxPaymentClient.interface.parseTransaction({ data: motion.action, }); return motionNameMapping[paymentValues.name]; } return motionNameMapping[values.name]; };
the_stack
'use strict' import { Pipeline } from '../engine/pipeline/pipeline' import { PipelineInput, PipelineStage } from '../engine/pipeline/pipeline-engine' import { Algebra } from 'sparqljs' import indexJoin from '../operators/join/index-join' import { rdf, sparql } from '../utils' import { Bindings, BindingBase } from './bindings' import { GRAPH_CAPABILITY } from './graph_capability' import ExecutionContext from '../engine/context/execution-context' import { mean, orderBy, isNull, round, sortBy } from 'lodash' /** * Metadata used for query optimization */ export interface PatternMetadata { triple: Algebra.TripleObject, cardinality: number, nbVars: number } function parseCapabilities (registry: Map<GRAPH_CAPABILITY, boolean>, proto: any): void { registry.set(GRAPH_CAPABILITY.ESTIMATE_TRIPLE_CARD, proto.estimateCardinality != null) registry.set(GRAPH_CAPABILITY.UNION, proto.evalUnion != null) } /** * An abstract RDF Graph, accessed through a RDF Dataset * @abstract * @author Thomas Minier */ export default abstract class Graph { private _iri: string private _capabilities: Map<GRAPH_CAPABILITY, boolean> constructor () { this._iri = '' this._capabilities = new Map() parseCapabilities(this._capabilities, Object.getPrototypeOf(this)) } /** * Get the IRI of the Graph * @return The IRI of the Graph */ get iri (): string { return this._iri } /** * Set the IRI of the Graph * @param value - The new IRI of the Graph */ set iri (value: string) { this._iri = value } /** * Test if a graph has a capability * @param token - Capability tested * @return True if the graph has the reuqested capability, false otherwise */ _isCapable (token: GRAPH_CAPABILITY): boolean { return this._capabilities.has(token) && this._capabilities.get(token)! } /** * Insert a RDF triple into the RDF Graph * @param triple - RDF Triple to insert * @return A Promise fulfilled when the insertion has been completed */ abstract insert (triple: Algebra.TripleObject): Promise<void> /** * Delete a RDF triple from the RDF Graph * @param triple - RDF Triple to delete * @return A Promise fulfilled when the deletion has been completed */ abstract delete (triple: Algebra.TripleObject): Promise<void> /** * Get a {@link PipelineInput} which finds RDF triples matching a triple pattern in the graph. * @param pattern - Triple pattern to find * @param context - Execution options * @return A {@link PipelineInput} which finds RDF triples matching a triple pattern */ abstract find (pattern: Algebra.TripleObject, context: ExecutionContext): PipelineInput<Algebra.TripleObject> /** * Remove all RDF triples in the Graph * @return A Promise fulfilled when the clear operation has been completed */ abstract clear (): Promise<void> /** * Estimate the cardinality of a Triple pattern, i.e., the number of matching RDF Triples in the RDF Graph. * @param triple - Triple pattern to estimate cardinality * @return A Promise fulfilled with the pattern's estimated cardinality */ estimateCardinality (triple: Algebra.TripleObject): Promise<number> { throw new SyntaxError('Error: this graph is not capable of estimating the cardinality of a triple pattern') } /** * Get a {@link PipelineStage} which finds RDF triples matching a triple pattern and a set of keywords in the RDF Graph. * The search can be constrained by min and max relevance (a 0 to 1 score signifying how closely the literal matches the search terms). * * The {@link Graph} class provides a default implementation that computes the relevance * score as the percentage of words matching the list of input keywords. * If the minRank and/or maxRanks parameters are used, then * the graph materializes all matching RDF triples, sort them by descending rank and then * selects the appropriates ranks. * Otherwise, the rank is not computed and all triples are associated with a rank of -1. * * Consequently, the default implementation should works fines for a basic usage, but more advanced users * should provides their own implementation, integrated with their own backend. * For example, a SQL-based RDF Graph should rely on GIN or GIST indexes for the full text search. * @param pattern - Triple pattern to find * @param variable - SPARQL variable on which the keyword search is performed * @param keywords - List of keywords to seach for occurence * @param matchAll - True if only values that contain all of the specified search terms should be considered. * @param minRelevance - Minimum relevance score (set it to null to disable it) * @param maxRelevance - Maximum relevance score (set it to null to disable it) * @param minRank - Minimum rank of the matches (set it to null to disable it) * @param maxRank - Maximum rank of the matches (set it to null to disable it) * @param context - Execution options * @return A {@link PipelineInput} which output tuples of shape [matching RDF triple, score, rank]. * @example * const pattern = { subject: '?s', predicate: 'foaf:name', object: '?n'} * const keywords = [ 'Ann' , 'Bob' ] * // Find the top 100 RDF triples matching the pattern where ?n contains the keyword 'Ann' or 'Bob' * // with a minimum relevance score of 0.25 and no maximum relevance score. * const pipeline = graph.fullTextSearch(pattern, '?n', keywords, 0.25, null, null, 100, context) * pipeline.subscribe(item => { * console.log(`Matching RDF triple ${item[0]} with score ${item[1]} and rank ${item[2]}`) * }, console.error, () => console.log('Search completed!')) */ fullTextSearch (pattern: Algebra.TripleObject, variable: string, keywords: string[], matchAll: boolean, minRelevance: number | null, maxRelevance: number | null, minRank: number | null, maxRank: number | null, context: ExecutionContext): PipelineStage<[Algebra.TripleObject, number, number]> { if (isNull(minRelevance)) { minRelevance = 0 } if (isNull(maxRelevance)) { maxRelevance = Number.MAX_SAFE_INTEGER } // find all RDF triples matching the input triple pattern const source = Pipeline.getInstance().from(this.find(pattern, context)) // compute the score of each matching RDF triple as the average number of words // in the RDF term that matches kewyords let iterator = Pipeline.getInstance().map(source, triple => { let words: string[] = [] if (pattern.subject === variable) { words = triple.subject.split(' ') } else if (pattern.predicate === variable) { words = triple.predicate.split(' ') } else if (pattern.object === variable) { words = triple.object.split(' ') } // For each keyword, compute % of words matching the keyword const keywordScores = keywords.map(keyword => { return words.reduce((acc, word) => { if (word.includes(keyword)) { acc += 1 } return acc }, 0) / words.length }) // if we should match all keyword, not matching a single keyword gives you a score of 0 if (matchAll && keywordScores.some(v => v === 0)) { return { triple, rank: -1, score: 0 } } // The relevance score is computed as the average keyword score return { triple, rank: -1, score: round(mean(keywordScores), 3) } }) // filter by min & max relevance scores iterator = Pipeline.getInstance().filter(iterator, v => { return v.score > 0 && minRelevance! <= v.score && v.score <= maxRelevance! }) // if needed, rank the matches by descending score if (!isNull(minRank) || !isNull(maxRank)) { if (isNull(minRank)) { minRank = 0 } if (isNull(maxRank)) { maxRank = Number.MAX_SAFE_INTEGER } // null or negative values for minRank and/or maxRank will yield no results if (minRank < 0 || maxRank < 0) { return Pipeline.getInstance().empty() } // ranks the matches, and then only keeps the desired ranks iterator = Pipeline.getInstance().flatMap(Pipeline.getInstance().collect(iterator), values => { return orderBy(values, [ 'score' ], [ 'desc' ]) // add rank .map((item, rank) => { item.rank = rank return item }) // slice using the minRank and maxRank parameters .slice(minRank!, maxRank! + 1) }) } // finally, format results as tuples [RDF triple, triple's score, triple's rank] return Pipeline.getInstance().map(iterator, v => [v.triple, v.score, v.rank]) } /** * Evaluates an union of Basic Graph patterns on the Graph using a {@link PipelineStage}. * @param patterns - The set of BGPs to evaluate * @param context - Execution options * @return A {@link PipelineStage} which evaluates the Basic Graph pattern on the Graph */ evalUnion (patterns: Algebra.TripleObject[][], context: ExecutionContext): PipelineStage<Bindings> { throw new SyntaxError('Error: this graph is not capable of evaluating UNION queries') } /** * Evaluates a Basic Graph pattern, i.e., a set of triple patterns, on the Graph using a {@link PipelineStage}. * @param bgp - The set of triple patterns to evaluate * @param context - Execution options * @return A {@link PipelineStage} which evaluates the Basic Graph pattern on the Graph */ evalBGP (bgp: Algebra.TripleObject[], context: ExecutionContext): PipelineStage<Bindings> { const engine = Pipeline.getInstance() if (this._isCapable(GRAPH_CAPABILITY.ESTIMATE_TRIPLE_CARD)) { const op = engine.from(Promise.all(bgp.map(triple => { return this.estimateCardinality(triple).then(c => { return { triple, cardinality: c, nbVars: rdf.countVariables(triple) } }) }))) return engine.mergeMap(op, (results: PatternMetadata[]) => { const sortedPatterns = sparql.leftLinearJoinOrdering(sortBy(results, 'cardinality').map(t => t.triple)) const start = engine.of(new BindingBase()) return sortedPatterns.reduce((iter: PipelineStage<Bindings>, t: Algebra.TripleObject) => { return indexJoin(iter, t, this, context) }, start) }) } else { // FIX ME: this trick is required, otherwise ADD, COPY and MOVE queries are not evaluated correctly. We need to find why... return engine.mergeMap(engine.from(Promise.resolve(null)), () => { const start = engine.of(new BindingBase()) return sparql.leftLinearJoinOrdering(bgp).reduce((iter: PipelineStage<Bindings>, t: Algebra.TripleObject) => { return indexJoin(iter, t, this, context) }, start) }) } } } // disable optional methods Object.defineProperty(Graph.prototype, 'estimateCardinality', { value: null }) Object.defineProperty(Graph.prototype, 'evalUnion', { value: null })
the_stack
import { SmoothTrail } from "../Graphics/Script/SmoothTrail"; import { SplineParameterization } from "./Script/CatmullRomSpline"; import { CornerType, SplineTrailRenderer } from "./Script/SplineTrailRenderer"; const {ccclass, property} = cc._decorator; type BezierParam = { A: cc.Vec2, B: cc.Vec2, C: cc.Vec2, D: cc.Vec2, CP1: cc.Vec2, CP2: cc.Vec2 }; @ccclass export default class SceneGraphicsDrawingBoard extends cc.Component { @property(cc.Node) board: cc.Node = null; @property(SmoothTrail) ctx: SmoothTrail = null; @property(SplineTrailRenderer) trailRenderer: SplineTrailRenderer = null; @property(cc.EditBox) edtK: cc.EditBox = null; @property([cc.Material]) materials: cc.Material[] = []; protected _autoRender: boolean = true; protected _isDragging: boolean = false; protected _points: cc.Vec2[] = []; protected _debug: boolean = false; protected _lineWidth: number = 0.05; // ratio of screen width protected _bezierParams: BezierParam[] = []; protected _debugK: number = 0; onLoad() { let sprite = this.board.getComponent(cc.Sprite); sprite.sizeMode = cc.Sprite.SizeMode.CUSTOM; // 设置混合模式为max,主要为了避免线段衔接处颜色叠加导致变厚 // var ext = gl.getExtension('EXT_blend_minmax'); // let mat = this.singlePass.node.getComponent(cc.Sprite).getMaterial(0); // mat?.setBlend( // true, // ext.MAX_EXT, // gfx.BLEND_SRC_ALPHA, // gfx.BLEND_ONE_MINUS_SRC_ALPHA, // ext.MAX_EXT, // gfx.BLEND_SRC_ALPHA, // gfx.BLEND_ONE_MINUS_SRC_ALPHA, // 0xffffffff, // 0); this.board.on(cc.Node.EventType.TOUCH_START, this.OnBoardTouchStart, this); this.board.on(cc.Node.EventType.TOUCH_MOVE, this.OnBoardTouchMove, this); this.board.on(cc.Node.EventType.TOUCH_END, this.OnBoardTouchEnd, this); this.board.on(cc.Node.EventType.TOUCH_CANCEL, this.OnBoardTouchEnd, this); } start () { // 2.4.6中导致尖角的case // 用于验证是否已经fix // let A = cc.v2(-174.606196, 148.231612); // let CP1 = cc.v2(-168.5968, 135.378); // let CP2 = cc.v2(-153.57333, 107.50); // let D = cc.v2(-156.578, 114.1784); // let ctx = this.ctx; // ctx.moveTo(A.x, A.y); // ctx.bezierCurveTo(CP1.x, CP1.y, CP2.x, CP2.y, D.x, D.y); // ctx.stroke(); let ctx = this.ctx; if (ctx.node.active) { ctx.StartPath(cc.v2(0, 0)); ctx.AddPathPoint(cc.v2(0, 100)); ctx.AddPathPoint(cc.v2(1, 0)); ctx.AddPathPoint(cc.v2(100, 0)); ctx.EndPath(); } let trailRenderer = this.trailRenderer; if (trailRenderer.node.active) { trailRenderer.StartPath(trailRenderer.FromLocalPos(cc.v2(0, 0))); trailRenderer.AddPoint(trailRenderer.FromLocalPos(cc.v2(0, 100))); trailRenderer.AddPoint(trailRenderer.FromLocalPos(cc.v2(100, 0))); } } // protected SetBlendEqToMax(mat: cc.Material) { // if (this._debug) // return; // //@ts-ignore // let gl = cc.game._renderContext; // //@ts-ignore // let gfx = cc.gfx; // var ext = gl.getExtension('EXT_blend_minmax'); // mat?.setBlend( // true, // ext.MAX_EXT, // gfx.BLEND_SRC_ALPHA, // gfx.BLEND_ONE_MINUS_SRC_ALPHA, // ext.MAX_EXT, // gfx.BLEND_SRC_ALPHA, // gfx.BLEND_ONE_MINUS_SRC_ALPHA, // 0xffffffff, // 0); // } protected _tmpV2 = cc.v2(0, 0); update() { // move everything to SmoothTrail return; let points = this._points; if (points.length < 3) return; let A = points[0]; let B = points[1]; let C = points[2]; let isValid: boolean = true; let useBezier: boolean = true; let halfBezier: boolean = false; // ABC共线的情况用直线处理 if (Math.abs((B.x-A.x) * (C.y-A.y) - (B.y-A.y) * (C.x-A.x)) <= 1e-5) { useBezier = false; } // 画直线时候点重叠,则不画 if (!useBezier && A.equals(B)) { isValid = false; } // if (useBezier) { // // 距离太短的也不要用bezier // let tmpV2 = this._tmpV2; // A.sub(B, tmpV2); // let dist2 = tmpV2.dot(tmpV2); // if (dist2 <= 16) { // useBezier = false; // } // } if (!useBezier) { // sprite.setMaterial(0, this.matCapsule); // let mat = sprite.getComponent(cc.Sprite).getMaterial(0); // this.SetBlendEqToMax(mat); // mat.setProperty("width", this._lineWidth); // mat.setProperty("PP", [A.x, A.y, B.x, B.y]); if (this.ctx.node.active) { this.ctx.moveTo(A.x, A.y); this.ctx.lineTo(B.x, B.y); this.ctx.stroke(); } } else { if (points.length <= 3) { // 只绘制cubic bezier,需要4个点 return; } // sprite.setMaterial(0, this.matBezier); // let mat = sprite.getComponent(cc.Sprite).getMaterial(0); // this.SetBlendEqToMax(mat); // if (halfBezier) { // // 切分bezier曲线,只绘制AB段 // // vec2 TC = PB; // // vec2 TB = (PA - PC) * 0.25 + PB; // // PB = TB; // // PC = TC; // let TB = A.sub(C); // TB.mulSelf(0.25).addSelf(B); // C = B; // B = TB; // } else { // // B从途经点变为控制点 // // B = (4.0 * B - A - C) / 2.0 // B = B.mul(4); // B.subSelf(A).subSelf(C).divSelf(2); // } // mat.setProperty("width", this._lineWidth); // mat.setProperty("PA", [A.x, A.y]); // mat.setProperty("PB", [B.x, B.y]); // mat.setProperty("PC", [C.x, C.y]); // 待计算的控制点 let CP1 = cc.v2(0, 0); let CP2 = cc.v2(0, 0); if (this.ctx.node.active) { // todo: 先不管overdraw的问题,直接绘制整条bezier let D = points[3]; this.ctx.moveTo(A.x, A.y); this.CalculateControlPoints(A, B, C, D, CP1, CP2); this.ctx.bezierCurveTo(CP1.x, CP1.y, CP2.x, CP2.y, D.x, D.y); this._bezierParams.push({ A: A, B: B, C: C, D: D, CP1: CP1, CP2: CP2 }); // if (CP1.sub(A).dot(CP1.sub(A)) > 40 || // CP2.sub(D).dot(CP2.sub(D)) > 40) { // console.log(` // A: (0, 0), // B: (${B.sub(A).x}, ${B.sub(A).y}), // C: (${C.sub(A).x}, ${C.sub(A).y}), // D: (${D.sub(A).x}, ${D.sub(A).y}), // CP1: (${CP1.sub(A).x}, ${CP1.sub(A).y}), // CP2: (${CP2.sub(A).x}, ${CP2.sub(A).y}`); // } // this.ctx.bezierCurveTo(B.x, B.y, C.x, C.y, D.x, D.y); // this.ctx.quadraticCurveTo(B.x, B.y, C.x, C.y); this.ctx.stroke(); } } if (this._debug) console.log(`${A}, ${B}, ${C}, color=${this._colorIndex}, useBezier=${useBezier}`); if (isValid) { // if (this._debug) // sprite.node.color = this._colors[this._colorIndex]; this._colorIndex = (this._colorIndex + 1) % this._colors.length; // this.RenderToNode(sprite.node, this.board); } this._points.shift(); // this._points.shift(); } // P0, P3是曲线的端点 // B1, B2是途经点,t值对应1/3, 2/3(假设每帧采样一次,所有点的t都等距) protected CalculateControlPoints(P0: cc.Vec2, B1: cc.Vec2, B2: cc.Vec2, P3: cc.Vec2, CP1: cc.Vec2, CP2: cc.Vec2) { let t = 1/3; let C0 = P0.mul(Math.pow(1-t, 3)); let C1 = 3 * Math.pow(1-t, 2) * t; let C2 = 3 * (1-t) * t * t; let C3 = P3.mul(t * t * t); t = 2/3; let D0 = P0.mul(Math.pow(1-t, 3)); let D1 = 3 * Math.pow(1-t, 2) * t; let D2 = 3 * (1-t) * t * t; let D3 = P3.mul(t * t * t); let Z1 = B1.sub(C0).sub(C3); let Z2 = B2.sub(D0).sub(D3); CP2.set(Z2.mul(C1).sub(Z1.mul(D1)).div(C1 * D2 - C2 * D1)); CP1.set(Z2.mul(C1).sub(CP2.mul(C1 * D2)).div(C1 * D1)); } public Clear() { if (this.ctx.node.active) this.ctx.clear(); this._bezierParams.length = 0; } public KthBezierEditEnd(e: cc.EditBox) { let k = parseInt(e.string); this.SetK(k); } protected SetK(k: number, updateCtrl: boolean = false) { if (k < 0 || k >= this._bezierParams.length) { console.error("k out of range"); return; } if (updateCtrl) { this.edtK.string = `${k}`; } this._debugK = k; let param = this._bezierParams[k]; let ctx = this.ctx; ctx.clear() ctx.moveTo(param.A.x, param.A.y); ctx.bezierCurveTo( param.CP1.x, param.CP1.y, param.CP2.x, param.CP2.y, param.D.x, param.D.y); ctx.stroke(); } public ShowKthBezierPoints() { let k = this._debugK; if (k < 0 || k >= this._bezierParams.length) { console.error("k out of range"); return; } let param = this._bezierParams[k] let A = param.A, B = param.B, C = param.C, D = param.D, CP1 = param.CP1, CP2 = param.CP2; // console.log(` // A: (0, 0), // B: (${B.sub(A).x}, ${B.sub(A).y}), // C: (${C.sub(A).x}, ${C.sub(A).y}), // D: (${D.sub(A).x}, ${D.sub(A).y}), // CP1: (${CP1.sub(A).x}, ${CP1.sub(A).y}), // CP2: (${CP2.sub(A).x}, ${CP2.sub(A).y}`); console.log(` A: (${A.x}, ${A.y}), B: (${B.x}, ${B.y}), C: (${C.x}, ${C.y}), D: (${D.x}, ${D.y}), CP1: (${CP1.x}, ${CP1.y}), CP2: (${CP2.x}, ${CP2.y}`); } public PrevK() { this.SetK(this._debugK - 1); } public NextK() { this.SetK(this._debugK + 1); } protected TouchPosToGraphicsPos(pos: cc.Vec2): cc.Vec2 { return this.ctx.node.convertToNodeSpaceAR(pos); // let node = this.ctx.node; // node.convertToNodeSpaceAR(pos, pos); // // map to [-0.5, 0.5] // pos.x /= node.width; // pos.y /= node.height; // // [-0.5, 0.5] map to [-1, 1] // pos.mulSelf(2.0); // // scale Y, same as in shader // pos.y *= node.height / node.width; // return pos; } protected OnBoardTouchStart(e: cc.Event.EventTouch) { let pos = this.TouchPosToGraphicsPos(e.getLocation()); this._isDragging = true; this._points.length = 0; this._points.push(pos); if (this.ctx.node.active) this.ctx.StartPath(pos); let trailRenderer = this.trailRenderer; if (trailRenderer.node.active) { trailRenderer.StartPath(trailRenderer.FromLocalPos(pos)); trailRenderer.AddPoint(trailRenderer.FromLocalPos(pos)); } // if (this.ctx.node.active) { // let localPos = this.node.convertToNodeSpaceAR(e.getLocation()); // this.ctx.moveTo(localPos.x, localPos.y); // } } protected _colorIndex: number = 0; protected _colors = [cc.Color.WHITE, cc.Color.RED, cc.Color.GREEN, cc.Color.BLUE, cc.Color.YELLOW, cc.Color.CYAN]; protected OnBoardTouchMove(e: cc.Event.EventTouch) { if (!this._isDragging) return; let cur = this.TouchPosToGraphicsPos(e.getLocation()); // console.log(`${cur.x}, ${cur.y}`); this._points.push(cur); if (this.ctx.node.active) this.ctx.AddPathPoint(cur); let trailRenderer = this.trailRenderer; if (trailRenderer.node.active) { trailRenderer.AddPoint(trailRenderer.FromLocalPos(cur)); } // if (this.ctx.node.active) { // let localPos = this.node.convertToNodeSpaceAR(e.getLocation()); // this.ctx.lineTo(localPos.x, localPos.y); // this.ctx.stroke(); // } } protected OnBoardTouchEnd() { this._isDragging = false; // simply clear points // todo: draw last segment this._points.length = 0; if (this.ctx.node.active) this.ctx.EndPath(); if (this.trailRenderer.node.active) { console.log(`----- vcount: ${this.trailRenderer._vertices.length}`); } if (this._debug) console.log(`---------------------------- end ------------------------`) } protected OnSwitchParam() { if (this.trailRenderer.cornerType === CornerType.Continuous) { this.trailRenderer.cornerType = CornerType.Fragmented; } else { this.trailRenderer.cornerType = CornerType.Continuous; } this.trailRenderer.RenderMesh(); } protected _materialIndex = 0; protected OnSwitchMaterial() { this._materialIndex = (this._materialIndex + 1) % this.materials.length; this.trailRenderer.setMaterial(0, this.materials[this._materialIndex]); this.trailRenderer.RenderMesh(); } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * ## Import * * Domain Services can be imported using the resource ID, together with the Replica Set ID that you wish to designate as the initial replica set, e.g. * * ```sh * $ pulumi import azure:domainservices/service:Service example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.AAD/domainServices/instance1/initialReplicaSetId/00000000-0000-0000-0000-000000000000 * ``` */ export class Service extends pulumi.CustomResource { /** * Get an existing Service resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ServiceState, opts?: pulumi.CustomResourceOptions): Service { return new Service(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:domainservices/service:Service'; /** * Returns true if the given object is an instance of Service. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is Service { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Service.__pulumiType; } /** * A unique ID for the managed domain deployment. */ public /*out*/ readonly deploymentId!: pulumi.Output<string>; /** * The Active Directory domain to use. See [official documentation](https://docs.microsoft.com/en-us/azure/active-directory-domain-services/tutorial-create-instance#create-a-managed-domain) for constraints and recommendations. */ public readonly domainName!: pulumi.Output<string>; /** * Whether to enable group-based filtered sync (also called scoped synchronisation). Defaults to `false`. */ public readonly filteredSyncEnabled!: pulumi.Output<boolean | undefined>; /** * An `initialReplicaSet` block as defined below. The initial replica set inherits the same location as the Domain Service resource. */ public readonly initialReplicaSet!: pulumi.Output<outputs.domainservices.ServiceInitialReplicaSet>; /** * The Azure location where the Domain Service exists. Changing this forces a new resource to be created. */ public readonly location!: pulumi.Output<string>; /** * The display name for your managed Active Directory Domain Service resource. Changing this forces a new resource to be created. */ public readonly name!: pulumi.Output<string>; /** * A `notifications` block as defined below. */ public readonly notifications!: pulumi.Output<outputs.domainservices.ServiceNotifications>; /** * The name of the Resource Group in which the Domain Service should exist. Changing this forces a new resource to be created. */ public readonly resourceGroupName!: pulumi.Output<string>; /** * The Azure resource ID for the domain service. */ public /*out*/ readonly resourceId!: pulumi.Output<string>; /** * A `secureLdap` block as defined below. */ public readonly secureLdap!: pulumi.Output<outputs.domainservices.ServiceSecureLdap>; /** * A `security` block as defined below. */ public readonly security!: pulumi.Output<outputs.domainservices.ServiceSecurity>; /** * The SKU to use when provisioning the Domain Service resource. One of `Standard`, `Enterprise` or `Premium`. */ public readonly sku!: pulumi.Output<string>; public /*out*/ readonly syncOwner!: pulumi.Output<string>; /** * A mapping of tags assigned to the resource. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; public /*out*/ readonly tenantId!: pulumi.Output<string>; public /*out*/ readonly version!: pulumi.Output<number>; /** * Create a Service resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: ServiceArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: ServiceArgs | ServiceState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as ServiceState | undefined; inputs["deploymentId"] = state ? state.deploymentId : undefined; inputs["domainName"] = state ? state.domainName : undefined; inputs["filteredSyncEnabled"] = state ? state.filteredSyncEnabled : undefined; inputs["initialReplicaSet"] = state ? state.initialReplicaSet : undefined; inputs["location"] = state ? state.location : undefined; inputs["name"] = state ? state.name : undefined; inputs["notifications"] = state ? state.notifications : undefined; inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined; inputs["resourceId"] = state ? state.resourceId : undefined; inputs["secureLdap"] = state ? state.secureLdap : undefined; inputs["security"] = state ? state.security : undefined; inputs["sku"] = state ? state.sku : undefined; inputs["syncOwner"] = state ? state.syncOwner : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["tenantId"] = state ? state.tenantId : undefined; inputs["version"] = state ? state.version : undefined; } else { const args = argsOrState as ServiceArgs | undefined; if ((!args || args.domainName === undefined) && !opts.urn) { throw new Error("Missing required property 'domainName'"); } if ((!args || args.initialReplicaSet === undefined) && !opts.urn) { throw new Error("Missing required property 'initialReplicaSet'"); } if ((!args || args.resourceGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupName'"); } if ((!args || args.sku === undefined) && !opts.urn) { throw new Error("Missing required property 'sku'"); } inputs["domainName"] = args ? args.domainName : undefined; inputs["filteredSyncEnabled"] = args ? args.filteredSyncEnabled : undefined; inputs["initialReplicaSet"] = args ? args.initialReplicaSet : undefined; inputs["location"] = args ? args.location : undefined; inputs["name"] = args ? args.name : undefined; inputs["notifications"] = args ? args.notifications : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined; inputs["secureLdap"] = args ? args.secureLdap : undefined; inputs["security"] = args ? args.security : undefined; inputs["sku"] = args ? args.sku : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["deploymentId"] = undefined /*out*/; inputs["resourceId"] = undefined /*out*/; inputs["syncOwner"] = undefined /*out*/; inputs["tenantId"] = undefined /*out*/; inputs["version"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Service.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Service resources. */ export interface ServiceState { /** * A unique ID for the managed domain deployment. */ deploymentId?: pulumi.Input<string>; /** * The Active Directory domain to use. See [official documentation](https://docs.microsoft.com/en-us/azure/active-directory-domain-services/tutorial-create-instance#create-a-managed-domain) for constraints and recommendations. */ domainName?: pulumi.Input<string>; /** * Whether to enable group-based filtered sync (also called scoped synchronisation). Defaults to `false`. */ filteredSyncEnabled?: pulumi.Input<boolean>; /** * An `initialReplicaSet` block as defined below. The initial replica set inherits the same location as the Domain Service resource. */ initialReplicaSet?: pulumi.Input<inputs.domainservices.ServiceInitialReplicaSet>; /** * The Azure location where the Domain Service exists. Changing this forces a new resource to be created. */ location?: pulumi.Input<string>; /** * The display name for your managed Active Directory Domain Service resource. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * A `notifications` block as defined below. */ notifications?: pulumi.Input<inputs.domainservices.ServiceNotifications>; /** * The name of the Resource Group in which the Domain Service should exist. Changing this forces a new resource to be created. */ resourceGroupName?: pulumi.Input<string>; /** * The Azure resource ID for the domain service. */ resourceId?: pulumi.Input<string>; /** * A `secureLdap` block as defined below. */ secureLdap?: pulumi.Input<inputs.domainservices.ServiceSecureLdap>; /** * A `security` block as defined below. */ security?: pulumi.Input<inputs.domainservices.ServiceSecurity>; /** * The SKU to use when provisioning the Domain Service resource. One of `Standard`, `Enterprise` or `Premium`. */ sku?: pulumi.Input<string>; syncOwner?: pulumi.Input<string>; /** * A mapping of tags assigned to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; tenantId?: pulumi.Input<string>; version?: pulumi.Input<number>; } /** * The set of arguments for constructing a Service resource. */ export interface ServiceArgs { /** * The Active Directory domain to use. See [official documentation](https://docs.microsoft.com/en-us/azure/active-directory-domain-services/tutorial-create-instance#create-a-managed-domain) for constraints and recommendations. */ domainName: pulumi.Input<string>; /** * Whether to enable group-based filtered sync (also called scoped synchronisation). Defaults to `false`. */ filteredSyncEnabled?: pulumi.Input<boolean>; /** * An `initialReplicaSet` block as defined below. The initial replica set inherits the same location as the Domain Service resource. */ initialReplicaSet: pulumi.Input<inputs.domainservices.ServiceInitialReplicaSet>; /** * The Azure location where the Domain Service exists. Changing this forces a new resource to be created. */ location?: pulumi.Input<string>; /** * The display name for your managed Active Directory Domain Service resource. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * A `notifications` block as defined below. */ notifications?: pulumi.Input<inputs.domainservices.ServiceNotifications>; /** * The name of the Resource Group in which the Domain Service should exist. Changing this forces a new resource to be created. */ resourceGroupName: pulumi.Input<string>; /** * A `secureLdap` block as defined below. */ secureLdap?: pulumi.Input<inputs.domainservices.ServiceSecureLdap>; /** * A `security` block as defined below. */ security?: pulumi.Input<inputs.domainservices.ServiceSecurity>; /** * The SKU to use when provisioning the Domain Service resource. One of `Standard`, `Enterprise` or `Premium`. */ sku: pulumi.Input<string>; /** * A mapping of tags assigned to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; }
the_stack
import { IBar } from "./bar"; import { IDataFrame } from "data-forge"; import { ITrade } from "./trade"; import { IStrategy } from "./strategy"; import { backtest } from "./backtest"; import { isObject, isArray, isFunction } from "./utils"; import { performance } from "perf_hooks"; import { Random } from "./random"; /** * Defines a function that selects an objective value to measure the performance of a set of trades. */ export type ObjectiveFn = (trades: ITrade[]) => number; /** * What is the best value of the objective function? */ export type OptimizeSearchDirection = "max" | "min"; /** * Defines the parameter to optimize for. */ export interface IParameterDef { /** * The name of the parameter. */ name: string; /** * The starting value of the parameter. */ startingValue: number; /** * The ending value of the parameter. */ endingValue: number; /** * Amount to step the parameter with each iteration of the optimziation. */ stepSize: number; } // // Sets the type of algoritm used for optimization. // export type OptimizationType = "grid" | "hill-climb"; /** * Options to the optimize function. */ export interface IOptimizationOptions { /** * Determine the direction we are optimizating for when looking out the object function. */ searchDirection?: OptimizeSearchDirection; /** * Sets the type of algoritm used for optimization. * Defaults to "grid". */ optimizationType?: OptimizationType; /** * Record all results from all iterations. */ recordAllResults?: boolean; /** * Starting seed for the random number generator. */ randomSeed?: number; /** * The number of starting points to consider for the hill climb algorithm. * The more starting point the better chance of getting an optimal result, but it also makes the algo run slower. */ numStartingPoints?: number; /** * Record the duration of the optimization algorithm. */ recordDuration?: boolean; } // // Records the result of an iteration of optimization. // export type IterationResult<ParameterT> = (ParameterT & { result: number, numTrades: number }); /** * Result of a multi-parameter optimisation. */ export interface IOptimizationResult<ParameterT> { /** * The best result that was found in the parameter space. */ bestResult: number; /** * Best parameter values produced by this optimization. */ bestParameterValues: ParameterT; /** * Results of all iterations of optimizations. */ allResults?: IterationResult<ParameterT>[]; /** * The time taken (in milliseconds) by the optimization algorithm. */ durationMS?: number; } interface OptimizationIterationResult { // // Metric used to compare iterations. // metric: number; // // Number of trades performed in this iteration. // numTrades: number; } // // Performs a single iteration of optimization and returns the result. // function optimizationIteration<InputBarT extends IBar, IndicatorBarT extends InputBarT, ParameterT, IndexT>( strategy: IStrategy<InputBarT, IndicatorBarT, ParameterT, IndexT>, parameters: IParameterDef[], objectiveFn: ObjectiveFn, inputSeries: IDataFrame<IndexT, InputBarT>, coordinates: number[] ): OptimizationIterationResult { const parameterOverride: any = {}; for (let parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) { const parameter = parameters[parameterIndex]; parameterOverride[parameter.name] = coordinates[parameterIndex]; } const strategyClone = Object.assign({}, strategy); strategyClone.parameters = Object.assign({}, strategy.parameters, parameterOverride); const trades = backtest<InputBarT, IndicatorBarT, ParameterT, IndexT>(strategyClone, inputSeries) return { metric: objectiveFn(trades), numTrades: trades.length, }; } // // Get neighbours of a particular set of coordinates. // function* getNeighbours(coordinates: number[], parameters: IParameterDef[]): IterableIterator<number[]> { // // Step forward. // for (let i = 0; i < parameters.length; ++i) { const nextCoordinate = coordinates[i] += parameters[i].stepSize; if (nextCoordinate <= parameters[i].endingValue) { const nextCoordinates = coordinates.slice(); // Clone. nextCoordinates[i] = nextCoordinate; yield nextCoordinates; } } // // Step backward. // for (let i = 0; i < parameters.length; ++i) { const nextCoordinate = coordinates[i] -= parameters[i].stepSize; if (nextCoordinate >= parameters[i].startingValue) { const nextCoordinates = coordinates.slice(); // Clone. nextCoordinates[i] = nextCoordinate; yield nextCoordinates; } } } // // Extracts parameter values from the coordinate system. // function extractParameterValues<ParameterT>(parameters: IParameterDef[], workingCoordinates: number[]): ParameterT { const bestParameterValues: any = {}; for (let parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) { const parameter = parameters[parameterIndex]; bestParameterValues[parameter.name] = workingCoordinates[parameterIndex]; } return bestParameterValues; } // // Packages the results of an iteration. // function packageIterationResult<ParameterT>(parameters: IParameterDef[], workingCoordinates: number[], result: OptimizationIterationResult): IterationResult<ParameterT> { const iterationResult: any = Object.assign( {}, extractParameterValues(parameters, workingCoordinates), { result: result.metric, numTrades: result.numTrades, } ); return iterationResult; } // // Returns true to accept the current result or false to discard. // function acceptResult(workingResult: number, nextResult: number, options: IOptimizationOptions): boolean { if (options.searchDirection === "max") { if (nextResult > workingResult) { // Looking for maximum value. return true; } } else { if (nextResult < workingResult) { // Looking for minimum value. return true; } } return false; } // // Iterate a dimension in coordinate space. // function* iterateDimension(workingCoordinates: number[], parameterIndex: number, parameters: IParameterDef[]): IterableIterator<number[]> { const parameter = parameters[parameterIndex]; for (let parameterValue = parameter.startingValue; parameterValue <= parameter.endingValue; parameterValue += parameter.stepSize) { const coordinatesHere = [...workingCoordinates, parameterValue]; if (parameterIndex < parameters.length-1) { // // Recurse to higher dimensions. // for (const coordinates of iterateDimension(coordinatesHere, parameterIndex+1, parameters)) { yield coordinates; } } else { // // At the bottommost dimension. // This is where we produce coordinates. // yield coordinatesHere; } } } // // Get all coordinates in a particular coordinate space. // function* getAllCoordinates(parameters: IParameterDef[]): IterableIterator<number[]> { for (const coordinates of iterateDimension([], 0, parameters)) { yield coordinates; } } // // Performs a fast but non-exhaustive hill climb optimization. // function hillClimbOptimization<InputBarT extends IBar, IndicatorBarT extends InputBarT, ParameterT, IndexT>( strategy: IStrategy<InputBarT, IndicatorBarT, ParameterT, IndexT>, parameters: IParameterDef[], objectiveFn: ObjectiveFn, inputSeries: IDataFrame<IndexT, InputBarT>, options: IOptimizationOptions ): IOptimizationResult<ParameterT> { let bestResult: number | undefined; let bestCoordinates: number[] | undefined; const results: IterationResult<ParameterT>[] = []; const startTime = performance.now(); const visitedCoordinates = new Map<number[], OptimizationIterationResult>(); // Tracks coordinates that we have already visited and their value. const random = new Random(options.randomSeed || 0); const numStartingPoints = options.numStartingPoints || 4; for (let startingPointIndex = 0; startingPointIndex < numStartingPoints; ++startingPointIndex) { // // Compute starting coordinates for this section. // let workingCoordinates: number[] = []; for (const parameter of parameters) { const randomIncrement = random.getInt(0, (parameter.endingValue - parameter.startingValue) / parameter.stepSize); const randomCoordinate = parameter.startingValue + randomIncrement * parameter.stepSize; workingCoordinates.push(randomCoordinate); } if (visitedCoordinates.has(workingCoordinates)) { // Already been here! continue; } let workingResult = optimizationIteration(strategy, parameters, objectiveFn, inputSeries, workingCoordinates); visitedCoordinates.set(workingCoordinates, workingResult); if (bestResult === undefined) { bestResult = workingResult.metric; bestCoordinates = workingCoordinates } else if (acceptResult(bestResult, workingResult.metric, options)) { bestResult = workingResult.metric; bestCoordinates = workingCoordinates; } if (options.recordAllResults) { results.push(packageIterationResult(parameters, workingCoordinates, workingResult)); } while (true) { let gotBetterResult = false; // // Visit all neighbouring coordinates. // let nextCoordinates: number[]; for (nextCoordinates of getNeighbours(workingCoordinates!, parameters)) { const cachedResult = visitedCoordinates.get(workingCoordinates); const nextResult = cachedResult !== undefined ? cachedResult : optimizationIteration(strategy, parameters, objectiveFn, inputSeries, nextCoordinates); if (options.recordAllResults) { results.push(packageIterationResult(parameters, workingCoordinates, workingResult)); } if (acceptResult(bestResult, workingResult.metric, options)) { bestResult = workingResult.metric; bestCoordinates = workingCoordinates; } if (acceptResult(workingResult.metric, nextResult.metric, options)) { workingCoordinates = nextCoordinates; workingResult = nextResult; gotBetterResult = true; break; // Move to this neighbour and start again. } } if (!gotBetterResult) { // There is no better neighbour, break out. break; } } } return { bestResult: bestResult!, bestParameterValues: extractParameterValues(parameters, bestCoordinates!), durationMS: options.recordDuration ? (performance.now() - startTime) : undefined, allResults: options.recordAllResults ? results : undefined, }; } // // Performs a slow exhaustive grid search optimization. // function gridSearchOptimization<InputBarT extends IBar, IndicatorBarT extends InputBarT, ParameterT, IndexT>( strategy: IStrategy<InputBarT, IndicatorBarT, ParameterT, IndexT>, parameters: IParameterDef[], objectiveFn: ObjectiveFn, inputSeries: IDataFrame<IndexT, InputBarT>, options: IOptimizationOptions ): IOptimizationResult<ParameterT> { let bestResult: number | undefined; let bestCoordinates: number[] | undefined; const results: IterationResult<ParameterT>[] = []; const startTime = performance.now(); for (const coordinates of getAllCoordinates(parameters)) { const iterationResult = optimizationIteration(strategy, parameters, objectiveFn, inputSeries, coordinates); if (bestResult === undefined) { bestResult = iterationResult.metric; bestCoordinates = coordinates; } else if (acceptResult(bestResult, iterationResult.metric, options)) { bestResult = iterationResult.metric; bestCoordinates = coordinates; } if (options.recordAllResults) { results.push(packageIterationResult(parameters, coordinates, iterationResult)); } } return { bestResult: bestResult!, bestParameterValues: extractParameterValues(parameters, bestCoordinates!), durationMS: options.recordDuration ? (performance.now() - startTime) : undefined, allResults: options.recordAllResults ? results : undefined, }; } /** * Perform an optimization over multiple parameters. */ export function optimize<InputBarT extends IBar, IndicatorBarT extends InputBarT, ParameterT, IndexT> ( strategy: IStrategy<InputBarT, IndicatorBarT, ParameterT, IndexT>, parameters: IParameterDef[], objectiveFn: ObjectiveFn, inputSeries: IDataFrame<IndexT, InputBarT>, options?: IOptimizationOptions ): IOptimizationResult<ParameterT> { if (!isObject(strategy)) { throw new Error("Expected 'strategy' argument to 'optimize' to be an object that defines the trading strategy to be optimized."); } if (!isArray(parameters)) { throw new Error("Expected 'parameters' argument to 'optimize' to be an array that defines the various strategy parameters to be optimized."); } if (!isFunction(objectiveFn)) { throw new Error("Expected 'objectiveFn' argument to 'optimize' to be a function that computes an objective function for a set of trades."); } if (!isObject(inputSeries)) { throw new Error("Expected 'inputSeries' argument to 'optimize' to be a Data-Forge DataFrame object that provides the input data for optimization."); } if (!options) { options = {}; } else { options = Object.assign({}, options); // Copy so we can change. } if (options.searchDirection === undefined) { options.searchDirection = "max"; } if (options.optimizationType === undefined) { options.optimizationType = "grid"; } if (options.optimizationType === "hill-climb") { return hillClimbOptimization<InputBarT, IndicatorBarT, ParameterT, IndexT>(strategy, parameters, objectiveFn, inputSeries, options); } else if (options.optimizationType === "grid") { return gridSearchOptimization<InputBarT, IndicatorBarT, ParameterT, IndexT>(strategy, parameters, objectiveFn, inputSeries, options); } else { throw new Error(`Unexpected "optimizationType" field of "options" parameter to the "optimize" function. Expected "grid", or "hill-climb", Actual: "${options.optimizationType}".`); } }
the_stack
import { SagaIterator } from 'redux-saga'; import { call, put, select, takeEvery } from 'redux-saga/effects'; import { FETCH_GROUP_GRADING_SUMMARY } from '../../features/dashboard/DashboardTypes'; import { Grading, GradingOverview, GradingQuestion } from '../../features/grading/GradingTypes'; import { OverallState, Role, SourceLanguage, styliseSublanguage } from '../application/ApplicationTypes'; import { ACKNOWLEDGE_NOTIFICATIONS, AdminPanelCourseRegistration, FETCH_ADMIN_PANEL_COURSE_REGISTRATIONS, FETCH_ASSESSMENT, FETCH_AUTH, FETCH_COURSE_CONFIG, FETCH_GRADING, FETCH_GRADING_OVERVIEWS, FETCH_NOTIFICATIONS, FETCH_USER_AND_COURSE, SUBMIT_ANSWER, SUBMIT_GRADING, SUBMIT_GRADING_AND_CONTINUE, Tokens, UNSUBMIT_SUBMISSION, UPDATE_ASSESSMENT_CONFIGS, UPDATE_COURSE_CONFIG, UPDATE_LATEST_VIEWED_COURSE } from '../application/types/SessionTypes'; import { AssessmentOverview, AssessmentStatuses, FETCH_ASSESSMENT_OVERVIEWS, Question, SUBMIT_ASSESSMENT } from '../assessment/AssessmentTypes'; import { Notification, NotificationFilterFunction } from '../notificationBadge/NotificationBadgeTypes'; import { actions } from '../utils/ActionsHelper'; import { history } from '../utils/HistoryHelper'; import { showSuccessMessage, showWarningMessage } from '../utils/NotificationsHelper'; import { WorkspaceLocation } from '../workspace/WorkspaceTypes'; import { mockAssessmentConfigurations, mockAssessmentOverviews, mockAssessments } from './AssessmentMocks'; import { mockFetchGrading, mockFetchGradingOverview, mockGradingSummary } from './GradingMocks'; import { mockAdminPanelCourseRegistrations, mockCourseConfigurations, mockCourseRegistrations, mockNotifications, mockUser } from './UserMocks'; export function* mockBackendSaga(): SagaIterator { yield takeEvery(FETCH_AUTH, function* (action: ReturnType<typeof actions.fetchAuth>) { const tokens: Tokens = { accessToken: 'accessToken', refreshToken: 'refreshToken' }; yield put(actions.setTokens(tokens)); yield mockGetUserAndCourse(); const courseId: number = yield select((state: OverallState) => state.session.courseId!); yield history.push(`/courses/${courseId}`); }); const mockGetUserAndCourse = function* () { const user = { ...mockUser }; const courseRegistration = { ...mockCourseRegistrations[0] }; const courseConfiguration = { ...mockCourseConfigurations[0] }; const assessmentConfigurations = [...mockAssessmentConfigurations[0]]; const sublanguage: SourceLanguage = { chapter: courseConfiguration.sourceChapter, variant: courseConfiguration.sourceVariant, displayName: styliseSublanguage( courseConfiguration.sourceChapter, courseConfiguration.sourceVariant ) }; yield put(actions.setUser(user)); yield put(actions.setCourseRegistration(courseRegistration)); yield put(actions.setCourseConfiguration(courseConfiguration)); yield put(actions.setAssessmentConfigurations(assessmentConfigurations)); yield put(actions.updateSublanguage(sublanguage)); }; yield takeEvery(FETCH_USER_AND_COURSE, mockGetUserAndCourse); yield takeEvery(FETCH_COURSE_CONFIG, function* () { const courseConfiguration = { ...mockCourseConfigurations[0] }; yield put(actions.setCourseConfiguration(courseConfiguration)); }); yield takeEvery(FETCH_ASSESSMENT_OVERVIEWS, function* () { yield put(actions.updateAssessmentOverviews([...mockAssessmentOverviews])); }); yield takeEvery(FETCH_ASSESSMENT, function* (action: ReturnType<typeof actions.fetchAssessment>) { const id = action.payload; const assessment = mockAssessments[id - 1]; yield put(actions.updateAssessment({ ...assessment })); }); yield takeEvery(SUBMIT_ANSWER, function* (action: ReturnType<typeof actions.submitAnswer>): any { const questionId = action.payload.id; const answer = action.payload.answer; // Now, update the answer for the question in the assessment in the store const assessmentId = yield select( (state: OverallState) => state.workspaces.assessment.currentAssessment! ); const assessment = yield select((state: OverallState) => state.session.assessments.get(assessmentId) ); const newQuestions = assessment.questions.slice().map((question: Question) => { if (question.id === questionId) { question.answer = answer; } return question; }); const newAssessment = { ...assessment, questions: newQuestions }; yield put(actions.updateAssessment(newAssessment)); yield call(showSuccessMessage, 'Saved!', 1000); return yield put(actions.updateHasUnsavedChanges('assessment' as WorkspaceLocation, false)); }); yield takeEvery( SUBMIT_ASSESSMENT, function* (action: ReturnType<typeof actions.submitAssessment>): any { const assessmentId = action.payload; // Update the status of the assessment overview in the store const overviews: AssessmentOverview[] = yield select( (state: OverallState) => state.session.assessmentOverviews ); const newOverviews = overviews.map(overview => { if (overview.id === assessmentId) { return { ...overview, status: AssessmentStatuses.submitted }; } return overview; }); yield call(showSuccessMessage, 'Submitted!', 2000); return yield put(actions.updateAssessmentOverviews(newOverviews)); } ); yield takeEvery( FETCH_GRADING_OVERVIEWS, function* (action: ReturnType<typeof actions.fetchGradingOverviews>): any { const accessToken = yield select((state: OverallState) => state.session.accessToken); const filterToGroup = action.payload; const gradingOverviews = yield call(() => mockFetchGradingOverview(accessToken, filterToGroup) ); if (gradingOverviews !== null) { yield put(actions.updateGradingOverviews([...gradingOverviews])); } } ); yield takeEvery(FETCH_GRADING, function* (action: ReturnType<typeof actions.fetchGrading>): any { const submissionId = action.payload; const accessToken = yield select((state: OverallState) => state.session.accessToken); const grading = yield call(() => mockFetchGrading(accessToken, submissionId)); if (grading !== null) { yield put(actions.updateGrading(submissionId, [...grading])); } }); yield takeEvery( UNSUBMIT_SUBMISSION, function* (action: ReturnType<typeof actions.unsubmitSubmission>) { const { submissionId } = action.payload; const overviews: GradingOverview[] = yield select( (state: OverallState) => state.session.gradingOverviews || [] ); const index = overviews.findIndex( overview => overview.submissionId === submissionId && overview.submissionStatus === 'submitted' ); if (index === -1) { yield call(showWarningMessage, '400: Bad Request'); return; } const newOverviews = (overviews as GradingOverview[]).map(overview => { if (overview.submissionId === submissionId) { return { ...overview, submissionStatus: 'attempted' }; } return overview; }); yield call(showSuccessMessage, 'Unsubmit successful!', 1000); yield put(actions.updateGradingOverviews(newOverviews)); } ); const sendGrade = function* ( action: ReturnType<typeof actions.submitGrading | typeof actions.submitGradingAndContinue> ): any { const role: Role = yield select((state: OverallState) => state.session.role!); if (role === Role.Student) { return yield call(showWarningMessage, 'Only staff can submit answers.'); } const { submissionId, questionId, xpAdjustment, comments } = action.payload; // Now, update the grade for the question in the Grading in the store const grading: Grading = yield select((state: OverallState) => state.session.gradings.get(submissionId) ); const newGrading = grading.slice().map((gradingQuestion: GradingQuestion) => { if (gradingQuestion.question.id === questionId) { gradingQuestion.grade = { xpAdjustment, xp: gradingQuestion.grade.xp, comments }; } return gradingQuestion; }); yield put(actions.updateGrading(submissionId, newGrading)); yield call(showSuccessMessage, 'Submitted!', 1000); }; const sendGradeAndContinue = function* ( action: ReturnType<typeof actions.submitGradingAndContinue> ): any { const { submissionId } = action.payload; yield* sendGrade(action); const [currentQuestion, courseId] = yield select((state: OverallState) => [ state.workspaces.grading.currentQuestion, state.session.courseId! ]); /** * Move to next question for grading: this only works because the * SUBMIT_GRADING_AND_CONTINUE Redux action is currently only * used in the Grading Workspace * * If the questionId is out of bounds, the componentDidUpdate callback of * GradingWorkspace will cause a redirect back to '/courses/${courseId}/grading' */ yield history.push( `/courses/${courseId}/grading/${submissionId}/${(currentQuestion || 0) + 1}` ); }; yield takeEvery(SUBMIT_GRADING, sendGrade); yield takeEvery(SUBMIT_GRADING_AND_CONTINUE, sendGradeAndContinue); yield takeEvery( FETCH_NOTIFICATIONS, function* (action: ReturnType<typeof actions.fetchNotifications>) { yield put(actions.updateNotifications([...mockNotifications])); } ); yield takeEvery( ACKNOWLEDGE_NOTIFICATIONS, function* (action: ReturnType<typeof actions.acknowledgeNotifications>) { const notificationFilter: NotificationFilterFunction | undefined = action.payload.withFilter; const notifications: Notification[] = yield select( (state: OverallState) => state.session.notifications ); let notificationsToAcknowledge = notifications; if (notificationFilter) { notificationsToAcknowledge = notificationFilter(notifications); } if (notificationsToAcknowledge.length === 0) { return; } const ids = notificationsToAcknowledge.map(n => n.id); const newNotifications: Notification[] = notifications.filter( notification => !ids.includes(notification.id) ); yield put(actions.updateNotifications(newNotifications)); } ); yield takeEvery( UPDATE_LATEST_VIEWED_COURSE, function* (action: ReturnType<typeof actions.updateLatestViewedCourse>) { const { courseId } = action.payload; const idx = courseId - 1; // zero-indexed const courseConfiguration = { ...mockCourseConfigurations[idx] }; yield put(actions.setCourseConfiguration(courseConfiguration)); yield put(actions.setAssessmentConfigurations([...mockAssessmentConfigurations[idx]])); yield put(actions.setCourseRegistration({ ...mockCourseRegistrations[idx] })); yield put( actions.updateSublanguage({ chapter: courseConfiguration.sourceChapter, variant: courseConfiguration.sourceVariant, displayName: styliseSublanguage( courseConfiguration.sourceChapter, courseConfiguration.sourceVariant ) }) ); yield call(showSuccessMessage, `Switched to ${courseConfiguration.courseName}!`, 5000); } ); yield takeEvery( UPDATE_COURSE_CONFIG, function* (action: ReturnType<typeof actions.updateCourseConfig>) { const courseConfig = action.payload; yield put(actions.setCourseConfiguration(courseConfig)); yield call(showSuccessMessage, 'Updated successfully!', 1000); } ); yield takeEvery( UPDATE_ASSESSMENT_CONFIGS, function* (action: ReturnType<typeof actions.updateAssessmentConfigs>): any { const assessmentConfig = action.payload; yield put(actions.setAssessmentConfigurations(assessmentConfig)); yield call(showSuccessMessage, 'Updated successfully!', 1000); } ); yield takeEvery( FETCH_ADMIN_PANEL_COURSE_REGISTRATIONS, function* (action: ReturnType<typeof actions.fetchAdminPanelCourseRegistrations>) { const courseRegistrations: AdminPanelCourseRegistration[] = [ ...mockAdminPanelCourseRegistrations ]; yield put(actions.setAdminPanelCourseRegistrations(courseRegistrations)); } ); yield takeEvery(FETCH_GROUP_GRADING_SUMMARY, function* () { yield put(actions.updateGroupGradingSummary({ ...mockGradingSummary })); }); }
the_stack
import { assert } from 'chai' import { XrplNetwork } from 'xpring-common-js' import { XrpError, XrpUtils } from '../../../src' import XrpTrustSet from '../../../src/XRP/protobuf-wrappers/xrp-trust-set' import XRPSignerEntry from '../../../src/XRP/protobuf-wrappers/xrp-signer-entry' import XrpSignerListSet from '../../../src/XRP/protobuf-wrappers/xrp-signer-list-set' import XrpSetRegularKey from '../../../src/XRP/protobuf-wrappers/xrp-set-regular-key' import XrpPaymentChannelFund from '../../../src/XRP/protobuf-wrappers/xrp-payment-channel-fund' import XrpPaymentChannelCreate from '../../../src/XRP/protobuf-wrappers/xrp-payment-channel-create' import XrpPaymentChannelClaim from '../../../src/XRP/protobuf-wrappers/xrp-payment-channel-claim' import XrpOfferCreate from '../../../src/XRP/protobuf-wrappers/xrp-offer-create' import XrpOfferCancel from '../../../src/XRP/protobuf-wrappers/xrp-offer-cancel' import XrpEscrowFinish from '../../../src/XRP/protobuf-wrappers/xrp-escrow-finish' import XrpEscrowCreate from '../../../src/XRP/protobuf-wrappers/xrp-escrow-create' import XrpEscrowCancel from '../../../src/XRP/protobuf-wrappers/xrp-escrow-cancel' import XrpDepositPreauth from '../../../src/XRP/protobuf-wrappers/xrp-deposit-preauth' import XrpCheckCreate from '../../../src/XRP/protobuf-wrappers/xrp-check-create' import XrpCheckCash from '../../../src/XRP/protobuf-wrappers/xrp-check-cash' import XrpAccountSet from '../../../src/XRP/protobuf-wrappers/xrp-account-set' import XrpCurrencyAmount from '../../../src/XRP/protobuf-wrappers/xrp-currency-amount' import XrpCheckCancel from '../../../src/XRP/protobuf-wrappers/xrp-check-cancel' import XrpAccountDelete from '../../../src/XRP/protobuf-wrappers/xrp-account-delete' import { testAccountSetProtoAllFields, testAccountSetProtoOneFieldSet, testAccountDeleteProto, testAccountDeleteProtoNoTag, testCheckCancelProto, testCheckCashProtoWithAmount, testCheckCashProtoWithDeliverMin, testCheckCreateProtoAllFields, testCheckCreateProtoMandatoryFields, testDepositPreauthProtoSetAuthorize, testDepositPreauthProtoSetUnauthorize, testEscrowCancelProto, testEscrowCreateProtoAllFields, testEscrowCreateProtoMandatoryOnly, testEscrowFinishProtoAllFields, testEscrowFinishProtoMandatoryOnly, testOfferCancelProto, testOfferCreateProtoAllFields, testOfferCreateProtoMandatoryOnly, testPaymentChannelCreateProtoAllFields, testPaymentChannelCreateProtoMandatoryOnly, testPaymentChannelFundProtoAllFields, testPaymentChannelFundProtoMandatoryOnly, testSetRegularKeyProtoWithKey, testSetRegularKeyProtoNoKey, testSignerListSetProto, testSignerListSetProtoDelete, testTrustSetProtoAllFields, testTrustSetProtoMandatoryOnly, testInvalidAccountSetProtoBadDomain, testInvalidAccountSetProtoBadLowTransferRate, testInvalidAccountSetProtoBadHighTransferRate, testInvalidAccountSetProtoBadTickSize, testInvalidAccountSetProtoSameSetClearFlag, testInvalidAccountDeleteProto, testInvalidCheckCancelProto, testInvalidCheckCashProtoNoCheckId, testInvalidCheckCashProtoNoAmountDeliverMin, testInvalidDepositPreauthProtoNoAuthUnauth, testInvalidDepositPreauthProtoSetBadAuthorize, testInvalidDepositPreauthProtoSetBadUnauthorize, testInvalidCheckCreateProto, testInvalidCheckCreateProtoBadDestination, testInvalidCheckCreateProtoNoSendMax, testInvalidEscrowCancelProtoNoOwner, testInvalidEscrowCancelProtoBadOwner, testInvalidEscrowCancelProtoNoOfferSequence, testInvalidEscrowCreateProtoNoDestination, testInvalidEscrowCreateProtoBadDestination, testInvalidEscrowCreateProtoNoAmount, testInvalidEscrowCreateProtoBadCancelFinish, testInvalidEscrowCreateProtoNoCancelFinish, testInvalidEscrowCreateProtoNoFinishCondition, testInvalidEscrowCreateProtoNoXRP, testInvalidEscrowFinishProtoNoOwner, testInvalidEscrowFinishProtoBadOwner, testInvalidEscrowFinishProtoNoOfferSequence, testInvalidOfferCancelProto, testInvalidOfferCreateProtoNoTakerGets, testInvalidOfferCreateProtoNoTakerPays, testPaymentChannelClaimProtoAllFields, testPaymentChannelClaimProtoMandatoryOnly, testInvalidPaymentChannelClaimProtoNoChannel, testInvalidPaymentChannelClaimProtoSignatureNoPublicKey, testInvalidPaymentChannelCreateProtoNoAmount, testInvalidPaymentChannelCreateProtoNoDestination, testInvalidPaymentChannelCreateProtoBadDestination, testInvalidPaymentChannelCreateProtoNoSettleDelay, testInvalidPaymentChannelCreateProtoNoPublicKey, testInvalidPaymentChannelFundProtoNoAmount, testInvalidPaymentChannelFundProtoNoChannel, testInvalidSignerListSetProtoNoSignerQuorum, testInvalidSignerListSetProtoNoSignerEntries, testInvalidSignerListSetProtoTooManySignerEntries, testInvalidSignerListSetProtoRepeatAddresses, testInvalidTrustSetProto, testInvalidTrustSetProtoXRP, testSignerEntry1, testSignerEntry2, } from '../fakes/fake-xrp-transaction-type-protobufs' import { AccountSet, AccountDelete, } from '../../../src/XRP/Generated/web/org/xrpl/rpc/v1/transaction_pb' describe('Protobuf Conversions - Transaction Types', function (): void { // AccountSet it('Convert AccountSet protobuf with all fields to XrpAccountSet object', function (): void { // GIVEN an AccountSet protocol buffer with all fields set. // WHEN the protocol buffer is converted to a native Typescript type. const accountSet = XrpAccountSet.from(testAccountSetProtoAllFields) // THEN the AccountSet converted as expected. assert.deepEqual( accountSet?.clearFlag, testAccountSetProtoAllFields.getClearFlag()?.getValue(), ) assert.deepEqual( accountSet?.domain, testAccountSetProtoAllFields.getDomain()?.getValue(), ) assert.deepEqual( accountSet?.emailHash, testAccountSetProtoAllFields.getEmailHash()?.getValue(), ) assert.deepEqual( accountSet?.messageKey, testAccountSetProtoAllFields.getMessageKey()?.getValue(), ) assert.deepEqual( accountSet?.setFlag, testAccountSetProtoAllFields.getSetFlag()?.getValue(), ) assert.deepEqual( accountSet?.transferRate, testAccountSetProtoAllFields.getTransferRate()?.getValue(), ) assert.deepEqual( accountSet?.tickSize, testAccountSetProtoAllFields.getTickSize()?.getValue(), ) }) it('Convert AccountSet protobuf with one field to XrpAccountSet object', function (): void { // GIVEN an AccountSet protocol buffer with only one field set. // WHEN the protocol buffer is converted to a native Typescript type. const accountSet = XrpAccountSet.from(testAccountSetProtoOneFieldSet) // THEN the AccountSet converted as expected. assert.deepEqual( accountSet?.clearFlag, testAccountSetProtoAllFields.getClearFlag()?.getValue(), ) assert.isUndefined(accountSet?.domain) assert.isUndefined(accountSet?.emailHash) assert.isUndefined(accountSet?.messageKey) assert.isUndefined(accountSet?.setFlag) assert.isUndefined(accountSet?.transferRate) assert.isUndefined(accountSet?.tickSize) }) it('Convert empty AccountSet protobuf to XrpAccountSet object', function (): void { // GIVEN an AccountSet protocol buffer with only one field set. // WHEN the protocol buffer is converted to a native Typescript type. const accountSet = XrpAccountSet.from(new AccountSet()) // THEN the AccountSet converted as expected. assert.isUndefined(accountSet.clearFlag) assert.isUndefined(accountSet.domain) assert.isUndefined(accountSet.emailHash) assert.isUndefined(accountSet.messageKey) assert.isUndefined(accountSet.setFlag) assert.isUndefined(accountSet.transferRate) assert.isUndefined(accountSet.tickSize) }) it('Convert AccountSet protobuf with invalid domain field to XrpAccountSet object', function (): void { // GIVEN an AccountSet protocol buffer with invalid domain field set. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpAccountSet.from(testInvalidAccountSetProtoBadDomain) }, XrpError) }) it('Convert AccountSet protobuf with invalid low transferRate field to XrpAccountSet object', function (): void { // GIVEN an AccountSet protocol buffer with invalid transferRate field set. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpAccountSet.from(testInvalidAccountSetProtoBadLowTransferRate) }, XrpError) }) it('Convert AccountSet protobuf with invalid high transferRate field to XrpAccountSet object', function (): void { // GIVEN an AccountSet protocol buffer with invalid transferRate field set. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpAccountSet.from(testInvalidAccountSetProtoBadHighTransferRate) }, XrpError) }) it('Convert AccountSet protobuf with invalid tickSize field to XrpAccountSet object', function (): void { // GIVEN an AccountSet protocol buffer with invalid tickSize field set. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpAccountSet.from(testInvalidAccountSetProtoBadTickSize) }, XrpError) }) it('Convert AccountSet protobuf with same setFlag and clearFlag to XrpAccountSet object', function (): void { // GIVEN an AccountSet protocol buffer with setFlag == clearFlag. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpAccountSet.from(testInvalidAccountSetProtoSameSetClearFlag) }, XrpError) }) // AccountDelete it('Convert AccountDelete protobuf with all fields to XrpAccountDelete object', function (): void { // GIVEN an AccountDelete protocol buffer with all fields set. // WHEN the protocol buffer is converted to a native Typescript type. const accountDelete = XrpAccountDelete.from( testAccountDeleteProto, XrplNetwork.Test, ) // THEN the AccountDelete converted as expected. const expectedXAddress = XrpUtils.encodeXAddress( testAccountDeleteProto.getDestination()!.getValue()!.getAddress()!, testAccountDeleteProto.getDestinationTag()?.getValue(), true, ) assert.deepEqual(accountDelete?.destinationXAddress, expectedXAddress) }) it('Convert AccountDelete protobuf with no tag to XrpAccountDelete object', function (): void { // GIVEN an AccountDelete protocol buffer with only destination field set. // WHEN the protocol buffer is converted to a native Typescript type. const accountDelete = XrpAccountDelete.from( testAccountDeleteProtoNoTag, XrplNetwork.Test, ) // THEN the AccountDelete converted as expected. const expectedXAddress = XrpUtils.encodeXAddress( testAccountDeleteProtoNoTag.getDestination()!.getValue()!.getAddress()!, testAccountDeleteProtoNoTag.getDestinationTag()?.getValue(), true, ) assert.deepEqual(accountDelete?.destinationXAddress, expectedXAddress) }) it('Convert AccountDelete protobuf to XrpAccountDelete object - missing destination field', function (): void { // GIVEN an AccountDelete protocol buffer missing the destination field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpAccountDelete.from(new AccountDelete(), XrplNetwork.Test) }, XrpError) }) it('Convert AccountDelete protobuf to XrpAccountDelete object - bad destination field', function (): void { // GIVEN an AccountDelete protocol buffer with a destination field that can't convert to an XAddress. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpAccountDelete.from(testInvalidAccountDeleteProto, XrplNetwork.Test) }, XrpError) }) it('Convert CheckCancel protobuf to XrpCheckCancel object', function (): void { // GIVEN a CheckCancel protocol buffer. // WHEN the protocol buffer is converted to a native Typescript type. const checkCancel = XrpCheckCancel.from(testCheckCancelProto) // THEN the CheckCancel converted as expected. assert.equal( checkCancel?.checkId, testCheckCancelProto.getCheckId()?.getValue_asB64(), ) }) it('Convert CheckCancel protobuf with missing checkId', function (): void { // GIVEN a CheckCancel protocol buffer without a checkId. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpCheckCancel.from(testInvalidCheckCancelProto) }, XrpError) }) // CheckCash it('Convert CheckCash protobuf to XrpCheckCash object - amount field set', function (): void { // GIVEN a valid CheckCash protocol buffer with amount field set. // WHEN the protocol buffer is converted to a native Typescript type. const checkCash = XrpCheckCash.from(testCheckCashProtoWithAmount) // THEN the CheckCash converted as expected. assert.equal( checkCash?.checkId, testCheckCashProtoWithAmount.getCheckId()?.getValue_asB64(), ) assert.deepEqual( checkCash?.amount, XrpCurrencyAmount.from( testCheckCashProtoWithAmount.getAmount()!.getValue()!, ), ) assert.isUndefined(checkCash?.deliverMin) }) it('Convert CheckCash protobuf to XrpCheckCash object - deliverMin field set', function (): void { // GIVEN a valid CheckCash protocol buffer with deliverMin field set. // WHEN the protocol buffer is converted to a native Typescript type. const checkCash = XrpCheckCash.from(testCheckCashProtoWithDeliverMin) // THEN the CheckCash converted as expected. assert.equal( checkCash?.checkId, testCheckCashProtoWithDeliverMin.getCheckId()?.getValue_asB64(), ) assert.isUndefined(checkCash?.amount) assert.deepEqual( checkCash?.deliverMin, XrpCurrencyAmount.from( testCheckCashProtoWithDeliverMin.getDeliverMin()!.getValue()!, ), ) }) it('Convert invalid CheckCash protobuf to XrpCheckCash object - missing checkId', function (): void { // GIVEN an invalid CheckCash protocol buffer missing the checkId field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpCheckCash.from(testInvalidCheckCashProtoNoCheckId) }, XrpError) }) it('Convert invalid CheckCash protobuf to XrpCheckCash object - missing amount and deliverMin', function (): void { // GIVEN an invalid CheckCash protocol buffer missing both the amount and deliverMin fields. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpCheckCash.from(testInvalidCheckCashProtoNoAmountDeliverMin) }, XrpError) }) // CheckCreate it('Convert CheckCreate protobuf to XrpCheckCreate object - all fields', function (): void { // GIVEN a CheckCreate protocol buffer with all fields set. // WHEN the protocol buffer is converted to a native Typescript type. const checkCreate = XrpCheckCreate.from( testCheckCreateProtoAllFields, XrplNetwork.Test, ) // THEN the CheckCreate converted as expected. const expectedXAddress = XrpUtils.encodeXAddress( testCheckCreateProtoAllFields.getDestination()!.getValue()!.getAddress()!, testCheckCreateProtoAllFields.getDestinationTag()?.getValue(), true, ) assert.equal(checkCreate?.destinationXAddress, expectedXAddress) assert.deepEqual( checkCreate?.sendMax, XrpCurrencyAmount.from( testCheckCreateProtoAllFields.getSendMax()!.getValue()!, ), ) assert.equal( checkCreate?.expiration, testCheckCreateProtoAllFields.getExpiration()?.getValue(), ) assert.equal( checkCreate?.invoiceId, testCheckCreateProtoAllFields.getInvoiceId()?.getValue_asB64(), ) }) it('Convert CheckCreate protobuf to XrpCheckCreate object - mandatory fields', function (): void { // GIVEN a CheckCreate protocol buffer with only mandatory fields set. // WHEN the protocol buffer is converted to a native Typescript type. const checkCreate = XrpCheckCreate.from( testCheckCreateProtoMandatoryFields, XrplNetwork.Test, ) // THEN the CheckCreate converted as expected. const expectedXAddress = XrpUtils.encodeXAddress( testCheckCreateProtoMandatoryFields .getDestination()! .getValue()! .getAddress()!, testCheckCreateProtoMandatoryFields.getDestinationTag()?.getValue(), true, ) assert.equal(checkCreate?.destinationXAddress, expectedXAddress) assert.deepEqual( checkCreate?.sendMax, XrpCurrencyAmount.from( testCheckCreateProtoMandatoryFields.getSendMax()!.getValue()!, ), ) assert.isUndefined(checkCreate?.expiration) assert.isUndefined(checkCreate?.invoiceId) }) it('Convert invalid CheckCreate protobuf to XrpCheckCreate object - missing destination', function (): void { // GIVEN an invalid CheckCreate protocol buffer missing the destination field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpCheckCreate.from(testInvalidCheckCreateProto, XrplNetwork.Test) }, XrpError) }) it('Convert invalid CheckCreate protobuf to XrpCheckCreate object - bad destination', function (): void { // GIVEN an invalid CheckCreate protocol buffer with a bad destination field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpCheckCreate.from( testInvalidCheckCreateProtoBadDestination, XrplNetwork.Test, ) }, XrpError) }) it('Convert invalid CheckCreate protobuf to XrpCheckCreate object - no SendMax', function (): void { // GIVEN an invalid CheckCreate protocol buffer missing the SendMax field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpCheckCreate.from( testInvalidCheckCreateProtoNoSendMax, XrplNetwork.Test, ) }, XrpError) }) // DepositPreauth it('Convert DepositPreauth protobuf to XrpDepositPreauth object - authorize set', function (): void { // GIVEN a DepositPreauth protocol buffer with authorize field set. // WHEN the protocol buffer is converted to a native Typescript type. const depositPreauth = XrpDepositPreauth.from( testDepositPreauthProtoSetAuthorize, XrplNetwork.Test, ) // THEN the DepositPreauth converted as expected. const expectedXAddress = XrpUtils.encodeXAddress( testDepositPreauthProtoSetAuthorize .getAuthorize()! .getValue()! .getAddress()!, undefined, true, ) assert.equal(depositPreauth.authorizeXAddress, expectedXAddress) }) it('Convert DepositPreauth protobuf to XrpDepositPreauth object - unauthorize set', function (): void { // GIVEN a DepositPreauth protocol buffer with unauthorize field set. // WHEN the protocol buffer is converted to a native Typescript type. const depositPreauth = XrpDepositPreauth.from( testDepositPreauthProtoSetUnauthorize, XrplNetwork.Test, ) // THEN the DepositPreauth converted as expected. const expectedXAddress = XrpUtils.encodeXAddress( testDepositPreauthProtoSetUnauthorize .getUnauthorize()! .getValue()! .getAddress()!, undefined, true, ) assert.equal(depositPreauth.unauthorizeXAddress, expectedXAddress) }) it('Convert DepositPreauth protobuf to XrpDepositPreauth object - neither authorize nor unauthorize', function (): void { // GIVEN a DepositPreauth protocol buffer neither authorize nor unauthorize field set. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpDepositPreauth.from( testInvalidDepositPreauthProtoNoAuthUnauth, XrplNetwork.Test, ) }, XrpError) }) it('Convert DepositPreauth protobuf to XrpDepositPreauth object - bad authorize', function (): void { // GIVEN a DepositPreauth protocol buffer with a bad authorize address field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpDepositPreauth.from( testInvalidDepositPreauthProtoSetBadAuthorize, XrplNetwork.Test, ) }, XrpError) }) it('Convert DepositPreauth protobuf to XrpDepositPreauth object - bad unauthorize', function (): void { // GIVEN a DepositPreauth protocol buffer with a bad unauthorize address field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpDepositPreauth.from( testInvalidDepositPreauthProtoSetBadUnauthorize, XrplNetwork.Test, ) }, XrpError) }) // Escrow Cancel it('Convert EscrowCancel protobuf to XrpEscrowCancel object - valid fields', function (): void { // GIVEN an EscrowCancel protocol buffer with all fields set. // WHEN the protocol buffer is converted to a native Typescript type. const escrowCancel = XrpEscrowCancel.from( testEscrowCancelProto, XrplNetwork.Test, ) // THEN the EscrowCancel converted as expected. const expectedXAddress = XrpUtils.encodeXAddress( testEscrowCancelProto.getOwner()!.getValue()!.getAddress()!, undefined, true, ) assert.equal(escrowCancel?.ownerXAddress, expectedXAddress) assert.equal( escrowCancel?.offerSequence, testEscrowCancelProto.getOfferSequence()?.getValue(), ) }) it('Convert EscrowCancel protobuf to XrpEscrowCancel object - missing owner field', function (): void { // GIVEN an EscrowCancel protocol buffer missing required owner field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpEscrowCancel.from( testInvalidEscrowCancelProtoNoOwner, XrplNetwork.Test, ) }, XrpError) }) it('Convert EscrowCancel protobuf to XrpEscrowCancel object - bad owner field', function (): void { // GIVEN an EscrowCancel protocol buffer with a bad owner field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpEscrowCancel.from( testInvalidEscrowCancelProtoBadOwner, XrplNetwork.Test, ) }, XrpError) }) it('Convert EscrowCancel protobuf to XrpEscrowCancel object - no OfferSequence field', function (): void { // GIVEN an EscrowCancel protocol buffer missing required offerSequence field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpEscrowCancel.from( testInvalidEscrowCancelProtoNoOfferSequence, XrplNetwork.Test, ) }, XrpError) }) // EscrowCreate it('Convert EscrowCreate protobuf to XrpEscrowCreate object - all fields', function (): void { // GIVEN an EscrowCreate protocol buffer with all fields set. // WHEN the protocol buffer is converted to a native Typescript type. const escrowCreate = XrpEscrowCreate.from( testEscrowCreateProtoAllFields, XrplNetwork.Test, ) // THEN the EscrowCreate converted as expected. const expectedXAddress = XrpUtils.encodeXAddress( testEscrowCreateProtoAllFields .getDestination()! .getValue()! .getAddress()!, testEscrowCreateProtoAllFields.getDestinationTag()?.getValue(), true, ) assert.deepEqual( escrowCreate?.amount, XrpCurrencyAmount.from( testEscrowCreateProtoAllFields.getAmount()!.getValue()!, ), ) assert.equal(escrowCreate?.destinationXAddress, expectedXAddress) assert.equal( escrowCreate?.cancelAfter, testEscrowCreateProtoAllFields.getCancelAfter()?.getValue(), ) assert.equal( escrowCreate?.finishAfter, testEscrowCreateProtoAllFields.getFinishAfter()?.getValue(), ) assert.equal( escrowCreate?.condition, testEscrowCreateProtoAllFields.getCondition()?.getValue_asB64(), ) }) it('Convert EscrowCreate protobuf to XrpEscrowCreate object - mandatory fields only', function (): void { // GIVEN an EscrowCreate protocol buffer with only mandatory fields set. // WHEN the protocol buffer is converted to a native Typescript type. const escrowCreate = XrpEscrowCreate.from( testEscrowCreateProtoMandatoryOnly, XrplNetwork.Test, ) // THEN the EscrowCreate converted as expected. const expectedXAddress = XrpUtils.encodeXAddress( testEscrowCreateProtoMandatoryOnly .getDestination()! .getValue()! .getAddress()!, testEscrowCreateProtoMandatoryOnly.getDestinationTag()?.getValue(), true, ) assert.deepEqual( escrowCreate?.amount, XrpCurrencyAmount.from( testEscrowCreateProtoMandatoryOnly.getAmount()!.getValue()!, ), ) assert.equal(escrowCreate?.destinationXAddress, expectedXAddress) assert.isUndefined(escrowCreate?.cancelAfter) assert.equal( escrowCreate?.finishAfter, testEscrowCreateProtoMandatoryOnly.getFinishAfter()?.getValue(), ) assert.isUndefined(escrowCreate?.condition) }) it('Convert EscrowCreate protobuf to XrpEscrowCreate object - missing destination field', function (): void { // GIVEN an EscrowCreate protocol buffer that's missing the destination field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpEscrowCreate.from( testInvalidEscrowCreateProtoNoDestination, XrplNetwork.Test, ) }, XrpError) }) it('Convert EscrowCreate protobuf to XrpEscrowCreate object - bad destination field', function (): void { // GIVEN an EscrowCreate protocol buffer with a bad destination field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpEscrowCreate.from( testInvalidEscrowCreateProtoBadDestination, XrplNetwork.Test, ) }, XrpError) }) it('Convert EscrowCreate protobuf to XrpEscrowCreate object - missing amount field', function (): void { // GIVEN an EscrowCreate protocol buffer that's missing the amount field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpEscrowCreate.from( testInvalidEscrowCreateProtoNoAmount, XrplNetwork.Test, ) }, XrpError) }) it('Convert EscrowCreate protobuf to XrpEscrowCreate object - amount not XRP', function (): void { // GIVEN an EscrowCreate protocol buffer with a non-XRP amount. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpEscrowCreate.from(testInvalidEscrowCreateProtoNoXRP, XrplNetwork.Test) }, XrpError) }) it('Convert EscrowCreate protobuf to XrpEscrowCreate object - missing cancelAfter and finishAfter fields', function (): void { // GIVEN an EscrowCreate protocol buffer that's missing both the cancelAfter and finishAfter fields. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpEscrowCreate.from( testInvalidEscrowCreateProtoNoCancelFinish, XrplNetwork.Test, ) }, XrpError) }) it('Convert EscrowCreate protobuf to XrpEscrowCreate object - bad cancelAfter and finishAfter fields', function (): void { // GIVEN an EscrowCreate protocol buffer with a finishAfter field that is not before the cancelAfter field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpEscrowCreate.from( testInvalidEscrowCreateProtoBadCancelFinish, XrplNetwork.Test, ) }, XrpError) }) it('Convert EscrowCreate protobuf to XrpEscrowCreate object - no finishAfter and condition fields', function (): void { // GIVEN an EscrowCreate protocol buffer that's missing both the finishAfter and condition fields. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpEscrowCreate.from( testInvalidEscrowCreateProtoNoFinishCondition, XrplNetwork.Test, ) }, XrpError) }) // EscrowFinish it('Convert EscrowFinish protobuf to XrpEscrowFinish object - all fields', function (): void { // GIVEN an EscrowFinish protocol buffer with all fields set. // WHEN the protocol buffer is converted to a native Typescript type. const escrowFinish = XrpEscrowFinish.from( testEscrowFinishProtoAllFields, XrplNetwork.Test, ) // THEN the EscrowFinish converted as expected. const expectedXAddress = XrpUtils.encodeXAddress( testEscrowFinishProtoAllFields.getOwner()!.getValue()!.getAddress()!, undefined, true, ) assert.deepEqual(escrowFinish?.ownerXAddress, expectedXAddress) assert.equal( escrowFinish?.offerSequence, testEscrowFinishProtoAllFields.getOfferSequence()?.getValue(), ) assert.equal( escrowFinish?.condition, testEscrowFinishProtoAllFields.getCondition()?.getValue(), ) assert.equal( escrowFinish?.fulfillment, testEscrowFinishProtoAllFields.getFulfillment()?.getValue(), ) }) it('Convert EscrowFinish protobuf to XrpEscrowFinish object - mandatory fields only', function (): void { // GIVEN an EscrowFinish protocol buffer with only mandatory fields set. // WHEN the protocol buffer is converted to a native Typescript type. const escrowFinish = XrpEscrowFinish.from( testEscrowFinishProtoMandatoryOnly, XrplNetwork.Test, ) // THEN the EscrowFinish converted as expected. const expectedXAddress = XrpUtils.encodeXAddress( testEscrowFinishProtoMandatoryOnly.getOwner()!.getValue()!.getAddress()!, undefined, true, ) assert.deepEqual(escrowFinish?.ownerXAddress, expectedXAddress) assert.equal( escrowFinish?.offerSequence, testEscrowFinishProtoMandatoryOnly.getOfferSequence()?.getValue(), ) assert.isUndefined(escrowFinish?.condition) assert.isUndefined(escrowFinish?.fulfillment) }) it('Convert EscrowFinish protobuf to XrpEscrowFinish object - missing owner', function (): void { // GIVEN an EscrowFinish protocol buffer missing the owner field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpEscrowFinish.from( testInvalidEscrowFinishProtoNoOwner, XrplNetwork.Test, ) }, XrpError) }) it('Convert EscrowFinish protobuf to XrpEscrowFinish object - bad owner', function (): void { // GIVEN an EscrowFinish protocol buffer with a bad owner field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpEscrowFinish.from( testInvalidEscrowFinishProtoBadOwner, XrplNetwork.Test, ) }, XrpError) }) it('Convert EscrowFinish protobuf to XrpEscrowFinish object - missing offerSequence', function (): void { // GIVEN an EscrowFinish protocol buffer missing the offerSequence field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpEscrowFinish.from( testInvalidEscrowFinishProtoNoOfferSequence, XrplNetwork.Test, ) }, XrpError) }) // OfferCancel it('Convert OfferCancel protobuf to XrpOfferCancel object', function (): void { // GIVEN an OfferCancel protocol buffer with offerSequence field set. // WHEN the protocol buffer is converted to a native Typescript type. const offerCancel = XrpOfferCancel.from(testOfferCancelProto) // THEN the OfferCancel converted as expected. assert.deepEqual( offerCancel?.offerSequence, testOfferCancelProto.getOfferSequence()?.getValue(), ) }) it('Convert OfferCancel protobuf to XrpOfferCancel object - missing required field', function (): void { // GIVEN an OfferCancel protocol buffer missing the offerSequence field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpOfferCancel.from(testInvalidOfferCancelProto) }, XrpError) }) // OfferCreate it('Convert OfferCreate protobuf to XrpOfferCreate object', function (): void { // GIVEN an OfferCreate protocol buffer with all fields set. // WHEN the protocol buffer is converted to a native Typescript type. const offerCreate = XrpOfferCreate.from(testOfferCreateProtoAllFields) // THEN the OfferCreate converted as expected. assert.equal( offerCreate?.expiration, testOfferCreateProtoAllFields.getExpiration()?.getValue(), ) assert.equal( offerCreate?.offerSequence, testOfferCreateProtoAllFields.getOfferSequence()?.getValue(), ) assert.deepEqual( offerCreate?.takerGets, XrpCurrencyAmount.from( testOfferCreateProtoAllFields.getTakerGets()!.getValue()!, ), ) assert.deepEqual( offerCreate?.takerPays, XrpCurrencyAmount.from( testOfferCreateProtoAllFields.getTakerPays()!.getValue()!, ), ) }) it('Convert OfferCreate protobuf to XrpOfferCreate object - mandatory fields', function (): void { // GIVEN an OfferCreate protocol buffer with only mandatory fields set. // WHEN the protocol buffer is converted to a native Typescript type. const offerCreate = XrpOfferCreate.from(testOfferCreateProtoMandatoryOnly) // THEN the OfferCreate converted as expected. assert.isUndefined(offerCreate?.expiration) assert.isUndefined(offerCreate?.offerSequence) assert.deepEqual( offerCreate?.takerGets, XrpCurrencyAmount.from( testOfferCreateProtoMandatoryOnly.getTakerGets()!.getValue()!, ), ) assert.deepEqual( offerCreate?.takerPays, XrpCurrencyAmount.from( testOfferCreateProtoMandatoryOnly.getTakerPays()!.getValue()!, ), ) }) it('Convert OfferCreate protobuf to XrpOfferCreate object - missing required TakerGets field', function (): void { // GIVEN an OfferCreate protocol buffer missing the TakerGets field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpOfferCreate.from(testInvalidOfferCreateProtoNoTakerGets) }, XrpError) }) it('Convert OfferCreate protobuf to XrpOfferCreate object - missing required TakerPays field', function (): void { // GIVEN an OfferCreate protocol buffer missing the TakerPays field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpOfferCreate.from(testInvalidOfferCreateProtoNoTakerPays) }, XrpError) }) // PaymentChannelClaim it('Convert PaymentChannelClaim protobuf to XrpPaymentChannelClaim object - all fields', function (): void { // GIVEN a PaymentChannelClaim protocol buffer with all fields set. // WHEN the protocol buffer is converted to a native Typescript type. const paymentChannelClaim = XrpPaymentChannelClaim.from( testPaymentChannelClaimProtoAllFields, ) // THEN the PaymentChannelClaim converted as expected. assert.equal( paymentChannelClaim?.channel, testPaymentChannelClaimProtoAllFields.getChannel()?.getValue_asB64(), ) assert.deepEqual( paymentChannelClaim?.balance, XrpCurrencyAmount.from( testPaymentChannelClaimProtoAllFields.getBalance()!.getValue()!, ), ) assert.deepEqual( paymentChannelClaim?.amount, XrpCurrencyAmount.from( testPaymentChannelClaimProtoAllFields.getAmount()!.getValue()!, ), ) assert.equal( paymentChannelClaim?.signature, testPaymentChannelClaimProtoAllFields .getPaymentChannelSignature() ?.getValue_asB64(), ) assert.equal( paymentChannelClaim?.publicKey, testPaymentChannelClaimProtoAllFields.getPublicKey()?.getValue_asB64(), ) }) it('Convert PaymentChannelClaim protobuf to XrpPaymentChannelClaim object - mandatory field', function (): void { // GIVEN a PaymentChannelClaim protocol buffer with only mandatory field set. // WHEN the protocol buffer is converted to a native Typescript type. const paymentChannelClaim = XrpPaymentChannelClaim.from( testPaymentChannelClaimProtoMandatoryOnly, ) // THEN the PaymentChannelClaim converted as expected. assert.equal( paymentChannelClaim?.channel, testPaymentChannelClaimProtoMandatoryOnly.getChannel()?.getValue_asB64(), ) assert.isUndefined(paymentChannelClaim?.balance) assert.isUndefined(paymentChannelClaim?.amount) assert.isUndefined(paymentChannelClaim?.signature) assert.isUndefined(paymentChannelClaim?.publicKey) }) it('Convert PaymentChannelClaim protobuf to XrpPaymentChannelClaim object - missing mandatory field', function (): void { // GIVEN a PaymentChannelClaim protocol buffer missing the mandatory field. // WHEN the protocol buffer is converted to a native Typescript type. assert.throws(() => { XrpPaymentChannelClaim.from(testInvalidPaymentChannelClaimProtoNoChannel) }, XrpError) }) it('Convert PaymentChannelClaim protobuf to XrpPaymentChannelClaim object - missing signature with public key', function (): void { // GIVEN a PaymentChannelClaim protocol buffer missing a signature when there is a public key. // WHEN the protocol buffer is converted to a native Typescript type. assert.throws(() => { XrpPaymentChannelClaim.from( testInvalidPaymentChannelClaimProtoSignatureNoPublicKey, ) }, XrpError) }) // PaymentChannelCreate it('Convert PaymentChannelCreate protobuf to XrpPaymentChannelCreate object - all fields', function (): void { // GIVEN a PaymentChannelCreate protocol buffer with all fields set. // WHEN the protocol buffer is converted to a native Typescript type. const paymentChannelCreate = XrpPaymentChannelCreate.from( testPaymentChannelCreateProtoAllFields, XrplNetwork.Test, ) // THEN the PaymentChannelCreate converted as expected. const expectedXAddress = XrpUtils.encodeXAddress( testPaymentChannelCreateProtoAllFields .getDestination()! .getValue()! .getAddress()!, testPaymentChannelCreateProtoAllFields.getDestinationTag()?.getValue(), true, ) assert.deepEqual( paymentChannelCreate?.amount, XrpCurrencyAmount.from( testPaymentChannelCreateProtoAllFields.getAmount()!.getValue()!, ), ) assert.equal(paymentChannelCreate?.destinationXAddress, expectedXAddress) assert.equal( paymentChannelCreate?.settleDelay, testPaymentChannelCreateProtoAllFields.getSettleDelay()?.getValue(), ) assert.equal( paymentChannelCreate?.publicKey, testPaymentChannelCreateProtoAllFields.getPublicKey()?.getValue_asB64(), ) assert.equal( paymentChannelCreate?.cancelAfter, testPaymentChannelCreateProtoAllFields.getCancelAfter()?.getValue(), ) }) it('Convert PaymentChannelCreate protobuf to XrpPaymentChannelCreate object - mandatory fields', function (): void { // GIVEN a PaymentChannelCreate protocol buffer with only mandatory fields set. // WHEN the protocol buffer is converted to a native Typescript type. const paymentChannelCreate = XrpPaymentChannelCreate.from( testPaymentChannelCreateProtoMandatoryOnly, XrplNetwork.Test, ) // THEN the PaymentChannelCreate converted as expected. const expectedXAddress = XrpUtils.encodeXAddress( testPaymentChannelCreateProtoMandatoryOnly .getDestination()! .getValue()! .getAddress()!, testPaymentChannelCreateProtoMandatoryOnly .getDestinationTag() ?.getValue(), true, ) assert.deepEqual( paymentChannelCreate?.amount, XrpCurrencyAmount.from( testPaymentChannelCreateProtoMandatoryOnly.getAmount()!.getValue()!, ), ) assert.equal(paymentChannelCreate?.destinationXAddress, expectedXAddress) assert.equal( paymentChannelCreate?.settleDelay, testPaymentChannelCreateProtoMandatoryOnly.getSettleDelay()?.getValue(), ) assert.equal( paymentChannelCreate?.publicKey, testPaymentChannelCreateProtoMandatoryOnly .getPublicKey() ?.getValue_asB64(), ) assert.isUndefined(paymentChannelCreate?.cancelAfter) }) it('Convert PaymentChannelCreate protobuf to XrpPaymentChannelCreate object - missing amount', function (): void { // GIVEN a PaymentChannelCreate protocol buffer missing the amount field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpPaymentChannelCreate.from( testInvalidPaymentChannelCreateProtoNoAmount, XrplNetwork.Test, ) }, XrpError) }) it('Convert PaymentChannelCreate protobuf to XrpPaymentChannelCreate object - missing destination', function (): void { // GIVEN a PaymentChannelCreate protocol buffer missing the destination field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpPaymentChannelCreate.from( testInvalidPaymentChannelCreateProtoNoDestination, XrplNetwork.Test, ) }, XrpError) }) it('Convert PaymentChannelCreate protobuf to XrpPaymentChannelCreate object - bad destination', function (): void { // GIVEN a PaymentChannelCreate protocol buffer with a bad destination field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpPaymentChannelCreate.from( testInvalidPaymentChannelCreateProtoBadDestination, XrplNetwork.Test, ) }, XrpError) }) it('Convert PaymentChannelCreate protobuf to XrpPaymentChannelCreate object - missing PublicKey', function (): void { // GIVEN a PaymentChannelCreate protocol buffer missing the publicKey field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpPaymentChannelCreate.from( testInvalidPaymentChannelCreateProtoNoPublicKey, XrplNetwork.Test, ) }, XrpError) }) it('Convert PaymentChannelCreate protobuf to XrpPaymentChannelCreate object - missing SettleDelay', function (): void { // GIVEN a PaymentChannelCreate protocol buffer missing the settleDelay field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpPaymentChannelCreate.from( testInvalidPaymentChannelCreateProtoNoSettleDelay, XrplNetwork.Test, ) }, XrpError) }) // PaymentChannelFund it('Convert PaymentChannelFund protobuf to XrpPaymentChannelFund object - all fields', function (): void { // GIVEN a PaymentChannelFund protocol buffer with all fields set. // WHEN the protocol buffer is converted to a native Typescript type. const paymentChannelFund = XrpPaymentChannelFund.from( testPaymentChannelFundProtoAllFields, ) // THEN the PaymentChannelFund converted as expected. assert.equal( paymentChannelFund?.channel, testPaymentChannelFundProtoAllFields.getChannel()?.getValue(), ) assert.deepEqual( paymentChannelFund?.amount, XrpCurrencyAmount.from( testPaymentChannelFundProtoAllFields.getAmount()!.getValue()!, ), ) assert.equal( paymentChannelFund?.expiration, testPaymentChannelFundProtoAllFields.getExpiration()?.getValue(), ) }) it('Convert PaymentChannelFund protobuf to XrpPaymentChannelFund object - mandatory fields', function (): void { // GIVEN a PaymentChannelFund protocol buffer with only mandatory fields set. // WHEN the protocol buffer is converted to a native Typescript type. const paymentChannelFund = XrpPaymentChannelFund.from( testPaymentChannelFundProtoMandatoryOnly, ) // THEN the PaymentChannelFund converted as expected. assert.equal( paymentChannelFund?.channel, testPaymentChannelFundProtoMandatoryOnly.getChannel()?.getValue(), ) assert.deepEqual( paymentChannelFund?.amount, XrpCurrencyAmount.from( testPaymentChannelFundProtoMandatoryOnly.getAmount()!.getValue()!, ), ) assert.isUndefined(paymentChannelFund?.expiration) }) it('Convert PaymentChannelFund protobuf to XrpPaymentChannelFund object - missing amount', function (): void { // GIVEN a PaymentChannelFund protocol buffer missing the required amount field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpPaymentChannelFund.from(testInvalidPaymentChannelFundProtoNoAmount) }, XrpError) }) it('Convert PaymentChannelFund protobuf to XrpPaymentChannelFund object - missing channel', function (): void { // GIVEN a PaymentChannelFund protocol buffer missing the required channel field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpPaymentChannelFund.from(testInvalidPaymentChannelFundProtoNoChannel) }, XrpError) }) // SetRegularKey it('Convert SetRegularKey protobuf to XrpSetRegularKey object - key set', function (): void { // GIVEN a SetRegularKey protocol buffer with regularKey set. // WHEN the protocol buffer is converted to a native Typescript type. const setRegularKey = XrpSetRegularKey.from(testSetRegularKeyProtoWithKey) // THEN the SetRegularKey converted as expected. assert.equal( setRegularKey?.regularKey, testSetRegularKeyProtoWithKey.getRegularKey()?.getValue()?.getAddress(), ) }) it('Convert SetRegularKey protobuf to XrpSetRegularKey object - no key', function (): void { // GIVEN a SetRegularKey protocol buffer without regularKey set. // WHEN the protocol buffer is converted to a native Typescript type. const setRegularKey = XrpSetRegularKey.from(testSetRegularKeyProtoNoKey) // THEN the result is undefined. assert.isUndefined(setRegularKey?.regularKey) }) // SignerListSet it('Convert SignerListSet protobuf to XrpSignerListSet object - all fields set', function (): void { // GIVEN a SetRegularKey protocol buffer with all fields set. // WHEN the protocol buffer is converted to a native Typescript type. const signerListSet = XrpSignerListSet.from( testSignerListSetProto, XrplNetwork.Test, ) // THEN the SignerListSet converted as expected. const expectedSignerEntries: Array<XRPSignerEntry> = [ XRPSignerEntry.from(testSignerEntry1, XrplNetwork.Test), XRPSignerEntry.from(testSignerEntry2, XrplNetwork.Test), ] assert.equal( signerListSet?.signerQuorum, testSignerListSetProto.getSignerQuorum()?.getValue(), ) assert.deepEqual(signerListSet?.signerEntries, expectedSignerEntries) }) it('Convert SignerListSet protobuf to XrpSignerListSet object - delete', function (): void { // GIVEN a SetRegularKey protocol buffer with all fields set. // WHEN the protocol buffer is converted to a native Typescript type. const signerListSet = XrpSignerListSet.from( testSignerListSetProtoDelete, XrplNetwork.Test, ) assert.equal( signerListSet.signerQuorum, testSignerListSetProtoDelete.getSignerQuorum()?.getValue(), ) assert.deepEqual(signerListSet.signerEntries, []) }) it('Convert SignerListSet protobuf to XrpSignerListSet object - missing signerQuorum', function (): void { // GIVEN a SignerListSet protocol buffer without signerQuorum set. // WHEN the protocol buffer is converted to a native Typescript type. assert.throws(() => { XrpSignerListSet.from( testInvalidSignerListSetProtoNoSignerQuorum, XrplNetwork.Test, ) }, XrpError) }) it('Convert SignerListSet protobuf to XrpSignerListSet object - missing signerEntries', function (): void { // GIVEN a SignerListSet protocol buffer without signerEntries set. // WHEN the protocol buffer is converted to a native Typescript type. assert.throws(() => { XrpSignerListSet.from( testInvalidSignerListSetProtoNoSignerEntries, XrplNetwork.Test, ) }, XrpError) }) it('Convert SignerListSet protobuf to XrpSignerListSet object - signerEntries too large', function (): void { // GIVEN a SignerListSet protocol buffer with too many elements in signerEntries. // WHEN the protocol buffer is converted to a native Typescript type. assert.throws(() => { XrpSignerListSet.from( testInvalidSignerListSetProtoTooManySignerEntries, XrplNetwork.Test, ) }, XrpError) }) it('Convert SignerListSet protobuf to XrpSignerListSet object - repeat addresses in signerEntries', function (): void { // GIVEN a SignerListSet protocol buffer with repeat addresses in signerEntries. // WHEN the protocol buffer is converted to a native Typescript type. assert.throws(() => { XrpSignerListSet.from( testInvalidSignerListSetProtoRepeatAddresses, XrplNetwork.Test, ) }, XrpError) }) // TrustSet it('Convert TrustSet protobuf to XrpTrustSet object - all fields set', function (): void { // GIVEN a TrustSet protocol buffer with all fields set. // WHEN the protocol buffer is converted to a native Typescript type. const trustSet = XrpTrustSet.from(testTrustSetProtoAllFields) // THEN the TrustSet converted as expected. assert.deepEqual( trustSet?.limitAmount, XrpCurrencyAmount.from( testTrustSetProtoAllFields.getLimitAmount()!.getValue()!, ), ) assert.equal( trustSet?.qualityIn, testTrustSetProtoAllFields.getQualityIn()?.getValue(), ) assert.equal( trustSet?.qualityOut, testTrustSetProtoAllFields.getQualityOut()?.getValue(), ) }) it('Convert TrustSet protobuf to XrpTrustSet object - mandatory fields set', function (): void { // GIVEN a TrustSet protocol buffer with only mandatory fields set. // WHEN the protocol buffer is converted to a native Typescript type. const trustSet = XrpTrustSet.from(testTrustSetProtoMandatoryOnly) // THEN the TrustSet converted as expected. assert.deepEqual( trustSet?.limitAmount, XrpCurrencyAmount.from( testTrustSetProtoMandatoryOnly.getLimitAmount()!.getValue()!, ), ) assert.isUndefined(trustSet?.qualityIn) assert.isUndefined(trustSet?.qualityOut) }) it('Convert TrustSet protobuf to XrpTrustSet object - missing mandatory field', function (): void { // GIVEN a TrustSet protocol buffer missing mandatory limitAmount field. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpTrustSet.from(testInvalidTrustSetProto) }, XrpError) }) it('Convert TrustSet protobuf to XrpTrustSet object - uses XRP', function (): void { // GIVEN a TrustSet protocol buffer using XRP. // WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown. assert.throws(() => { XrpTrustSet.from(testInvalidTrustSetProtoXRP) }, XrpError) }) })
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [panorama](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awspanorama.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Panorama extends PolicyStatement { public servicePrefix = 'panorama'; /** * Statement provider for service [panorama](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awspanorama.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 create an AWS Panorama application * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/panorama/latest/dev/API_CreateApp.html */ public toCreateApp() { return this.to('CreateApp'); } /** * Grants permission to deploy an AWS Panorama application * * Access Level: Write * * https://docs.aws.amazon.com/panorama/latest/dev/API_CreateAppDeployment.html */ public toCreateAppDeployment() { return this.to('CreateAppDeployment'); } /** * Grants permission to create a version of an AWS Panorama application * * Access Level: Write * * https://docs.aws.amazon.com/panorama/latest/dev/API_CreateAppVersion.html */ public toCreateAppVersion() { return this.to('CreateAppVersion'); } /** * Grants permission to create an AWS Panorama datasource * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/panorama/latest/dev/API_CreateDataSource.html */ public toCreateDataSource() { return this.to('CreateDataSource'); } /** * Grants permission to configure a deployment for an AWS Panorama application * * Access Level: Write * * https://docs.aws.amazon.com/panorama/latest/dev/API_CreateDeploymentConfiguration.html */ public toCreateDeploymentConfiguration() { return this.to('CreateDeploymentConfiguration'); } /** * Grants permission to register an AWS Panorama Appliance * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/panorama/latest/dev/API_CreateDevice.html */ public toCreateDevice() { return this.to('CreateDevice'); } /** * Grants permission to apply a software update to an AWS Panorama Appliance * * Access Level: Write * * https://docs.aws.amazon.com/panorama/latest/dev/API_CreateDeviceUpdate.html */ public toCreateDeviceUpdate() { return this.to('CreateDeviceUpdate'); } /** * Grants permission to generate a list of cameras on the same network as an AWS Panorama Appliance * * Access Level: Write * * https://docs.aws.amazon.com/panorama/latest/dev/API_CreateInputList.html */ public toCreateInputs() { return this.to('CreateInputs'); } /** * Grants permission to import a machine learning model into AWS Panorama * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/panorama/latest/dev/API_CreateModel.html */ public toCreateModel() { return this.to('CreateModel'); } /** * Grants permission to generate a list of streams available to an AWS Panorama Appliance * * Access Level: Write * * https://docs.aws.amazon.com/panorama/latest/dev/API_CreateStreamsList.html */ public toCreateStreams() { return this.to('CreateStreams'); } /** * Grants permission to delete an AWS Panorama application * * Access Level: Write * * https://docs.aws.amazon.com/panorama/latest/dev/API_DeleteApp.html */ public toDeleteApp() { return this.to('DeleteApp'); } /** * Grants permission to delete a version of an AWS Panorama application * * Access Level: Write * * https://docs.aws.amazon.com/panorama/latest/dev/API_DeleteAppVersion.html */ public toDeleteAppVersion() { return this.to('DeleteAppVersion'); } /** * Grants permission to delete an AWS Panorama datasource * * Access Level: Write * * https://docs.aws.amazon.com/panorama/latest/dev/API_DeleteDataSource.html */ public toDeleteDataSource() { return this.to('DeleteDataSource'); } /** * Grants permission to deregister an AWS Panorama Appliance * * Access Level: Write * * https://docs.aws.amazon.com/panorama/latest/dev/API_DeleteDevice.html */ public toDeleteDevice() { return this.to('DeleteDevice'); } /** * Grants permission to delete a machine learning model from AWS Panorama * * Access Level: Write * * https://docs.aws.amazon.com/panorama/latest/dev/API_DeleteModel.html */ public toDeleteModel() { return this.to('DeleteModel'); } /** * Grants permission to view details about an AWS Panorama application * * Access Level: Read * * https://docs.aws.amazon.com/panorama/latest/dev/API_DescribeApp.html */ public toDescribeApp() { return this.to('DescribeApp'); } /** * Grants permission to view details about a deployment for an AWS Panorama application * * Access Level: Read * * https://docs.aws.amazon.com/panorama/latest/dev/API_DescribeAppDeployment.html */ public toDescribeAppDeployment() { return this.to('DescribeAppDeployment'); } /** * Grants permission to view details about a version of an AWS Panorama application * * Access Level: Read * * https://docs.aws.amazon.com/panorama/latest/dev/API_DescribeAppVersion.html */ public toDescribeAppVersion() { return this.to('DescribeAppVersion'); } /** * Grants permission to view details about a datasource in AWS Panorama * * Access Level: Read * * https://docs.aws.amazon.com/panorama/latest/dev/API_DescribeDataSource.html */ public toDescribeDataSource() { return this.to('DescribeDataSource'); } /** * Grants permission to view details about an AWS Panorama Appliance * * Access Level: Read * * https://docs.aws.amazon.com/panorama/latest/dev/API_DescribeDevice.html */ public toDescribeDevice() { return this.to('DescribeDevice'); } /** * Grants permission to view details about a software update for an AWS Panorama Appliance * * Access Level: Read * * https://docs.aws.amazon.com/panorama/latest/dev/API_DescribeDeviceUpdate.html */ public toDescribeDeviceUpdate() { return this.to('DescribeDeviceUpdate'); } /** * Grants permission to view details about a machine learning model in AWS Panorama * * Access Level: Read * * https://docs.aws.amazon.com/panorama/latest/dev/API_DescribeModel.html */ public toDescribeModel() { return this.to('DescribeModel'); } /** * Grants permission to view details about a software version for the AWS Panorama Appliance * * Access Level: Read * * https://docs.aws.amazon.com/panorama/latest/dev/API_DescribeSoftware.html */ public toDescribeSoftware() { return this.to('DescribeSoftware'); } /** * Grants permission to view details about a deployment configuration for an AWS Panorama application * * Access Level: Read * * https://docs.aws.amazon.com/panorama/latest/dev/API_GetDeploymentConfiguration.html */ public toGetDeploymentConfiguration() { return this.to('GetDeploymentConfiguration'); } /** * Grants permission to retrieve a list of cameras generated with CreateInputs * * Access Level: Read * * https://docs.aws.amazon.com/panorama/latest/dev/API_GetInputList.html */ public toGetInputs() { return this.to('GetInputs'); } /** * Grants permission to retrieve a list of streams generated with CreateStreams * * Access Level: Read * * https://docs.aws.amazon.com/panorama/latest/dev/API_GetStreamsList.html */ public toGetStreams() { return this.to('GetStreams'); } /** * Grants permission to generate a WebSocket endpoint for communication with AWS Panorama * * Access Level: Read * * https://docs.aws.amazon.com/panorama/latest/dev/API_GetWebSocketURL.html */ public toGetWebSocketURL() { return this.to('GetWebSocketURL'); } /** * Grants permission to retrieve a list of deployments for an AWS Panorama application * * Access Level: List * * https://docs.aws.amazon.com/panorama/latest/dev/API_ListAppDeploymentOperations.html */ public toListAppDeploymentOperations() { return this.to('ListAppDeploymentOperations'); } /** * Grants permission to retrieve a list of application versions in AWS Panorama * * Access Level: List * * https://docs.aws.amazon.com/panorama/latest/dev/API_ListAppVersions.html */ public toListAppVersions() { return this.to('ListAppVersions'); } /** * Grants permission to retrieve a list of applications in AWS Panorama * * Access Level: List * * https://docs.aws.amazon.com/panorama/latest/dev/API_ListApps.html */ public toListApps() { return this.to('ListApps'); } /** * Grants permission to retrieve a list of datasources in AWS Panorama * * Access Level: List * * https://docs.aws.amazon.com/panorama/latest/dev/API_ListDataSources.html */ public toListDataSources() { return this.to('ListDataSources'); } /** * Grants permission to retrieve a list of deployment configurations in AWS Panorama * * Access Level: List * * https://docs.aws.amazon.com/panorama/latest/dev/API_ListDeploymentConfigurations.html */ public toListDeploymentConfigurations() { return this.to('ListDeploymentConfigurations'); } /** * Grants permission to retrieve a list of software updates for an AWS Panorama Appliance * * Access Level: List * * https://docs.aws.amazon.com/panorama/latest/dev/API_ListDeviceUpdates.html */ public toListDeviceUpdates() { return this.to('ListDeviceUpdates'); } /** * Grants permission to retrieve a list of appliances in AWS Panorama * * Access Level: List * * https://docs.aws.amazon.com/panorama/latest/dev/API_ListDevices.html */ public toListDevices() { return this.to('ListDevices'); } /** * Grants permission to retrieve a list of models in AWS Panorama * * Access Level: List * * https://docs.aws.amazon.com/panorama/latest/dev/API_ListModels.html */ public toListModels() { return this.to('ListModels'); } /** * Grants permission to retrieve a list of tags for a resource in AWS Panorama * * Access Level: List * * https://docs.aws.amazon.com/panorama/latest/dev/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to add tags to a resource in AWS Panorama * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/panorama/latest/dev/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to remove tags from a resource in AWS Panorama * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/panorama/latest/dev/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to modify an AWS Panorama application * * Access Level: Write * * https://docs.aws.amazon.com/panorama/latest/dev/API_UpdateApp.html */ public toUpdateApp() { return this.to('UpdateApp'); } /** * Grants permission to modify the version-specific configuration of an AWS Panorama application * * Access Level: Write * * https://docs.aws.amazon.com/panorama/latest/dev/API_UpdateAppConfiguration.html */ public toUpdateAppConfiguration() { return this.to('UpdateAppConfiguration'); } /** * Grants permission to modify an AWS Panorama datasource * * Access Level: Write * * https://docs.aws.amazon.com/panorama/latest/dev/API_UpdateDataSource.html */ public toUpdateDataSource() { return this.to('UpdateDataSource'); } /** * Grants permission to modify basic settings for an AWS Panorama Appliance * * Access Level: Write * * https://docs.aws.amazon.com/panorama/latest/dev/API_UpdateDevice.html */ public toUpdateDevice() { return this.to('UpdateDevice'); } protected accessLevelList: AccessLevelList = { "Write": [ "CreateApp", "CreateAppDeployment", "CreateAppVersion", "CreateDataSource", "CreateDeploymentConfiguration", "CreateDevice", "CreateDeviceUpdate", "CreateInputs", "CreateModel", "CreateStreams", "DeleteApp", "DeleteAppVersion", "DeleteDataSource", "DeleteDevice", "DeleteModel", "UpdateApp", "UpdateAppConfiguration", "UpdateDataSource", "UpdateDevice" ], "Read": [ "DescribeApp", "DescribeAppDeployment", "DescribeAppVersion", "DescribeDataSource", "DescribeDevice", "DescribeDeviceUpdate", "DescribeModel", "DescribeSoftware", "GetDeploymentConfiguration", "GetInputs", "GetStreams", "GetWebSocketURL" ], "List": [ "ListAppDeploymentOperations", "ListAppVersions", "ListApps", "ListDataSources", "ListDeploymentConfigurations", "ListDeviceUpdates", "ListDevices", "ListModels", "ListTagsForResource" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type device to the statement * * https://docs.aws.amazon.com/panorama/latest/dev/ * * @param deviceName - Identifier for the deviceName. * @param accountId - 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 onDevice(deviceName: string, accountId?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:panorama:${Region}:${AccountId}:device/${DeviceName}'; arn = arn.replace('${DeviceName}', deviceName); arn = arn.replace('${AccountId}', accountId || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type dataSource to the statement * * https://docs.aws.amazon.com/panorama/latest/dev/ * * @param deviceName - Identifier for the deviceName. * @param dataSourceName - Identifier for the dataSourceName. * @param accountId - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onDataSource(deviceName: string, dataSourceName: string, accountId?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:panorama:${Region}:${AccountId}:dataSource/${DeviceName}/${DataSourceName}'; arn = arn.replace('${DeviceName}', deviceName); arn = arn.replace('${DataSourceName}', dataSourceName); arn = arn.replace('${AccountId}', accountId || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type model to the statement * * https://docs.aws.amazon.com/panorama/latest/dev/ * * @param modelName - Identifier for the modelName. * @param accountId - 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 onModel(modelName: string, accountId?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:panorama:${Region}:${AccountId}:model/${ModelName}'; arn = arn.replace('${ModelName}', modelName); arn = arn.replace('${AccountId}', accountId || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type app to the statement * * https://docs.aws.amazon.com/panorama/latest/dev/ * * @param appName - Identifier for the appName. * @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 onApp(appName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:panorama:${Region}:${Account}:app/${AppName}'; arn = arn.replace('${AppName}', appName); 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 appVersion to the statement * * https://docs.aws.amazon.com/panorama/latest/dev/ * * @param appName - Identifier for the appName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onAppVersion(appName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:panorama:${Region}:${Account}:app/${AppName}:{AppVersion}'; arn = arn.replace('${AppName}', appName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
export const bodyParts = { // The most notable physical trait of $currentNPC.firstName is that $currentNPC.heshe has ______ head: { hair: [ 'thick, long hair down to their hips', 'a mostly shaved head', 'a short crewcut', 'a pretty short mohawk', 'neatly trimmed hair', 'wild, unkempt hair', 'long curly hair', 'short curly hair', 'thick straight hair', 'thin stringy hair', 'small tufts of hair, but not much', 'short braided hair', 'hair in thick long braids', 'thick braids of hair banded with gold', 'short, messy hair', 'a very short, no-nonsense haircut', 'a short, very tailored haircut', 'bangs that obscure the eyes', 'hair flaked with snowy dandruff', 'a hair braid like a thick rope', 'hair pulled up in a tight bun', 'hair coiled in a top-knot', 'greasy looking hair', 'rather oily looking hair', 'thin whispy hair down to the shoulders', 'hair elaborately dressed with ribbons', 'hair greased into a ducktail', 'locks that flutter to the floor', 'incredibly frizzy hair', 'hair like straw', 'hair that droops down to the cheeks', 'matted looking hair', 'pigtails', 'a very noble haircut', 'long messy hair', 'hair in a low bun', 'has slicked back hair', 'braided hair', 'a ring of hair', 'barely any hair', 'long bangs', 'a bowl cut', 'very bushy hair', "a rat's nest for hair", 'a shaved head', 'long sideburns', 'thin, neatly trimmed sideburns', 'thick, tangled hair', 'neatly combed hair' ], // covers eyes, eyelids, and eyebrows eyes: [ 'eyes like a hawk', 'quick-witted eyes', 'incredibly sharp eyes', 'rather dull eyes', 'cold eyes', 'lifeless looking eyes', 'incredibly wide eyes', 'slits for eyes', 'very droopy eyelids', 'rather square shaped eyes', 'brilliant eyes', 'shifty eyes', 'deep crows feet around both eyes', 'almond shaped eyes', 'beady rat eyes', 'a beseeching gaze', 'a blazing gaze', 'bug-eyes', 'bulging eyes', 'feline-like eyes', 'eyes like a shark', 'eyes like liquid pools of color', 'sneaky, close-set eyes', 'very sunken eyes', 'constantly watery eyes', 'narrow, wide-set eyes', 'moon shaped eyes', 'steeply arched brows', 'tired looking eyes', 'a thick unibrow', 'a thin unibrow', 'thick, straight eyebrows', 'very hairy eyebrows', 'thin, curved brows', 'outrageously long eyelashes', 'very long eyelashes', 'eyebrows like checkmarks', 'well manicured eyebrows', 'eyebrows like caterpillars', 'small beady eyes', 'strangely bloodshot eyes', 'deep-set eyes', 'quite owlish eyes', 'oval shaped eyes', 'slanted eyes', 'drawn on eyebrows', 'quite sparse eyebrows', 'thin, wispy eyebrows', 'doe-eyes', 'an emotionless gaze', 'hollow eyes', 'squinty eyes', 'twinkling eyes', 'wide spaced, sunken eyes', 'a black eye', 'two black eyes', 'enormous eyes', 'incredibly tiny eyes' ], nose: [ 'a long slender nose', 'a rather snout looking nose', 'a piggish nose', 'a round, bulbous nose', 'a short slender nose', 'a bird-like nose', 'a beaked nose', 'a rather bent looking nose', "a boxer's nose", 'a broken nose', 'a very large nose', 'a very small nose', 'a quite long nose', 'a rather askew nose', 'a bovine looking nose', 'a broad, flat nose', 'a childlike nose', 'a chiseled nose', 'a cleft nose', 'a crooked nose', 'a short, curved nose', 'a long, curved nose', 'a curved nose', 'a delicate looking nose', 'a dimpled nose', 'an elegantly curved nose', 'an elegant, round nose', 'an enormous nose', 'a cat-like nose', 'a flaccid looking nose', 'a freckled nose', 'a fat nose', 'a hooked nose', 'a thin, hooked nose', 'a wide, hooked nose', 'an impish nose', 'a knobby nose', 'a long, lopsided nose', 'a narrow, lopsided nose', 'a rather lumpy', 'a long, lumpy nose', 'a round, lumpy nose', 'a flat, meaty nose', 'an oddly misshapen nose', 'a short pinched nose', 'a squashed nose', 'a wide, wrinkled nose', 'a rather noble nose', 'a thin, sloped nose', 'a broad, sloped nose', 'a warty nose', 'nose covered in blackheads', 'a rather greasy looking nose', 'a pockmarked nose' ], // covers mouth and cheeks mouth: [ 'long thin lips', 'thick, full lips', 'a permanent smile', 'a permanent frown', 'a permanent scowl', 'very pouty lips', 'a permanent look of awe', 'tight, pursed lips', 'rather dainty lips', 'long, thick lips', 'narrow, thin lips', 'yellowed teeth', 'incredibly crooked teeth', 'almost rotten looking teeth', 'almost no teeth', 'a perfect smile', 'incredibly white teeth', 'perfectly straight teeth', 'teeth like headstones', 'plump, luscious lips', 'very wide lips', 'troutlike lips', 'dry, cracked lips', 'leathery looking lips', 'a sagging lower lip', 'very full lips', 'a fat lip', 'a kind smile', 'hallowed cheeks', 'harsh cheekbones', 'sharp cheekbones', 'rosy red cheeks', 'very high cheekbones', 'sunken cheekbones', 'soft round cheeks', 'plump cheeks', 'chubby cheeks', 'dimpled cheeks', 'large puffy cheeks', 'thin ruddy cheeks', 'pale, sunken cheeks', 'freckled cheeks', 'large buck teeth', 'teeth like a beaver', 'teeth like a horse', 'a large gap between the two front teeth', 'an underbite', 'an overbite' ], // covers chin, jaw, and neck chin: [ 'a strong, jutting chin', 'an angular chin', 'a strong cleft chin', 'a slight cleft chin', 'a double chin', 'a large double chin', 'a wide beefy chin', 'a thin dainty chin', 'a rather bony chin', 'a wide chin', 'a narrow, sunken chin', 'a very feminine chin', 'a flat chin', 'a recessed chin', 'an almost non-existant chin', 'a misshapen chin', 'a noble looking chin', 'a flat, pockmarked chin', 'a very prominent chin', 'a sharp chin', 'a quite slender chin', 'a well-molded chin', 'a square chin', 'a soft, rounded chin', 'a chiseled jawline', 'a well sculpted jaw', 'a chin like a shovel', 'a delicately rounded jaw', 'a caved in chin', 'a heavy round jaw', 'a jaw narrowed into a pointed little chin', 'jowls', 'a narrow jawline that arrows into a pointed chin', 'a pick-like chin', 'a receding chin that makes their nose seem bigger', 'a saggy jaw that droops into a turkey neck', 'a spade of a chin', 'a strong square jaw', 'a weak chin', 'a prominent jawline', 'a smooth, youthful jawline', 'a long elegant neck', 'a long stocky neck', 'a very wide neck', 'a quite short, thin neck', 'a thin stocky neck', 'a narrow neck', 'a neck that looks to small for their head', 'an incredibly thick neck' ], ears: [ 'jug-like ears', 'elephant-like ears', 'cauliflower ears', 'large, protruding ears', 'small, protruding ears', 'long, thick earlobes', 'thin, fat earlobes', 'very tiny ears', 'small tender ears', 'big, floppy ears', 'no earlobes', 'ears that curl like an exotic shell', 'rather pointed ears', 'very rounded ears', 'very delicate ears', 'rather hairy ears' ], misc: [ 'a densely pockmarked face', 'an incredibly freckly face', 'a face covered in freckles', 'a well freckled face', 'a rather angular face', 'a soft rounded face', 'a friendly looking face', 'a sunken face', 'a hollow looking face', 'a sharply angled face', 'a long, horselike face', 'a horseface', 'an exceptionally pale face', 'a very blocky face', 'a baby-face', 'a rather blotchy looking face', 'a well countoured face', 'a flabby face', 'a youthful looking face' ] }, torso: { descriptions: [ 'a hunched back', 'an incredibly large hunch', 'very broad shoulders', 'incredibly broad shoulders', 'quite broad shoulders', 'narrow shoulders', 'quite rounded shoulders', 'terrible posture', 'perfect posture', 'a large barrel chest', 'a barrel chest', 'very bony shoulders', 'wide set shoulders', 'a sunken chest', 'a wide ribcage', 'a narrow ribcage', 'a very narrow waist', 'a rather wide waist', 'a distended stomach', 'rather drooped shoulders', 'strong, square shoulders', 'broad, powerful shoulders', 'very pronounced collar bones', 'wide, bony hips', 'very narrows hips', 'very wide set hips', 'a misshapen ribcage' ] }, arms: { descriptions: [ 'long, gangly arms', 'quite short arms', 'arms like a gorilla', 'long, spindly fingers', 'short, stubby arms', 'short, stubby fingers', 'child-sized hands', 'very hairy forearms', 'incredibly veiny arms', 'swollen, red knuckles', 'quite bony elbows', 'fingers like sausages', 'heavily calloused hands', 'fingernails cut to the quick', 'long, brittle fingernails', 'colorfully painted nails', 'talon-like nails', 'nails sharpened to a point', 'neatly trimmed fingernails', 'small webs between each finger', 'long, elegant fingers', 'rough, cracked hands', 'large swollen knuckles', 'impossibly enormous hands', 'very muscular hands', 'quite muscular arms', 'grimy looking fingernails', 'yellow-ish fingernails' ] }, legs: { descriptions: [ 'more legs than torso', 'widely bowed legs', 'very notcieable knock knees', 'large, knobly knees', 'quite stumpy legs', 'large, wide feet', 'very tiny feet', 'feet like a toddler', 'feet like a chimp', 'almost no kneecaps', 'long, monkey like toes', 'pale, veiny legs' ] } }
the_stack
import { dew as _PendingOperationDewDew } from "./PendingOperation.dew.js"; import { dew as _ResourceDewDew } from "./Resource.dew.js"; import { dew as _utilsDewDew } from "./utils.dew.js"; import _events from "../../@jspm/core@1.1.0/nodelibs/events.js";; import _timers from "../../@jspm/core@1.1.0/nodelibs/timers.js";; var exports = {}, _dewExec = false; export function dew() { if (_dewExec) return exports; _dewExec = true; Object.defineProperty(exports, "__esModule", { value: true }); const PendingOperation_1 = _PendingOperationDewDew(); const Resource_1 = _ResourceDewDew(); const utils_1 = _utilsDewDew(); const events_1 = _events; const timers_1 = _timers; class Pool { constructor(opt) { this.destroyed = false; this.emitter = new events_1.EventEmitter(); opt = opt || {}; if (!opt.create) { throw new Error('Tarn: opt.create function most be provided'); } if (!opt.destroy) { throw new Error('Tarn: opt.destroy function most be provided'); } if (typeof opt.min !== 'number' || opt.min < 0 || opt.min !== Math.round(opt.min)) { throw new Error('Tarn: opt.min must be an integer >= 0'); } if (typeof opt.max !== 'number' || opt.max <= 0 || opt.max !== Math.round(opt.max)) { throw new Error('Tarn: opt.max must be an integer > 0'); } if (opt.min > opt.max) { throw new Error('Tarn: opt.max is smaller than opt.min'); } if (!utils_1.checkOptionalTime(opt.acquireTimeoutMillis)) { throw new Error('Tarn: invalid opt.acquireTimeoutMillis ' + JSON.stringify(opt.acquireTimeoutMillis)); } if (!utils_1.checkOptionalTime(opt.createTimeoutMillis)) { throw new Error('Tarn: invalid opt.createTimeoutMillis ' + JSON.stringify(opt.createTimeoutMillis)); } if (!utils_1.checkOptionalTime(opt.destroyTimeoutMillis)) { throw new Error('Tarn: invalid opt.destroyTimeoutMillis ' + JSON.stringify(opt.destroyTimeoutMillis)); } if (!utils_1.checkOptionalTime(opt.idleTimeoutMillis)) { throw new Error('Tarn: invalid opt.idleTimeoutMillis ' + JSON.stringify(opt.idleTimeoutMillis)); } if (!utils_1.checkOptionalTime(opt.reapIntervalMillis)) { throw new Error('Tarn: invalid opt.reapIntervalMillis ' + JSON.stringify(opt.reapIntervalMillis)); } if (!utils_1.checkOptionalTime(opt.createRetryIntervalMillis)) { throw new Error('Tarn: invalid opt.createRetryIntervalMillis ' + JSON.stringify(opt.createRetryIntervalMillis)); } const allowedKeys = { create: true, validate: true, destroy: true, log: true, min: true, max: true, acquireTimeoutMillis: true, createTimeoutMillis: true, destroyTimeoutMillis: true, idleTimeoutMillis: true, reapIntervalMillis: true, createRetryIntervalMillis: true, propagateCreateError: true }; for (const key of Object.keys(opt)) { if (!allowedKeys[key]) { throw new Error(`Tarn: unsupported option opt.${key}`); } } this.creator = opt.create; this.destroyer = opt.destroy; this.validate = typeof opt.validate === 'function' ? opt.validate : () => true; this.log = opt.log || (() => {}); this.acquireTimeoutMillis = opt.acquireTimeoutMillis || 30000; this.createTimeoutMillis = opt.createTimeoutMillis || 30000; this.destroyTimeoutMillis = opt.destroyTimeoutMillis || 5000; this.idleTimeoutMillis = opt.idleTimeoutMillis || 30000; this.reapIntervalMillis = opt.reapIntervalMillis || 1000; this.createRetryIntervalMillis = opt.createRetryIntervalMillis || 200; this.propagateCreateError = !!opt.propagateCreateError; this.min = opt.min; this.max = opt.max; // All the resources, which are either already acquired or which are // considered for being passed to acquire in async validation phase. this.used = []; // All the resources, which are either just created and free or returned // back to pool after using. this.free = []; this.pendingCreates = []; this.pendingAcquires = []; this.pendingDestroys = []; // When acquire is pending, but also still in validation phase this.pendingValidations = []; this.destroyed = false; this.interval = null; this.eventId = 1; } numUsed() { return this.used.length; } numFree() { return this.free.length; } numPendingAcquires() { return this.pendingAcquires.length; } numPendingValidations() { return this.pendingValidations.length; } numPendingCreates() { return this.pendingCreates.length; } acquire() { const eventId = this.eventId++; this._executeEventHandlers('acquireRequest', eventId); const pendingAcquire = new PendingOperation_1.PendingOperation(this.acquireTimeoutMillis); this.pendingAcquires.push(pendingAcquire); // If the acquire fails for whatever reason // remove it from the pending queue. pendingAcquire.promise = pendingAcquire.promise.then(resource => { this._executeEventHandlers('acquireSuccess', eventId, resource); return resource; }).catch(err => { this._executeEventHandlers('acquireFail', eventId, err); remove(this.pendingAcquires, pendingAcquire); return Promise.reject(err); }); this._tryAcquireOrCreate(); return pendingAcquire; } release(resource) { this._executeEventHandlers('release', resource); for (let i = 0, l = this.used.length; i < l; ++i) { const used = this.used[i]; if (used.resource === resource) { this.used.splice(i, 1); this.free.push(used.resolve()); this._tryAcquireOrCreate(); return true; } } return false; } isEmpty() { return [this.numFree(), this.numUsed(), this.numPendingAcquires(), this.numPendingValidations(), this.numPendingCreates()].reduce((total, value) => total + value) === 0; } /** * Reaping cycle. */ check() { const timestamp = utils_1.now(); const newFree = []; const minKeep = this.min - this.used.length; const maxDestroy = this.free.length - minKeep; let numDestroyed = 0; this.free.forEach(free => { if (utils_1.duration(timestamp, free.timestamp) >= this.idleTimeoutMillis && numDestroyed < maxDestroy) { numDestroyed++; this._destroy(free.resource); } else { newFree.push(free); } }); this.free = newFree; // Pool is completely empty, stop reaping. // Next .acquire will start reaping interval again. if (this.isEmpty()) { this._stopReaping(); } } destroy() { const eventId = this.eventId++; this._executeEventHandlers('poolDestroyRequest', eventId); this._stopReaping(); this.destroyed = true; // First wait for all the pending creates get ready. return utils_1.reflect(Promise.all(this.pendingCreates.map(create => utils_1.reflect(create.promise))).then(() => { // poll every 100ms and wait that all validations are ready return new Promise((resolve, reject) => { const interval = setInterval(() => { if (this.numPendingValidations() === 0) { timers_1.clearInterval(interval); resolve(); } }, 100); }); }).then(() => { // Wait for all the used resources to be freed. return Promise.all(this.used.map(used => utils_1.reflect(used.promise))); }).then(() => { // Abort all pending acquires. return Promise.all(this.pendingAcquires.map(acquire => { acquire.abort(); return utils_1.reflect(acquire.promise); })); }).then(() => { // Now we can destroy all the freed resources. return Promise.all(this.free.map(free => utils_1.reflect(this._destroy(free.resource)))); }).then(() => { // Also wait rest of the pending destroys to finish return Promise.all(this.pendingDestroys.map(pd => pd.promise)); }).then(() => { this.free = []; this.pendingAcquires = []; })).then(res => { this._executeEventHandlers('poolDestroySuccess', eventId); this.emitter.removeAllListeners(); return res; }); } on(event, listener) { this.emitter.on(event, listener); } removeListener(event, listener) { this.emitter.removeListener(event, listener); } removeAllListeners(event) { this.emitter.removeAllListeners(event); } /** * The most important method that is called always when resources * are created / destroyed / acquired / released. In other words * every time when resources are moved from used to free or vice * versa. * * Either assigns free resources to pendingAcquires or creates new * resources if there is room for it in the pool. */ _tryAcquireOrCreate() { if (this.destroyed) { return; } if (this._hasFreeResources()) { this._doAcquire(); } else if (this._shouldCreateMoreResources()) { this._doCreate(); } } _hasFreeResources() { return this.free.length > 0; } _doAcquire() { // Acquire as many pending acquires as possible concurrently while (this._canAcquire()) { // To allow async validation, we actually need to move free resource // and pending acquire temporary from their respective arrays and depending // on validation result to either leave the free resource to used resources array // or destroy the free resource if validation did fail. const pendingAcquire = this.pendingAcquires.shift(); const free = this.free.pop(); if (free === undefined || pendingAcquire === undefined) { const errMessage = 'this.free was empty while trying to acquire resource'; this.log(`Tarn: ${errMessage}`, 'warn'); throw new Error(`Internal error, should never happen. ${errMessage}`); } // Make sure that pendingAcquire that is being validated is not lost and // can be freed when pool is destroyed. this.pendingValidations.push(pendingAcquire); // Must be added here pre-emptively to prevent logic that decides // if new resources are created will keep on working correctly. this.used.push(free); // if acquire fails also pending validation, must be aborted so that pre reserved // resource will be returned to free resources immediately const abortAbleValidation = new PendingOperation_1.PendingOperation(this.acquireTimeoutMillis); pendingAcquire.promise.catch(err => { abortAbleValidation.abort(); }); abortAbleValidation.promise.catch(err => { // There's nothing we can do here but log the error. This would otherwise // leak out as an unhandled exception. this.log('Tarn: resource validator threw an exception ' + err.stack, 'warn'); return false; }).then(validationSuccess => { try { if (validationSuccess) { // At least one active resource exist, start reaping. this._startReaping(); pendingAcquire.resolve(free.resource); } else { remove(this.used, free); this._destroy(free.resource); // is acquire was canceled, failed or timed out already // no need to return it to pending queries if (!pendingAcquire.isRejected) { this.pendingAcquires.unshift(pendingAcquire); } // Since we destroyed an invalid resource and were not able to fulfill // all the pending acquires, we may need to create new ones or at // least run this acquire loop again to verify it. But not immediately // to prevent starving event loop. setTimeout(() => { this._tryAcquireOrCreate(); }, 0); } } finally { remove(this.pendingValidations, pendingAcquire); } }); // try to validate this._validateResource(free.resource).then(validationSuccess => { abortAbleValidation.resolve(validationSuccess); }).catch(err => { abortAbleValidation.reject(err); }); } } _canAcquire() { return this.free.length > 0 && this.pendingAcquires.length > 0; } _validateResource(resource) { try { return Promise.resolve(this.validate(resource)); } catch (err) { // prevent leaking of sync exception return Promise.reject(err); } } _shouldCreateMoreResources() { return this.used.length + this.pendingCreates.length < this.max && this.pendingCreates.length < this.pendingAcquires.length; } _doCreate() { const pendingAcquiresBeforeCreate = this.pendingAcquires.slice(); const pendingCreate = this._create(); pendingCreate.promise.then(() => { // Not returned on purpose. this._tryAcquireOrCreate(); return null; }).catch(err => { if (this.propagateCreateError && this.pendingAcquires.length !== 0) { // If propagateCreateError is true, we don't retry the create // but reject the first pending acquire immediately. Intentionally // use `this.pendingAcquires` instead of `pendingAcquiresBeforeCreate` // in case some acquires in pendingAcquiresBeforeCreate have already // been resolved. this.pendingAcquires[0].reject(err); } // Save the create error to all pending acquires so that we can use it // as the error to reject the acquire if it times out. pendingAcquiresBeforeCreate.forEach(pendingAcquire => { pendingAcquire.possibleTimeoutCause = err; }); // Not returned on purpose. utils_1.delay(this.createRetryIntervalMillis).then(() => this._tryAcquireOrCreate()); }); } _create() { const eventId = this.eventId++; this._executeEventHandlers('createRequest', eventId); const pendingCreate = new PendingOperation_1.PendingOperation(this.createTimeoutMillis); // If an error occurs (likely a create timeout) remove this creation from // the list of pending creations so we try to create a new one. pendingCreate.promise = pendingCreate.promise.catch(err => { remove(this.pendingCreates, pendingCreate); throw err; }); this.pendingCreates.push(pendingCreate); callbackOrPromise(this.creator).then(resource => { if (pendingCreate.isRejected) { this.destroyer(resource); return null; } remove(this.pendingCreates, pendingCreate); this.free.push(new Resource_1.Resource(resource)); // Not returned on purpose. pendingCreate.resolve(resource); this._executeEventHandlers('createSuccess', eventId, resource); return null; }).catch(err => { if (pendingCreate.isRejected) { return null; } remove(this.pendingCreates, pendingCreate); // Not returned on purpose. pendingCreate.reject(err); this._executeEventHandlers('createFail', eventId, err); return null; }); return pendingCreate; } _destroy(resource) { const eventId = this.eventId++; this._executeEventHandlers('destroyRequest', eventId, resource); // this.destroyer can be both synchronous and asynchronous. // so we wrap it to promise to get all exceptions through same pipeline const pendingDestroy = new PendingOperation_1.PendingOperation(this.destroyTimeoutMillis); const retVal = Promise.resolve().then(() => this.destroyer(resource)); retVal.then(() => { pendingDestroy.resolve(resource); }).catch(err => { pendingDestroy.reject(err); }); this.pendingDestroys.push(pendingDestroy); // In case of an error there's nothing we can do here but log it. return pendingDestroy.promise.then(res => { this._executeEventHandlers('destroySuccess', eventId, resource); return res; }).catch(err => this._logDestroyerError(eventId, resource, err)).then(res => { const index = this.pendingDestroys.findIndex(pd => pd === pendingDestroy); this.pendingDestroys.splice(index, 1); return res; }); } _logDestroyerError(eventId, resource, err) { this._executeEventHandlers('destroyFail', eventId, resource, err); this.log('Tarn: resource destroyer threw an exception ' + err.stack, 'warn'); } _startReaping() { if (!this.interval) { this._executeEventHandlers('startReaping'); this.interval = setInterval(() => this.check(), this.reapIntervalMillis); } } _stopReaping() { if (this.interval !== null) { this._executeEventHandlers('stopReaping'); timers_1.clearInterval(this.interval); } this.interval = null; } _executeEventHandlers(eventName, ...args) { const listeners = this.emitter.listeners(eventName); // just calling .emit() would stop running rest of the listeners if one them fails listeners.forEach(listener => { try { listener(...args); } catch (err) { // There's nothing we can do here but log the error. This would otherwise // leak out as an unhandled exception. this.log(`Tarn: event handler "${eventName}" threw an exception ${err.stack}`, 'warn'); } }); } } exports.Pool = Pool; function remove(arr, item) { const idx = arr.indexOf(item); if (idx === -1) { return false; } else { arr.splice(idx, 1); return true; } } function callbackOrPromise(func) { return new Promise((resolve, reject) => { const callback = (err, resource) => { if (err) { reject(err); } else { resolve(resource); } }; utils_1.tryPromise(() => func(callback)).then(res => { // If the result is falsy, we assume that the callback will // be called instead of interpreting the falsy value as a // result value. if (res) { resolve(res); } }).catch(err => { reject(err); }); }); } return exports; }
the_stack
import {Dictionary} from "../AltDictionary"; import {Guid} from "../Guid"; import {DateTime, DateTimeStyles} from "../DateTime"; import {StringHelper, ArrayHelper, Convert} from "../ExtensionMethods"; import {EwsUtilities} from "../Core/EwsUtilities"; import {LazyMember} from "../Core/LazyMember"; import {ArgumentException} from "../Exceptions/ArgumentException"; import {MapiPropertyType} from "../Enumerations/MapiPropertyType"; import {MapiTypeConverterTypeSystem} from "../Enumerations/MapiTypeConverterTypeSystem"; import {MapiTypeConverterMapEntry} from "./MapiTypeConverterMapEntry"; export type MapiTypeConverterMap = Dictionary<MapiPropertyType, MapiTypeConverterMapEntry>; export class MapiTypeConverter { private static UtcDataTimeStyles: DateTimeStyles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal; static get MapiTypeConverterMap(): MapiTypeConverterMap { return MapiTypeConverter.mapiTypeConverterMap.Member; } private static mapiTypeConverterMap: LazyMember<MapiTypeConverterMap> = new LazyMember<MapiTypeConverterMap>(() => { var map: MapiTypeConverterMap = new Dictionary<MapiPropertyType, MapiTypeConverterMapEntry>((k) => k.toString()); map.Add( MapiPropertyType.ApplicationTime, new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.number, //double (s) => Convert.toNumber(s), //Parse (o) => o.toString() //ConvertToString )); map.Add( MapiPropertyType.ApplicationTimeArray, new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.number, //double (s) => Convert.toNumber(s), //Parse (o) => o.toString(), //ConvertToString true //IsArray )); var byteConverter = new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.byteArray, //byte[] (s) => StringHelper.IsNullOrEmpty(s) ? null : Convert.FromBase64String(s), //Parse (o) => Convert.ToBase64String(<number[]>o) //ConvertToString ); map.Add( MapiPropertyType.Binary, byteConverter); var byteArrayConverter = new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.byteArray, //byte[] (s) => StringHelper.IsNullOrEmpty(s) ? null : Convert.FromBase64String(s), //Parse (o) => Convert.ToBase64String(<number[]>o), //ConvertToString true //IsArray ); map.Add( MapiPropertyType.BinaryArray, byteArrayConverter); var boolConverter = new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.boolean, (s) => Convert.toBool(s), //Parse (o) => (<boolean>o).toString().toLowerCase() //ConvertToString ); map.Add( MapiPropertyType.Boolean, boolConverter); var clsidConverter = new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.guid, (s) => new Guid(s), //Parse (o) => (<Guid>o).ToString() //ConvertToString ); map.Add( MapiPropertyType.CLSID, clsidConverter); var clsidArrayConverter = new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.guid, (s) => new Guid(s), //Parse (o) => (<Guid>o).ToString(), //ConvertToString true //IsArray ); map.Add( MapiPropertyType.CLSIDArray, clsidArrayConverter); map.Add( MapiPropertyType.Currency, new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.number, //Int64 (s) => Convert.toNumber(s), //Parse (o) => o.toString() //ConvertToString )); map.Add( MapiPropertyType.CurrencyArray, new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.number, //Int64 (s) => Convert.toNumber(s), //Parse (o) => o.toString(), //ConvertToString true //IsArray )); map.Add( MapiPropertyType.Double, new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.number, //double (s) => Convert.toNumber(s), //Parse (o) => o.toString() //ConvertToString )); map.Add( MapiPropertyType.DoubleArray, new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.number, //double (s) => Convert.toNumber(s), //Parse (o) => o.toString(), //ConvertToString true //IsArray )); map.Add( MapiPropertyType.Error, new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.number, //Int32 (s) => Convert.toNumber(s), //Parse (o) => o.toString() //ConvertToString )); map.Add( MapiPropertyType.Float, new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.number, //float (s) => Convert.toNumber(s), //Parse (o) => o.toString() //ConvertToString )); map.Add( MapiPropertyType.FloatArray, new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.number, //float (s) => Convert.toNumber(s), //Parse (o) => o.toString(), //ConvertToString true //IsArray )); map.Add( MapiPropertyType.Integer, new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.number, //Int32 (s) => MapiTypeConverter.ParseMapiIntegerValue(s), //Parse (o) => o.toString() //ConvertToString )); map.Add( MapiPropertyType.IntegerArray, new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.number, //Int32 (s) => Convert.toNumber(s), //Parse //ref: check if latest ews managed api code changes this to same as Integer property type above (o) => o.toString(), //ConvertToString true //IsArray )); map.Add( MapiPropertyType.Long, new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.number, //Int64 (s) => Convert.toNumber(s), //Parse (o) => o.toString() //ConvertToString )); map.Add( MapiPropertyType.LongArray, new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.number, //Int64 (s) => Convert.toNumber(s), //Parse (o) => o.toString(), //ConvertToString true //IsArray )); var objectConverter = new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.string, (s) => s, //Parse (o) => o.toString() //ConvertToString ); map.Add( MapiPropertyType.Object, objectConverter); var objectArrayConverter = new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.string, (s) => s, //Parse (o) => o.toString(), //ConvertToString true //IsArray ); map.Add( MapiPropertyType.ObjectArray, objectArrayConverter); map.Add( MapiPropertyType.Short, new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.number, //short (s) => Convert.toNumber(s), //Parse (o) => o.toString() //ConvertToString )); map.Add( MapiPropertyType.ShortArray, new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.number, //short (s) => Convert.toNumber(s), //Parse (o) => o.toString(), //ConvertToString true //IsArray )); var stringConverter = new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.string, (s) => s, //Parse (o) => o.toString() //ConvertToString ); map.Add( MapiPropertyType.String, stringConverter); var stringArrayConverter = new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.string, (s) => s, //Parse (o) => o.toString(), //ConvertToString true //IsArray ); map.Add( MapiPropertyType.StringArray, stringArrayConverter); var sysTimeConverter = new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.DateTime, (s) => DateTime.Parse(s), //Parse //ref: UtcDataTimeStyles not used, always utc, timezone not implemented (o) => EwsUtilities.DateTimeToXSDateTime(<DateTime>o) //ConvertToString ); map.Add( MapiPropertyType.SystemTime, sysTimeConverter); var sysTimeArrayConverter = new MapiTypeConverterMapEntry( MapiTypeConverterTypeSystem.DateTime, (s) => DateTime.Parse(s), //Parse //ref: UtcDataTimeStyles not used, always utc, timezone not implemented (o) => EwsUtilities.DateTimeToXSDateTime(<DateTime>o), //ConvertToString true //IsArray ); map.Add( MapiPropertyType.SystemTimeArray, sysTimeArrayConverter); return map; }); static ChangeType(mapiType: MapiPropertyType, value: any): any { EwsUtilities.ValidateParam(value, "value"); return MapiTypeConverter.MapiTypeConverterMap.get(mapiType).ChangeType(value); } static ConvertToString(mapiPropType: MapiPropertyType, value: any): string { return (value === null || value === undefined) ? StringHelper.Empty : MapiTypeConverter.MapiTypeConverterMap.get(mapiPropType).ConvertToString(value); } static ConvertToValue(mapiPropType: MapiPropertyType, stringValue: string): any; static ConvertToValue(mapiPropType: MapiPropertyType, strings: string[]): any[]; static ConvertToValue(mapiPropType: MapiPropertyType, strings: string | string[]): any|any[] { if (typeof strings === 'string') { return MapiTypeConverter.MapiTypeConverterMap.get(mapiPropType).ConvertToValue(strings); } else if (Array.isArray(strings)) { EwsUtilities.ValidateParam(strings, "strings"); var typeConverter: MapiTypeConverterMapEntry = MapiTypeConverter.MapiTypeConverterMap.get(mapiPropType); var array: any[] = [];// = Array.CreateInstance(typeConverter.Type, strings.length); var index: number = 0; for (var stringValue of strings) { var value: any = typeConverter.ConvertToValueOrDefault(stringValue); array.push(value); } return array; } throw new ArgumentException("parameter not in correct type"); } static IsArrayType(mapiType: MapiPropertyType): boolean { return MapiTypeConverter.MapiTypeConverterMap.get(mapiType).IsArray; } static ParseMapiIntegerValue(s: string): any { var num = Convert.toNumber(s); if (num === NaN) { return s; } return num; } }
the_stack
require('source-map-support').install(); import fs = require("fs"); import tv4 = require('tv4'); import expression = require('../src/expression'); import schema = require('../src/schema'); import path = require('path'); import Json = require('source-processor'); import error = require('source-processor'); export var debug = false; /** * synchronously loads a file resource, converting from YAML to JSON * @param filepath location on filesystem */ export function load_yaml(filepath: string): Json.JValue{ var yaml_text = fs.readFileSync(filepath, {encoding: 'utf8'}).toString(); return Json.parse_yaml(yaml_text); } export function load_json(filepath: string): Json.JValue{ var json_text = fs.readFileSync(filepath, {encoding: 'utf8'}).toString(); return Json.parse(json_text); } /** * synchronously loads a file resource, converting from multi document YAML to a callback with a JSON param */ export function load_yaml_collection(filepath: string, cb:(json: Json.JValue) => void):void{ var yaml_text = fs.readFileSync(filepath, {encoding: 'utf8'}).toString(); Json.parse_yaml_collection(yaml_text, cb); } export var root:string = path.dirname(fs.realpathSync(__filename)) + "/../"; export var rules_schema: Json.JValue = load_yaml(root + "schema/security_rules.yaml"); export function validate_rules(rules: Json.JValue): boolean{ tv4.addSchema("http://firebase.com/schema/types/object#", this.load_yaml(root + "schema/types/object.yaml").toJSON()); tv4.addSchema("http://firebase.com/schema/types/string#", this.load_yaml(root + "schema/types/string.yaml").toJSON()); tv4.addSchema("http://firebase.com/schema/types/boolean#",this.load_yaml(root + "schema/types/boolean.yaml").toJSON()); tv4.addSchema("http://firebase.com/schema/types/number#", this.load_yaml(root + "schema/types/number.yaml").toJSON()); tv4.addSchema("http://firebase.com/schema/types/any#", this.load_yaml(root + "schema/types/any.yaml").toJSON()); tv4.addSchema("http://firebase.com/schema#", this.load_yaml(root + "schema/schema.yaml").toJSON()); tv4.addSchema("http://json-schema.org/draft-04/schema#", fs.readFileSync(root + "schema/jsonschema", {encoding: 'utf8'}).toString()); var valid: boolean = tv4.validate(rules.toJSON(), this.rules_schema.toJSON(), true, true); if (!valid){ throw error.validation( rules, this.rules_schema, "blaze file", "blaze schema", tv4.error) .source(rules.lookup(tv4.error.dataPath.split("/"))) .on(new Error()) } if (tv4.getMissingUris().length != 0){ throw error.missingURI(tv4.getMissingUris()).on(new Error()); } return valid; } export class SchemaRoot{ json: Json.JValue; root: schema.SchemaNode; constructor(json: Json.JValue){ this.json = json; } static parse(json: Json.JValue): SchemaRoot { if (json == null) { json = new Json.JObject() } return new SchemaRoot(json); } } export class AccessEntry{ location: string[]; //components of address, e.g. users/$userid is mapped to ['users', '$userid'] read: expression.Expression = expression.Expression.FALSE; write: expression.Expression = expression.Expression.FALSE; static parse(json: Json.JValue): AccessEntry{ //console.log("AccessEntry.parse:", json); var accessEntry = new AccessEntry(); accessEntry.location = json.getOrThrow("location", "all access entries require a location to be defined") .asString().value.split("/"); //deal with issue of "/*" being split to "['', '*']" by removing first element while (accessEntry.location[0] === ''){ accessEntry.location.shift(); } if (accessEntry.location[accessEntry.location.length-1] == "") { accessEntry.location.pop() } if (json.has("read")){ accessEntry.read = expression.Expression.parseUser(json.getOrThrow("read", "").coerceString()); } if (json.has("write")){ accessEntry.write = expression.Expression.parseUser(json.getOrThrow("write", "").coerceString()); } //console.log("accessEntry.location", accessEntry.location); return accessEntry } match(location: string[]): boolean{ //console.log("checking if ", location, " matches ", this.location); //candidate location must be at least as specific as this location if(this.location.length > location.length) return false; for(var idx in this.location){ if (!this.matchSegment(this.location[idx], location[idx])) return false } //console.log("access entry is applicable"); return true; } // todo hot method isChildOf(location: string[]): boolean{ if (this.location.length <= location.length) return false; for(var idx in location){ if (!this.matchSegment(this.location[idx], location[idx])) return false } return true; } matchSegment(rule_segment: string, path_segment): boolean{ if (rule_segment.indexOf("~$") == 0) rule_segment = rule_segment.substr(1); if (path_segment.indexOf("~$") == 0) path_segment = path_segment.substr(1); if (rule_segment.indexOf("$") == 0 && path_segment.indexOf("$") == 0) return true; return rule_segment == path_segment } /** *localize the read expression for the given path */ getReadFor(symbols: expression.Symbols, path: string[]): expression.Expression { var base_read = expression.Expression.parse(this.read.expandFunctions(symbols)); for (var i = 0; i < path.length - this.location.length; i++) { var rewrite = base_read.rewriteForChild(); base_read = expression.Expression.parse(rewrite) } return base_read } /** *localize the read expression for the given path * we have to expand functions first, so that the insides of functions are also localised */ getWriteFor(symbols: expression.Symbols, path: string[]): expression.Expression { var base_write = expression.Expression.parse(this.write.expandFunctions(symbols)); for (var i = 0; i < path.length - this.location.length; i++) { base_write = expression.Expression.parse(base_write.rewriteForChild()) } return base_write } } export class Access { [index: number]: AccessEntry; static parse(json: Json.JValue):Access{ //console.log("Access.parse:", json); var access = new Access(); if (json == null) return access; json.asArray().forEachIndexed(function(entry: Json.JValue, id: number){ var accessEntry = AccessEntry.parse(entry); access[id] = (accessEntry); }); return access } // todo hot method static getChildren(self: Access, path: string[]): AccessEntry[] { var children: AccessEntry[] = []; for (var i = 0; self[i] != undefined; i++) { var rule: AccessEntry = self[i]; if (rule.isChildOf(path)) children.push(rule) } return children; } } export class Rules{ functions: expression.Functions; schema: SchemaRoot; access: Access; code: string = null; //generated rules, or null static parse(json: Json.JObject):Rules{ var rules = new Rules(); rules.functions = expression.Functions.parse(json.getOrNull("functions")); rules.schema = SchemaRoot.parse(json.getOrNull("schema")); rules.access = Access.parse(json.getOrWarn("access", "no access list defined, this Firebase will be inactive")); return rules } /** * adds dummy schema */ inflateSchema():void { this.inflateSchemaRecursive(this.schema.json.asObject(), [], {}) } inflateSchemaRecursive(json: Json.JObject, path: string[], memoization: {[path: string]: boolean}): void { if (memoization[path.join("/")]) return; //we processed this before else { memoization[path.join("/")] = true; // indicate this has been done } // console.log("inflateSchemaRecursive", path); var children = Access.getChildren(this.access, path); children.map(function(child: AccessEntry) { var childSegment = child.location[path.length]; var schemaChild = null; if (childSegment.indexOf("~$") == 0 || childSegment.indexOf("$") == 0) { //the child is a wildchild var wildKey = schema.getWildchild(json); if (wildKey == null){ schemaChild = new Json.JObject(); console.error("WARNING: " + child.location.join("/") + " in access rule but not in a schema"); json.put(new Json.JString(childSegment, -1,-1), schemaChild); } else { schemaChild = json.getOrThrow(wildKey.getString(), "error"); } } else { //the child is a fixed child, should be declared in properties //lazy create properties if necessary var properties = json.getOrNull("properties"); if (properties == null) { properties = new Json.JObject(); json.put(new Json.JString("properties", -1,-1), properties) } //lazy add child if necessary schemaChild = properties.asObject().getOrNull(childSegment); if (schemaChild == null){ console.error("WARNING: " + child.location.join("/") + " in access rule but not in a schema"); schemaChild = new Json.JObject(); properties.asObject().put(new Json.JString(childSegment, -1,-1), schemaChild); } } this.inflateSchemaRecursive(schemaChild, child.location.slice(0, path.length + 1), memoization); }, this) } }
the_stack
module android.widget { import Canvas = android.graphics.Canvas; import Rect = android.graphics.Rect; import Drawable = android.graphics.drawable.Drawable; import KeyEvent = android.view.KeyEvent; import MotionEvent = android.view.MotionEvent; import ViewConfiguration = android.view.ViewConfiguration; import Integer = java.lang.Integer; import ProgressBar = android.widget.ProgressBar; import AttrBinder = androidui.attr.AttrBinder; export abstract class AbsSeekBar extends ProgressBar { private mThumb:Drawable; private mThumbOffset:number = 0; /** * On touch, this offset plus the scaled value from the position of the * touch will form the progress value. Usually 0. */ mTouchProgressOffset:number = 0; /** * Whether this is user seekable. */ mIsUserSeekable:boolean = true; /** * On key presses (right or left), the amount to increment/decrement the * progress. */ private mKeyProgressIncrement:number = 1; private static NO_ALPHA:number = 0xFF; private mDisabledAlpha:number = 0; private mTouchDownX:number = 0; private mIsDragging:boolean; constructor(context:android.content.Context, bindElement?:HTMLElement, defStyle?:Map<string, string>) { super(context, bindElement, defStyle); let a = context.obtainStyledAttributes(bindElement, defStyle); const thumb = a.getDrawable('thumb'); this.setThumb(thumb); // will guess mThumbOffset if thumb != null... // ...but allow layout to override this const thumbOffset = a.getDimensionPixelOffset('thumbOffset', this.getThumbOffset()); this.setThumbOffset(thumbOffset); a.recycle(); a = context.obtainStyledAttributes(bindElement, defStyle); this.mDisabledAlpha = a.getFloat('disabledAlpha', 0.5); a.recycle(); } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return super.createClassAttrBinder().set('thumb', { setter(v:AbsSeekBar, value:any, attrBinder:AttrBinder) { v.setThumb(attrBinder.parseDrawable(value)); }, getter(v:AbsSeekBar) { return v.mThumb; } }).set('thumbOffset', { setter(v:AbsSeekBar, value:any, attrBinder:AttrBinder) { v.setThumbOffset(attrBinder.parseNumberPixelOffset(value)); }, getter(v:AbsSeekBar) { return v.mThumbOffset; } }).set('disabledAlpha', { setter(v:AbsSeekBar, value:any, attrBinder:AttrBinder) { v.mDisabledAlpha = attrBinder.parseFloat(value, 0.5); }, getter(v:AbsSeekBar) { return v.mDisabledAlpha; } }); } /** * Sets the thumb that will be drawn at the end of the progress meter within the SeekBar. * <p> * If the thumb is a valid drawable (i.e. not null), half its width will be * used as the new thumb offset (@see #setThumbOffset(int)). * * @param thumb Drawable representing the thumb */ setThumb(thumb:Drawable):void { let needUpdate:boolean; // drawable changed) if (this.mThumb != null && thumb != this.mThumb) { this.mThumb.setCallback(null); needUpdate = true; } else { needUpdate = false; } if (thumb != null) { thumb.setCallback(this); //if (this.canResolveLayoutDirection()) { // thumb.setLayoutDirection(this.getLayoutDirection()); //} // Assuming the thumb drawable is symmetric, set the thumb offset // such that the thumb will hang halfway off either edge of the // progress bar. this.mThumbOffset = thumb.getIntrinsicWidth() / 2; // If we're updating get the new states if (needUpdate && (thumb.getIntrinsicWidth() != this.mThumb.getIntrinsicWidth() || thumb.getIntrinsicHeight() != this.mThumb.getIntrinsicHeight())) { this.requestLayout(); } } this.mThumb = thumb; this.invalidate(); if (needUpdate) { this.updateThumbPos(this.getWidth(), this.getHeight()); if (thumb != null && thumb.isStateful()) { // Note that if the states are different this won't work. // For now, let's consider that an app bug. let state:number[] = this.getDrawableState(); thumb.setState(state); } } } /** * Return the drawable used to represent the scroll thumb - the component that * the user can drag back and forth indicating the current value by its position. * * @return The current thumb drawable */ getThumb():Drawable { return this.mThumb; } /** * @see #setThumbOffset(int) */ getThumbOffset():number { return this.mThumbOffset; } /** * Sets the thumb offset that allows the thumb to extend out of the range of * the track. * * @param thumbOffset The offset amount in pixels. */ setThumbOffset(thumbOffset:number):void { this.mThumbOffset = thumbOffset; this.invalidate(); } /** * Sets the amount of progress changed via the arrow keys. * * @param increment The amount to increment or decrement when the user * presses the arrow keys. */ setKeyProgressIncrement(increment:number):void { this.mKeyProgressIncrement = increment < 0 ? -increment : increment; } /** * Returns the amount of progress changed via the arrow keys. * <p> * By default, this will be a value that is derived from the max progress. * * @return The amount to increment or decrement when the user presses the * arrow keys. This will be positive. */ getKeyProgressIncrement():number { return this.mKeyProgressIncrement; } setMax(max:number):void { super.setMax(max); if ((this.mKeyProgressIncrement == 0) || (this.getMax() / this.mKeyProgressIncrement > 20)) { // It will take the user too long to change this via keys, change it // to something more reasonable this.setKeyProgressIncrement(Math.max(1, Math.round(<number> this.getMax() / 20))); } } protected verifyDrawable(who:Drawable):boolean { return who == this.mThumb || super.verifyDrawable(who); } jumpDrawablesToCurrentState():void { super.jumpDrawablesToCurrentState(); if (this.mThumb != null) this.mThumb.jumpToCurrentState(); } protected drawableStateChanged():void { super.drawableStateChanged(); let progressDrawable:Drawable = this.getProgressDrawable(); if (progressDrawable != null) { progressDrawable.setAlpha(this.isEnabled() ? AbsSeekBar.NO_ALPHA : Math.floor((AbsSeekBar.NO_ALPHA * this.mDisabledAlpha))); } if (this.mThumb != null && this.mThumb.isStateful()) { let state:number[] = this.getDrawableState(); this.mThumb.setState(state); } } onProgressRefresh(scale:number, fromUser:boolean):void { super.onProgressRefresh(scale, fromUser); let thumb:Drawable = this.mThumb; if (thumb != null) { this.setThumbPos(this.getWidth(), thumb, scale, Integer.MIN_VALUE); /* * Since we draw translated, the drawable's bounds that it signals * for invalidation won't be the actual bounds we want invalidated, * so just invalidate this whole view. */ this.invalidate(); } } protected onSizeChanged(w:number, h:number, oldw:number, oldh:number):void { super.onSizeChanged(w, h, oldw, oldh); this.updateThumbPos(w, h); } private updateThumbPos(w:number, h:number):void { let d:Drawable = this.getCurrentDrawable(); let thumb:Drawable = this.mThumb; let thumbHeight:number = thumb == null ? 0 : thumb.getIntrinsicHeight(); // The max height does not incorporate padding, whereas the height // parameter does let trackHeight:number = Math.min(this.mMaxHeight, h - this.mPaddingTop - this.mPaddingBottom); let max:number = this.getMax(); let scale:number = max > 0 ? <number> this.getProgress() / <number> max : 0; if (thumbHeight > trackHeight) { if (thumb != null) { this.setThumbPos(w, thumb, scale, 0); } let gapForCenteringTrack:number = (thumbHeight - trackHeight) / 2; if (d != null) { // Canvas will be translated by the padding, so 0,0 is where we start drawing d.setBounds(0, gapForCenteringTrack, w - this.mPaddingRight - this.mPaddingLeft, h - this.mPaddingBottom - gapForCenteringTrack - this.mPaddingTop); } } else { if (d != null) { // Canvas will be translated by the padding, so 0,0 is where we start drawing d.setBounds(0, 0, w - this.mPaddingRight - this.mPaddingLeft, h - this.mPaddingBottom - this.mPaddingTop); } let gap:number = (trackHeight - thumbHeight) / 2; if (thumb != null) { this.setThumbPos(w, thumb, scale, gap); } } } /** * @param gap If set to {@link Integer#MIN_VALUE}, this will be ignored and */ private setThumbPos(w:number, thumb:Drawable, scale:number, gap:number):void { let available:number = w - this.mPaddingLeft - this.mPaddingRight; let thumbWidth:number = thumb.getIntrinsicWidth(); let thumbHeight:number = thumb.getIntrinsicHeight(); available -= thumbWidth; // The extra space for the thumb to move on the track available += this.mThumbOffset * 2; let thumbPos:number = Math.floor((scale * available)); let topBound:number, bottomBound:number; if (gap == Integer.MIN_VALUE) { let oldBounds:Rect = thumb.getBounds(); topBound = oldBounds.top; bottomBound = oldBounds.bottom; } else { topBound = gap; bottomBound = gap + thumbHeight; } // Canvas will be translated, so 0,0 is where we start drawing const left:number = (this.isLayoutRtl() && this.mMirrorForRtl) ? available - thumbPos : thumbPos; thumb.setBounds(left, topBound, left + thumbWidth, bottomBound); } ///** // * @hide // */ //onResolveDrawables(layoutDirection:number):void { // super.onResolveDrawables(layoutDirection); // if (this.mThumb != null) { // this.mThumb.setLayoutDirection(layoutDirection); // } //} protected onDraw(canvas:Canvas):void { super.onDraw(canvas); if (this.mThumb != null) { canvas.save(); // Translate the padding. For the x, we need to allow the thumb to // draw in its extra space canvas.translate(this.mPaddingLeft - this.mThumbOffset, this.mPaddingTop); this.mThumb.draw(canvas); canvas.restore(); } } protected onMeasure(widthMeasureSpec:number, heightMeasureSpec:number):void { let d:Drawable = this.getCurrentDrawable(); let thumbHeight:number = this.mThumb == null ? 0 : this.mThumb.getIntrinsicHeight(); let dw:number = 0; let dh:number = 0; if (d != null) { dw = Math.max(this.mMinWidth, Math.min(this.mMaxWidth, d.getIntrinsicWidth())); dh = Math.max(this.mMinHeight, Math.min(this.mMaxHeight, d.getIntrinsicHeight())); dh = Math.max(thumbHeight, dh); } dw += this.mPaddingLeft + this.mPaddingRight; dh += this.mPaddingTop + this.mPaddingBottom; this.setMeasuredDimension(AbsSeekBar.resolveSizeAndState(dw, widthMeasureSpec, 0), AbsSeekBar.resolveSizeAndState(dh, heightMeasureSpec, 0)); } onTouchEvent(event:MotionEvent):boolean { if (!this.mIsUserSeekable || !this.isEnabled()) { return false; } switch(event.getAction()) { case MotionEvent.ACTION_DOWN: if (this.isInScrollingContainer()) { this.mTouchDownX = event.getX(); } else { this.setPressed(true); if (this.mThumb != null) { // This may be within the padding region this.invalidate(this.mThumb.getBounds()); } this.onStartTrackingTouch(); this.trackTouchEvent(event); this.attemptClaimDrag(); } break; case MotionEvent.ACTION_MOVE: if (this.mIsDragging) { this.trackTouchEvent(event); } else { const x:number = event.getX(); if (Math.abs(x - this.mTouchDownX) > this.mTouchSlop) { this.setPressed(true); if (this.mThumb != null) { // This may be within the padding region this.invalidate(this.mThumb.getBounds()); } this.onStartTrackingTouch(); this.trackTouchEvent(event); this.attemptClaimDrag(); } } break; case MotionEvent.ACTION_UP: if (this.mIsDragging) { this.trackTouchEvent(event); this.onStopTrackingTouch(); this.setPressed(false); } else { // Touch up when we never crossed the touch slop threshold should // be interpreted as a tap-seek to that location. this.onStartTrackingTouch(); this.trackTouchEvent(event); this.onStopTrackingTouch(); } // ProgressBar doesn't know to repaint the thumb drawable // in its inactive state when the touch stops (because the // value has not apparently changed) this.invalidate(); break; case MotionEvent.ACTION_CANCEL: if (this.mIsDragging) { this.onStopTrackingTouch(); this.setPressed(false); } // see above explanation this.invalidate(); break; } return true; } private trackTouchEvent(event:MotionEvent):void { const width:number = this.getWidth(); const available:number = width - this.mPaddingLeft - this.mPaddingRight; let x:number = Math.floor(event.getX()); let scale:number; let progress:number = 0; if (this.isLayoutRtl() && this.mMirrorForRtl) { if (x > width - this.mPaddingRight) { scale = 0.0; } else if (x < this.mPaddingLeft) { scale = 1.0; } else { scale = <number> (available - x + this.mPaddingLeft) / <number> available; progress = this.mTouchProgressOffset; } } else { if (x < this.mPaddingLeft) { scale = 0.0; } else if (x > width - this.mPaddingRight) { scale = 1.0; } else { scale = <number> (x - this.mPaddingLeft) / <number> available; progress = this.mTouchProgressOffset; } } const max:number = this.getMax(); progress += scale * max; this.setProgress(Math.floor(progress), true); } /** * Tries to claim the user's drag motion, and requests disallowing any * ancestors from stealing events in the drag. */ private attemptClaimDrag():void { if (this.mParent != null) { this.mParent.requestDisallowInterceptTouchEvent(true); } } /** * This is called when the user has started touching this widget. */ onStartTrackingTouch():void { this.mIsDragging = true; } /** * This is called when the user either releases his touch or the touch is * canceled. */ onStopTrackingTouch():void { this.mIsDragging = false; } /** * Called when the user changes the seekbar's progress by using a key event. */ onKeyChange():void { } onKeyDown(keyCode:number, event:KeyEvent):boolean { if (this.isEnabled()) { let progress:number = this.getProgress(); switch(keyCode) { case KeyEvent.KEYCODE_DPAD_LEFT: if (progress <= 0) break; this.setProgress(progress - this.mKeyProgressIncrement, true); this.onKeyChange(); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: if (progress >= this.getMax()) break; this.setProgress(progress + this.mKeyProgressIncrement, true); this.onKeyChange(); return true; } } return super.onKeyDown(keyCode, event); } //onRtlPropertiesChanged(layoutDirection:number):void { // super.onRtlPropertiesChanged(layoutDirection); // let max:number = this.getMax(); // let scale:number = max > 0 ? <number> this.getProgress() / <number> max : 0; // let thumb:Drawable = this.mThumb; // if (thumb != null) { // this.setThumbPos(this.getWidth(), thumb, scale, Integer.MIN_VALUE); // /* // * Since we draw translated, the drawable's bounds that it signals // * for invalidation won't be the actual bounds we want invalidated, // * so just invalidate this whole view. // */ // this.invalidate(); // } //} } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Manages an Authorization Server within an API Management Service. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleApi = azure.apimanagement.getApi({ * name: "search-api", * apiManagementName: "search-api-management", * resourceGroupName: "search-service", * revision: "2", * }); * const exampleAuthorizationServer = new azure.apimanagement.AuthorizationServer("exampleAuthorizationServer", { * apiManagementName: data.azurerm_api_management.example.name, * resourceGroupName: data.azurerm_api_management.example.resource_group_name, * displayName: "Test Server", * authorizationEndpoint: "https://example.mydomain.com/client/authorize", * clientId: "42424242-4242-4242-4242-424242424242", * clientRegistrationEndpoint: "https://example.mydomain.com/client/register", * grantTypes: ["authorizationCode"], * }); * ``` * * ## Import * * API Management Authorization Servers can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:apimanagement/authorizationServer:AuthorizationServer example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.ApiManagement/service/service1/authorizationServers/server1 * ``` */ export class AuthorizationServer extends pulumi.CustomResource { /** * Get an existing AuthorizationServer resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: AuthorizationServerState, opts?: pulumi.CustomResourceOptions): AuthorizationServer { return new AuthorizationServer(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:apimanagement/authorizationServer:AuthorizationServer'; /** * Returns true if the given object is an instance of AuthorizationServer. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is AuthorizationServer { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === AuthorizationServer.__pulumiType; } /** * The name of the API Management Service in which this Authorization Server should be created. Changing this forces a new resource to be created. */ public readonly apiManagementName!: pulumi.Output<string>; /** * The OAUTH Authorization Endpoint. */ public readonly authorizationEndpoint!: pulumi.Output<string>; /** * The HTTP Verbs supported by the Authorization Endpoint. Possible values are `DELETE`, `GET`, `HEAD`, `OPTIONS`, `PATCH`, `POST`, `PUT` and `TRACE`. */ public readonly authorizationMethods!: pulumi.Output<string[]>; /** * The mechanism by which Access Tokens are passed to the API. Possible values are `authorizationHeader` and `query`. */ public readonly bearerTokenSendingMethods!: pulumi.Output<string[] | undefined>; /** * The Authentication Methods supported by the Token endpoint of this Authorization Server.. Possible values are `Basic` and `Body`. */ public readonly clientAuthenticationMethods!: pulumi.Output<string[] | undefined>; /** * The Client/App ID registered with this Authorization Server. */ public readonly clientId!: pulumi.Output<string>; /** * The URI of page where Client/App Registration is performed for this Authorization Server. */ public readonly clientRegistrationEndpoint!: pulumi.Output<string>; /** * The Client/App Secret registered with this Authorization Server. */ public readonly clientSecret!: pulumi.Output<string | undefined>; /** * The Default Scope used when requesting an Access Token, specified as a string containing space-delimited values. */ public readonly defaultScope!: pulumi.Output<string | undefined>; /** * A description of the Authorization Server, which may contain HTML formatting tags. */ public readonly description!: pulumi.Output<string | undefined>; /** * The user-friendly name of this Authorization Server. */ public readonly displayName!: pulumi.Output<string>; /** * Form of Authorization Grants required when requesting an Access Token. Possible values are `authorizationCode`, `clientCredentials`, `implicit` and `resourceOwnerPassword`. */ public readonly grantTypes!: pulumi.Output<string[]>; /** * The name of this Authorization Server. Changing this forces a new resource to be created. */ public readonly name!: pulumi.Output<string>; /** * The name of the Resource Group in which the API Management Service exists. Changing this forces a new resource to be created. */ public readonly resourceGroupName!: pulumi.Output<string>; /** * The password associated with the Resource Owner. */ public readonly resourceOwnerPassword!: pulumi.Output<string | undefined>; /** * The username associated with the Resource Owner. */ public readonly resourceOwnerUsername!: pulumi.Output<string | undefined>; /** * Does this Authorization Server support State? If this is set to `true` the client may use the state parameter to raise protocol security. */ public readonly supportState!: pulumi.Output<boolean | undefined>; /** * A `tokenBodyParameter` block as defined below. */ public readonly tokenBodyParameters!: pulumi.Output<outputs.apimanagement.AuthorizationServerTokenBodyParameter[] | undefined>; /** * The OAUTH Token Endpoint. */ public readonly tokenEndpoint!: pulumi.Output<string | undefined>; /** * Create a AuthorizationServer resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: AuthorizationServerArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: AuthorizationServerArgs | AuthorizationServerState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as AuthorizationServerState | undefined; inputs["apiManagementName"] = state ? state.apiManagementName : undefined; inputs["authorizationEndpoint"] = state ? state.authorizationEndpoint : undefined; inputs["authorizationMethods"] = state ? state.authorizationMethods : undefined; inputs["bearerTokenSendingMethods"] = state ? state.bearerTokenSendingMethods : undefined; inputs["clientAuthenticationMethods"] = state ? state.clientAuthenticationMethods : undefined; inputs["clientId"] = state ? state.clientId : undefined; inputs["clientRegistrationEndpoint"] = state ? state.clientRegistrationEndpoint : undefined; inputs["clientSecret"] = state ? state.clientSecret : undefined; inputs["defaultScope"] = state ? state.defaultScope : undefined; inputs["description"] = state ? state.description : undefined; inputs["displayName"] = state ? state.displayName : undefined; inputs["grantTypes"] = state ? state.grantTypes : undefined; inputs["name"] = state ? state.name : undefined; inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined; inputs["resourceOwnerPassword"] = state ? state.resourceOwnerPassword : undefined; inputs["resourceOwnerUsername"] = state ? state.resourceOwnerUsername : undefined; inputs["supportState"] = state ? state.supportState : undefined; inputs["tokenBodyParameters"] = state ? state.tokenBodyParameters : undefined; inputs["tokenEndpoint"] = state ? state.tokenEndpoint : undefined; } else { const args = argsOrState as AuthorizationServerArgs | undefined; if ((!args || args.apiManagementName === undefined) && !opts.urn) { throw new Error("Missing required property 'apiManagementName'"); } if ((!args || args.authorizationEndpoint === undefined) && !opts.urn) { throw new Error("Missing required property 'authorizationEndpoint'"); } if ((!args || args.authorizationMethods === undefined) && !opts.urn) { throw new Error("Missing required property 'authorizationMethods'"); } if ((!args || args.clientId === undefined) && !opts.urn) { throw new Error("Missing required property 'clientId'"); } if ((!args || args.clientRegistrationEndpoint === undefined) && !opts.urn) { throw new Error("Missing required property 'clientRegistrationEndpoint'"); } if ((!args || args.displayName === undefined) && !opts.urn) { throw new Error("Missing required property 'displayName'"); } if ((!args || args.grantTypes === undefined) && !opts.urn) { throw new Error("Missing required property 'grantTypes'"); } if ((!args || args.resourceGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupName'"); } inputs["apiManagementName"] = args ? args.apiManagementName : undefined; inputs["authorizationEndpoint"] = args ? args.authorizationEndpoint : undefined; inputs["authorizationMethods"] = args ? args.authorizationMethods : undefined; inputs["bearerTokenSendingMethods"] = args ? args.bearerTokenSendingMethods : undefined; inputs["clientAuthenticationMethods"] = args ? args.clientAuthenticationMethods : undefined; inputs["clientId"] = args ? args.clientId : undefined; inputs["clientRegistrationEndpoint"] = args ? args.clientRegistrationEndpoint : undefined; inputs["clientSecret"] = args ? args.clientSecret : undefined; inputs["defaultScope"] = args ? args.defaultScope : undefined; inputs["description"] = args ? args.description : undefined; inputs["displayName"] = args ? args.displayName : undefined; inputs["grantTypes"] = args ? args.grantTypes : undefined; inputs["name"] = args ? args.name : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined; inputs["resourceOwnerPassword"] = args ? args.resourceOwnerPassword : undefined; inputs["resourceOwnerUsername"] = args ? args.resourceOwnerUsername : undefined; inputs["supportState"] = args ? args.supportState : undefined; inputs["tokenBodyParameters"] = args ? args.tokenBodyParameters : undefined; inputs["tokenEndpoint"] = args ? args.tokenEndpoint : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(AuthorizationServer.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering AuthorizationServer resources. */ export interface AuthorizationServerState { /** * The name of the API Management Service in which this Authorization Server should be created. Changing this forces a new resource to be created. */ apiManagementName?: pulumi.Input<string>; /** * The OAUTH Authorization Endpoint. */ authorizationEndpoint?: pulumi.Input<string>; /** * The HTTP Verbs supported by the Authorization Endpoint. Possible values are `DELETE`, `GET`, `HEAD`, `OPTIONS`, `PATCH`, `POST`, `PUT` and `TRACE`. */ authorizationMethods?: pulumi.Input<pulumi.Input<string>[]>; /** * The mechanism by which Access Tokens are passed to the API. Possible values are `authorizationHeader` and `query`. */ bearerTokenSendingMethods?: pulumi.Input<pulumi.Input<string>[]>; /** * The Authentication Methods supported by the Token endpoint of this Authorization Server.. Possible values are `Basic` and `Body`. */ clientAuthenticationMethods?: pulumi.Input<pulumi.Input<string>[]>; /** * The Client/App ID registered with this Authorization Server. */ clientId?: pulumi.Input<string>; /** * The URI of page where Client/App Registration is performed for this Authorization Server. */ clientRegistrationEndpoint?: pulumi.Input<string>; /** * The Client/App Secret registered with this Authorization Server. */ clientSecret?: pulumi.Input<string>; /** * The Default Scope used when requesting an Access Token, specified as a string containing space-delimited values. */ defaultScope?: pulumi.Input<string>; /** * A description of the Authorization Server, which may contain HTML formatting tags. */ description?: pulumi.Input<string>; /** * The user-friendly name of this Authorization Server. */ displayName?: pulumi.Input<string>; /** * Form of Authorization Grants required when requesting an Access Token. Possible values are `authorizationCode`, `clientCredentials`, `implicit` and `resourceOwnerPassword`. */ grantTypes?: pulumi.Input<pulumi.Input<string>[]>; /** * The name of this Authorization Server. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * The name of the Resource Group in which the API Management Service exists. Changing this forces a new resource to be created. */ resourceGroupName?: pulumi.Input<string>; /** * The password associated with the Resource Owner. */ resourceOwnerPassword?: pulumi.Input<string>; /** * The username associated with the Resource Owner. */ resourceOwnerUsername?: pulumi.Input<string>; /** * Does this Authorization Server support State? If this is set to `true` the client may use the state parameter to raise protocol security. */ supportState?: pulumi.Input<boolean>; /** * A `tokenBodyParameter` block as defined below. */ tokenBodyParameters?: pulumi.Input<pulumi.Input<inputs.apimanagement.AuthorizationServerTokenBodyParameter>[]>; /** * The OAUTH Token Endpoint. */ tokenEndpoint?: pulumi.Input<string>; } /** * The set of arguments for constructing a AuthorizationServer resource. */ export interface AuthorizationServerArgs { /** * The name of the API Management Service in which this Authorization Server should be created. Changing this forces a new resource to be created. */ apiManagementName: pulumi.Input<string>; /** * The OAUTH Authorization Endpoint. */ authorizationEndpoint: pulumi.Input<string>; /** * The HTTP Verbs supported by the Authorization Endpoint. Possible values are `DELETE`, `GET`, `HEAD`, `OPTIONS`, `PATCH`, `POST`, `PUT` and `TRACE`. */ authorizationMethods: pulumi.Input<pulumi.Input<string>[]>; /** * The mechanism by which Access Tokens are passed to the API. Possible values are `authorizationHeader` and `query`. */ bearerTokenSendingMethods?: pulumi.Input<pulumi.Input<string>[]>; /** * The Authentication Methods supported by the Token endpoint of this Authorization Server.. Possible values are `Basic` and `Body`. */ clientAuthenticationMethods?: pulumi.Input<pulumi.Input<string>[]>; /** * The Client/App ID registered with this Authorization Server. */ clientId: pulumi.Input<string>; /** * The URI of page where Client/App Registration is performed for this Authorization Server. */ clientRegistrationEndpoint: pulumi.Input<string>; /** * The Client/App Secret registered with this Authorization Server. */ clientSecret?: pulumi.Input<string>; /** * The Default Scope used when requesting an Access Token, specified as a string containing space-delimited values. */ defaultScope?: pulumi.Input<string>; /** * A description of the Authorization Server, which may contain HTML formatting tags. */ description?: pulumi.Input<string>; /** * The user-friendly name of this Authorization Server. */ displayName: pulumi.Input<string>; /** * Form of Authorization Grants required when requesting an Access Token. Possible values are `authorizationCode`, `clientCredentials`, `implicit` and `resourceOwnerPassword`. */ grantTypes: pulumi.Input<pulumi.Input<string>[]>; /** * The name of this Authorization Server. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * The name of the Resource Group in which the API Management Service exists. Changing this forces a new resource to be created. */ resourceGroupName: pulumi.Input<string>; /** * The password associated with the Resource Owner. */ resourceOwnerPassword?: pulumi.Input<string>; /** * The username associated with the Resource Owner. */ resourceOwnerUsername?: pulumi.Input<string>; /** * Does this Authorization Server support State? If this is set to `true` the client may use the state parameter to raise protocol security. */ supportState?: pulumi.Input<boolean>; /** * A `tokenBodyParameter` block as defined below. */ tokenBodyParameters?: pulumi.Input<pulumi.Input<inputs.apimanagement.AuthorizationServerTokenBodyParameter>[]>; /** * The OAUTH Token Endpoint. */ tokenEndpoint?: pulumi.Input<string>; }
the_stack
import { getHeapStatistics } from 'v8'; import { CancellationToken, CompletionItem, DocumentSymbol } from 'vscode-languageserver'; import { TextDocumentContentChangeEvent } from 'vscode-languageserver-textdocument'; import { CallHierarchyIncomingCall, CallHierarchyItem, CallHierarchyOutgoingCall, CompletionList, DocumentHighlight, MarkupKind, } from 'vscode-languageserver-types'; import { OperationCanceledException, throwIfCancellationRequested } from '../common/cancellationUtils'; import { appendArray } from '../common/collectionUtils'; import { ConfigOptions, ExecutionEnvironment } from '../common/configOptions'; import { ConsoleInterface, StandardConsole } from '../common/console'; import { assert, assertNever } from '../common/debug'; import { Diagnostic } from '../common/diagnostic'; import { FileDiagnostics } from '../common/diagnosticSink'; import { FileEditAction, FileEditActions, TextEditAction } from '../common/editAction'; import { LanguageServiceExtension } from '../common/extensibility'; import { LogTracker } from '../common/logTracker'; import { combinePaths, getDirectoryPath, getFileName, getRelativePath, isFile, makeDirectories, normalizePath, normalizePathCase, stripFileExtension, } from '../common/pathUtils'; import { convertPositionToOffset, convertRangeToTextRange, convertTextRangeToRange } from '../common/positionUtils'; import { computeCompletionSimilarity } from '../common/stringUtils'; import { DocumentRange, doesRangeContain, doRangesIntersect, Position, Range } from '../common/textRange'; import { Duration, timingStats } from '../common/timing'; import { AutoImporter, AutoImportResult, buildModuleSymbolsMap, ModuleSymbolMap, } from '../languageService/autoImporter'; import { CallHierarchyProvider } from '../languageService/callHierarchyProvider'; import { AbbreviationMap, CompletionMap, CompletionOptions, CompletionResultsList, } from '../languageService/completionProvider'; import { DefinitionFilter } from '../languageService/definitionProvider'; import { DocumentSymbolCollector } from '../languageService/documentSymbolCollector'; import { IndexOptions, IndexResults, WorkspaceSymbolCallback } from '../languageService/documentSymbolProvider'; import { HoverResults } from '../languageService/hoverProvider'; import { ReferenceCallback, ReferencesResult } from '../languageService/referencesProvider'; import { RenameModuleProvider } from '../languageService/renameModuleProvider'; import { SignatureHelpResults } from '../languageService/signatureHelpProvider'; import { ParseNodeType } from '../parser/parseNodes'; import { ParseResults } from '../parser/parser'; import { AbsoluteModuleDescriptor, ImportLookupResult } from './analyzerFileInfo'; import * as AnalyzerNodeInfo from './analyzerNodeInfo'; import { CircularDependency } from './circularDependency'; import { Declaration } from './declaration'; import { ImportResolver } from './importResolver'; import { ImportResult, ImportType } from './importResult'; import { findNodeByOffset, getDocString } from './parseTreeUtils'; import { Scope } from './scope'; import { getScopeForNode } from './scopeUtils'; import { SourceFile } from './sourceFile'; import { isStubFile, SourceMapper } from './sourceMapper'; import { Symbol } from './symbol'; import { isPrivateOrProtectedName } from './symbolNameUtils'; import { createTracePrinter } from './tracePrinter'; import { TypeEvaluator } from './typeEvaluatorTypes'; import { createTypeEvaluatorWithTracker } from './typeEvaluatorWithTracker'; import { PrintTypeFlags } from './typePrinter'; import { Type } from './types'; import { TypeStubWriter } from './typeStubWriter'; const _maxImportDepth = 256; export const MaxWorkspaceIndexFileCount = 2000; // Tracks information about each source file in a program, // including the reason it was added to the program and any // dependencies that it has on other files in the program. export interface SourceFileInfo { // Reference to the source file sourceFile: SourceFile; // Information about the source file isTypeshedFile: boolean; isThirdPartyImport: boolean; isThirdPartyPyTypedPresent: boolean; diagnosticsVersion?: number | undefined; builtinsImport?: SourceFileInfo | undefined; ipythonDisplayImport?: SourceFileInfo | undefined; // Information about the chained source file // Chained source file is not supposed to exist on file system but // must exist in the program's source file list. Module level // scope of the chained source file will be inserted before // current file's scope. chainedSourceFile?: SourceFileInfo | undefined; // Information about why the file is included in the program // and its relation to other source files in the program. isTracked: boolean; isOpenByClient: boolean; imports: SourceFileInfo[]; importedBy: SourceFileInfo[]; shadows: SourceFileInfo[]; shadowedBy: SourceFileInfo[]; } export interface MaxAnalysisTime { // Maximum number of ms to analyze when there are open files // that require analysis. This number is usually kept relatively // small to guarantee responsiveness during typing. openFilesTimeInMs: number; // Maximum number of ms to analyze when all open files and their // dependencies have been analyzed. This number can be higher // to reduce overall analysis time but needs to be short enough // to remain responsive if an open file is modified. noOpenFilesTimeInMs: number; } export interface Indices { setWorkspaceIndex(path: string, indexResults: IndexResults): void; getIndex(execEnv: string | undefined): Map<string, IndexResults> | undefined; setIndex(execEnv: string | undefined, path: string, indexResults: IndexResults): void; reset(): void; } interface UpdateImportInfo { path: string; isTypeshedFile: boolean; isThirdPartyImport: boolean; isPyTypedPresent: boolean; } export type PreCheckCallback = (parseResults: ParseResults, evaluator: TypeEvaluator) => void; export interface OpenFileOptions { isTracked: boolean; ipythonMode: boolean; chainedFilePath: string | undefined; } // Container for all of the files that are being analyzed. Files // can fall into one or more of the following categories: // Tracked - specified by the config options // Referenced - part of the transitive closure // Opened - temporarily opened in the editor // Shadowed - implementation file that shadows a type stub file export class Program { private _console: ConsoleInterface; private _sourceFileList: SourceFileInfo[] = []; private _sourceFileMap = new Map<string, SourceFileInfo>(); private _allowedThirdPartyImports: string[] | undefined; private _evaluator: TypeEvaluator | undefined; private _configOptions: ConfigOptions; private _importResolver: ImportResolver; private _logTracker: LogTracker; private _parsedFileCount = 0; private _preCheckCallback: PreCheckCallback | undefined; constructor( initialImportResolver: ImportResolver, initialConfigOptions: ConfigOptions, console?: ConsoleInterface, private _extension?: LanguageServiceExtension, logTracker?: LogTracker, private _disableChecker?: boolean ) { this._console = console || new StandardConsole(); this._logTracker = logTracker ?? new LogTracker(console, 'FG'); this._importResolver = initialImportResolver; this._configOptions = initialConfigOptions; this._createNewEvaluator(); } get evaluator(): TypeEvaluator | undefined { return this._evaluator; } setConfigOptions(configOptions: ConfigOptions) { this._configOptions = configOptions; // Create a new evaluator with the updated config options. this._createNewEvaluator(); } setImportResolver(importResolver: ImportResolver) { this._importResolver = importResolver; // Create a new evaluator with the updated import resolver. // Otherwise, lookup import passed to type evaluator might use // older import resolver when resolving imports after parsing. this._createNewEvaluator(); } // Sets the list of tracked files that make up the program. setTrackedFiles(filePaths: string[]): FileDiagnostics[] { if (this._sourceFileList.length > 0) { // We need to determine which files to remove from the existing file list. const newFileMap = new Map<string, string>(); filePaths.forEach((path) => { newFileMap.set(normalizePathCase(this._fs, path), path); }); // Files that are not in the tracked file list are // marked as no longer tracked. this._sourceFileList.forEach((oldFile) => { const filePath = normalizePathCase(this._fs, oldFile.sourceFile.getFilePath()); if (!newFileMap.has(filePath)) { oldFile.isTracked = false; } }); } // Add the new files. Only the new items will be added. this.addTrackedFiles(filePaths); return this._removeUnneededFiles(); } // Allows a caller to set a callback that is called right before // a source file is type checked. It is intended for testing only. setPreCheckCallback(preCheckCallback: PreCheckCallback) { this._preCheckCallback = preCheckCallback; } // By default, no third-party imports are allowed. This enables // third-party imports for a specified import and its children. // For example, if importNames is ['tensorflow'], then third-party // (absolute) imports are allowed for 'import tensorflow', // 'import tensorflow.optimizers', etc. setAllowedThirdPartyImports(importNames: string[]) { this._allowedThirdPartyImports = importNames; } addTrackedFiles(filePaths: string[], isThirdPartyImport = false, isInPyTypedPackage = false) { filePaths.forEach((filePath) => { this.addTrackedFile(filePath, isThirdPartyImport, isInPyTypedPackage); }); } addTrackedFile(filePath: string, isThirdPartyImport = false, isInPyTypedPackage = false): SourceFile { let sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (sourceFileInfo) { sourceFileInfo.isTracked = true; return sourceFileInfo.sourceFile; } const importName = this._getImportNameForFile(filePath); const sourceFile = new SourceFile( this._fs, filePath, importName, isThirdPartyImport, isInPyTypedPackage, this._console, this._logTracker ); sourceFileInfo = { sourceFile, isTracked: true, isOpenByClient: false, isTypeshedFile: false, isThirdPartyImport, isThirdPartyPyTypedPresent: isInPyTypedPackage, diagnosticsVersion: undefined, imports: [], importedBy: [], shadows: [], shadowedBy: [], }; this._addToSourceFileListAndMap(sourceFileInfo); return sourceFile; } setFileOpened( filePath: string, version: number | null, contents: TextDocumentContentChangeEvent[], options?: OpenFileOptions ) { let sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { const importName = this._getImportNameForFile(filePath); const sourceFile = new SourceFile( this._fs, filePath, importName, /* isThirdPartyImport */ false, /* isInPyTypedPackage */ false, this._console, this._logTracker, options?.ipythonMode ?? false ); const chainedFilePath = options?.chainedFilePath; sourceFileInfo = { sourceFile, isTracked: options?.isTracked ?? false, chainedSourceFile: chainedFilePath ? this._getSourceFileInfoFromPath(chainedFilePath) : undefined, isOpenByClient: true, isTypeshedFile: false, isThirdPartyImport: false, isThirdPartyPyTypedPresent: false, diagnosticsVersion: undefined, imports: [], importedBy: [], shadows: [], shadowedBy: [], }; this._addToSourceFileListAndMap(sourceFileInfo); } else { sourceFileInfo.isOpenByClient = true; // Reset the diagnostic version so we force an update to the // diagnostics, which can change based on whether the file is open. // We do not set the version to undefined here because that implies // there are no diagnostics currently reported for this file. sourceFileInfo.diagnosticsVersion = 0; } sourceFileInfo.sourceFile.setClientVersion(version, contents); } updateChainedFilePath(filePath: string, chainedFilePath: string | undefined) { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (sourceFileInfo) { sourceFileInfo.chainedSourceFile = chainedFilePath ? this._getSourceFileInfoFromPath(chainedFilePath) : undefined; sourceFileInfo.sourceFile.markDirty(); this._markFileDirtyRecursive(sourceFileInfo, new Map<string, boolean>()); } } setFileClosed(filePath: string): FileDiagnostics[] { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (sourceFileInfo) { sourceFileInfo.isOpenByClient = false; sourceFileInfo.sourceFile.setClientVersion(null, []); // There is no guarantee that content is saved before the file is closed. // We need to mark the file dirty so we can re-analyze next time. // This won't matter much for OpenFileOnly users, but it will matter for // people who use diagnosticMode Workspace. if (sourceFileInfo.sourceFile.didContentsChangeOnDisk()) { sourceFileInfo.sourceFile.markDirty(); this._markFileDirtyRecursive(sourceFileInfo, new Map<string, boolean>()); } } return this._removeUnneededFiles(); } markAllFilesDirty(evenIfContentsAreSame: boolean, indexingNeeded = true) { const markDirtyMap = new Map<string, boolean>(); this._sourceFileList.forEach((sourceFileInfo) => { if (evenIfContentsAreSame) { sourceFileInfo.sourceFile.markDirty(indexingNeeded); } else if (sourceFileInfo.sourceFile.didContentsChangeOnDisk()) { sourceFileInfo.sourceFile.markDirty(indexingNeeded); // Mark any files that depend on this file as dirty // also. This will retrigger analysis of these other files. this._markFileDirtyRecursive(sourceFileInfo, markDirtyMap); } }); if (markDirtyMap.size > 0) { this._createNewEvaluator(); } } markFilesDirty(filePaths: string[], evenIfContentsAreSame: boolean, indexingNeeded = true) { const markDirtyMap = new Map<string, boolean>(); filePaths.forEach((filePath) => { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (sourceFileInfo) { const fileName = getFileName(filePath); // Handle builtins and __builtins__ specially. They are implicitly // included by all source files. if (fileName === 'builtins.pyi' || fileName === '__builtins__.pyi') { this.markAllFilesDirty(evenIfContentsAreSame, indexingNeeded); return; } // If !evenIfContentsAreSame, see if the on-disk contents have // changed. If the file is open, the on-disk contents don't matter // because we'll receive updates directly from the client. if ( evenIfContentsAreSame || (!sourceFileInfo.isOpenByClient && sourceFileInfo.sourceFile.didContentsChangeOnDisk()) ) { sourceFileInfo.sourceFile.markDirty(indexingNeeded); // Mark any files that depend on this file as dirty // also. This will retrigger analysis of these other files. this._markFileDirtyRecursive(sourceFileInfo, markDirtyMap); } } }); if (markDirtyMap.size > 0) { this._createNewEvaluator(); } } getFileCount() { return this._sourceFileList.length; } // Returns the number of files that are considered "user" files and therefore // are checked. getUserFileCount() { return this._sourceFileList.filter((s) => this._isUserCode(s)).length; } getTracked(): SourceFileInfo[] { return this._sourceFileList.filter((s) => s.isTracked); } getOpened(): SourceFileInfo[] { return this._sourceFileList.filter((s) => s.isOpenByClient); } getFilesToAnalyzeCount() { let sourceFileCount = 0; if (this._disableChecker) { return sourceFileCount; } this._sourceFileList.forEach((fileInfo) => { if (fileInfo.sourceFile.isCheckingRequired()) { if (this._shouldCheckFile(fileInfo)) { sourceFileCount++; } } }); return sourceFileCount; } isCheckingOnlyOpenFiles() { return this._configOptions.checkOnlyOpenFiles || false; } containsSourceFileIn(folder: string): boolean { const normalized = normalizePathCase(this._fs, folder); return this._sourceFileList.some((i) => i.sourceFile.getFilePath().startsWith(normalized)); } getSourceFile(filePath: string): SourceFile | undefined { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { return undefined; } return sourceFileInfo.sourceFile; } getBoundSourceFile(filePath: string): SourceFile | undefined { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { return undefined; } this._bindFile(sourceFileInfo); return this.getSourceFile(filePath); } // Performs parsing and analysis of any source files in the program // that require it. If a limit time is specified, the operation // is interrupted when the time expires. The return value indicates // whether the method needs to be called again to complete the // analysis. In interactive mode, the timeout is always limited // to the smaller value to maintain responsiveness. analyze(maxTime?: MaxAnalysisTime, token: CancellationToken = CancellationToken.None): boolean { return this._runEvaluatorWithCancellationToken(token, () => { const elapsedTime = new Duration(); const openFiles = this._sourceFileList.filter( (sf) => sf.isOpenByClient && sf.sourceFile.isCheckingRequired() ); if (openFiles.length > 0) { const effectiveMaxTime = maxTime ? maxTime.openFilesTimeInMs : Number.MAX_VALUE; // Check the open files. for (const sourceFileInfo of openFiles) { if (this._checkTypes(sourceFileInfo)) { if (elapsedTime.getDurationInMilliseconds() > effectiveMaxTime) { return true; } } } // If the caller specified a maxTime, return at this point // since we've finalized all open files. We want to get // the results to the user as quickly as possible. if (maxTime !== undefined) { return true; } } if (!this._configOptions.checkOnlyOpenFiles) { const effectiveMaxTime = maxTime ? maxTime.noOpenFilesTimeInMs : Number.MAX_VALUE; // Now do type parsing and analysis of the remaining. for (const sourceFileInfo of this._sourceFileList) { if (!this._isUserCode(sourceFileInfo)) { continue; } if (this._checkTypes(sourceFileInfo)) { if (elapsedTime.getDurationInMilliseconds() > effectiveMaxTime) { return true; } } } } return false; }); } indexWorkspace(callback: (path: string, results: IndexResults) => void, token: CancellationToken): number { if (!this._configOptions.indexing) { return 0; } return this._runEvaluatorWithCancellationToken(token, () => { // Go through all workspace files to create indexing data. // This will cause all files in the workspace to be parsed and bound. But // _handleMemoryHighUsage will make sure we don't OOM and // at the end of this method, we will drop all trees and symbol tables // created due to indexing. const initiallyParsedSet = new Set<SourceFileInfo>(); for (const sourceFileInfo of this._sourceFileList) { if (!sourceFileInfo.sourceFile.isParseRequired()) { initiallyParsedSet.add(sourceFileInfo); } } let count = 0; for (const sourceFileInfo of this._sourceFileList) { if (!this._isUserCode(sourceFileInfo) || !sourceFileInfo.sourceFile.isIndexingRequired()) { continue; } this._bindFile(sourceFileInfo); const results = sourceFileInfo.sourceFile.index({ indexingForAutoImportMode: false }, token); if (results) { if (++count > MaxWorkspaceIndexFileCount) { this._console.warn(`Workspace indexing has hit its upper limit: 2000 files`); dropParseAndBindInfoCreatedForIndexing(this._sourceFileList, initiallyParsedSet); return count; } callback(sourceFileInfo.sourceFile.getFilePath(), results); } this._handleMemoryHighUsage(); } dropParseAndBindInfoCreatedForIndexing(this._sourceFileList, initiallyParsedSet); return count; }); function dropParseAndBindInfoCreatedForIndexing( sourceFiles: SourceFileInfo[], initiallyParsedSet: Set<SourceFileInfo> ) { for (const sourceFileInfo of sourceFiles) { if (sourceFileInfo.sourceFile.isParseRequired() || initiallyParsedSet.has(sourceFileInfo)) { continue; } // Drop parse and bind info created during indexing. sourceFileInfo.sourceFile.dropParseAndBindInfo(); } } } // Prints a detailed list of files that have been checked and the times associated // with each of them, sorted greatest to least. printDetailedAnalysisTimes() { const sortedFiles = this._sourceFileList .filter((s) => s.sourceFile.getCheckTime() !== undefined) .sort((a, b) => { return b.sourceFile.getCheckTime()! - a.sourceFile.getCheckTime()!; }); this._console.info(''); this._console.info('Analysis time by file'); sortedFiles.forEach((sfInfo) => { const checkTimeInMs = sfInfo.sourceFile.getCheckTime()!; this._console.info(`${checkTimeInMs}ms: ${sfInfo.sourceFile.getFilePath()}`); }); } // Prints import dependency information for each of the files in // the program, skipping any typeshed files. printDependencies(projectRootDir: string, verbose: boolean) { const fs = this._importResolver.fileSystem; const sortedFiles = this._sourceFileList .filter((s) => !s.isTypeshedFile) .sort((a, b) => { return fs.getOriginalFilePath(a.sourceFile.getFilePath()) < fs.getOriginalFilePath(b.sourceFile.getFilePath()) ? 1 : -1; }); const zeroImportFiles: SourceFile[] = []; sortedFiles.forEach((sfInfo) => { this._console.info(''); let filePath = fs.getOriginalFilePath(sfInfo.sourceFile.getFilePath()); const relPath = getRelativePath(filePath, projectRootDir); if (relPath) { filePath = relPath; } this._console.info(`${filePath}`); this._console.info( ` Imports ${sfInfo.imports.length} ` + `file${sfInfo.imports.length === 1 ? '' : 's'}` ); if (verbose) { sfInfo.imports.forEach((importInfo) => { this._console.info(` ${fs.getOriginalFilePath(importInfo.sourceFile.getFilePath())}`); }); } this._console.info( ` Imported by ${sfInfo.importedBy.length} ` + `file${sfInfo.importedBy.length === 1 ? '' : 's'}` ); if (verbose) { sfInfo.importedBy.forEach((importInfo) => { this._console.info(` ${fs.getOriginalFilePath(importInfo.sourceFile.getFilePath())}`); }); } if (sfInfo.importedBy.length === 0) { zeroImportFiles.push(sfInfo.sourceFile); } }); if (zeroImportFiles.length > 0) { this._console.info(''); this._console.info( `${zeroImportFiles.length} file${zeroImportFiles.length === 1 ? '' : 's'}` + ` not explicitly imported` ); zeroImportFiles.forEach((importFile) => { this._console.info(` ${fs.getOriginalFilePath(importFile.getFilePath())}`); }); } } writeTypeStub(targetImportPath: string, targetIsSingleFile: boolean, stubPath: string, token: CancellationToken) { for (const sourceFileInfo of this._sourceFileList) { throwIfCancellationRequested(token); const filePath = sourceFileInfo.sourceFile.getFilePath(); // Generate type stubs only for the files within the target path, // not any files that the target module happened to import. const relativePath = getRelativePath(filePath, targetImportPath); if (relativePath !== undefined) { let typeStubPath = normalizePath(combinePaths(stubPath, relativePath)); // If the target is a single file implementation, as opposed to // a package in a directory, transform the name of the type stub // to __init__.pyi because we're placing it in a directory. if (targetIsSingleFile) { typeStubPath = combinePaths(getDirectoryPath(typeStubPath), '__init__.pyi'); } else { typeStubPath = stripFileExtension(typeStubPath) + '.pyi'; } const typeStubDir = getDirectoryPath(typeStubPath); try { makeDirectories(this._fs, typeStubDir, stubPath); } catch (e: any) { const errMsg = `Could not create directory for '${typeStubDir}'`; throw new Error(errMsg); } this._bindFile(sourceFileInfo); this._runEvaluatorWithCancellationToken(token, () => { const writer = new TypeStubWriter(typeStubPath, sourceFileInfo.sourceFile, this._evaluator!); writer.write(); }); // This operation can consume significant memory, so check // for situations where we need to discard the type cache. this._handleMemoryHighUsage(); } } } getTypeOfSymbol(symbol: Symbol) { this._handleMemoryHighUsage(); const evaluator = this._evaluator || this._createNewEvaluator(); return evaluator.getEffectiveTypeOfSymbol(symbol); } printType(type: Type, expandTypeAlias: boolean): string { this._handleMemoryHighUsage(); const evaluator = this._evaluator || this._createNewEvaluator(); return evaluator.printType(type, expandTypeAlias); } private static _getPrintTypeFlags(configOptions: ConfigOptions): PrintTypeFlags { let flags = PrintTypeFlags.None; if (configOptions.diagnosticRuleSet.printUnknownAsAny) { flags |= PrintTypeFlags.PrintUnknownWithAny; } if (configOptions.diagnosticRuleSet.omitConditionalConstraint) { flags |= PrintTypeFlags.OmitConditionalConstraint; } if (configOptions.diagnosticRuleSet.omitTypeArgsIfAny) { flags |= PrintTypeFlags.OmitTypeArgumentsIfAny; } if (configOptions.diagnosticRuleSet.omitUnannotatedParamType) { flags |= PrintTypeFlags.OmitUnannotatedParamType; } if (configOptions.diagnosticRuleSet.pep604Printing) { flags |= PrintTypeFlags.PEP604; } return flags; } private get _fs() { return this._importResolver.fileSystem; } private _getImportNameForFile(filePath: string) { const moduleNameAndType = this._importResolver.getModuleNameForImport( filePath, this._configOptions.getDefaultExecEnvironment() ); return moduleNameAndType.moduleName; } // A "shadowed" file is a python source file that has been added to the program because // it "shadows" a type stub file for purposes of finding doc strings and definitions. // We need to track the relationship so if the original type stub is removed from the // program, we can remove the corresponding shadowed file and any files it imports. private _addShadowedFile(stubFile: SourceFileInfo, shadowImplPath: string): SourceFile { let shadowFileInfo = this._getSourceFileInfoFromPath(shadowImplPath); if (!shadowFileInfo) { const importName = this._getImportNameForFile(shadowImplPath); const sourceFile = new SourceFile( this._fs, shadowImplPath, importName, /* isThirdPartyImport */ false, /* isInPyTypedPackage */ false, this._console, this._logTracker ); shadowFileInfo = { sourceFile, isTracked: false, isOpenByClient: false, isTypeshedFile: false, isThirdPartyImport: false, isThirdPartyPyTypedPresent: false, diagnosticsVersion: undefined, imports: [], importedBy: [], shadows: [], shadowedBy: [], }; this._addToSourceFileListAndMap(shadowFileInfo); } if (!shadowFileInfo.shadows.includes(stubFile)) { shadowFileInfo.shadows.push(stubFile); } if (!stubFile.shadowedBy.includes(shadowFileInfo)) { stubFile.shadowedBy.push(shadowFileInfo); } return shadowFileInfo.sourceFile; } private _createNewEvaluator() { if (this._evaluator) { // We shouldn't need to call this, but there appears to be a bug // in the v8 garbage collector where it's unable to resolve orphaned // objects without us giving it some assistance. this._evaluator.disposeEvaluator(); } this._evaluator = createTypeEvaluatorWithTracker( this._lookUpImport, { printTypeFlags: Program._getPrintTypeFlags(this._configOptions), logCalls: this._configOptions.logTypeEvaluationTime, minimumLoggingThreshold: this._configOptions.typeEvaluationTimeThreshold, analyzeUnannotatedFunctions: this._configOptions.analyzeUnannotatedFunctions, evaluateUnknownImportsAsAny: !!this._configOptions.evaluateUnknownImportsAsAny, verifyTypeCacheEvaluatorFlags: !!this._configOptions.internalTestMode, }, this._logTracker, this._configOptions.logTypeEvaluationTime ? createTracePrinter( this._importResolver.getImportRoots( this._configOptions.findExecEnvironment(this._configOptions.projectRoot) ) ) : undefined ); return this._evaluator; } private _parseFile(fileToParse: SourceFileInfo, content?: string) { if (!this._isFileNeeded(fileToParse) || !fileToParse.sourceFile.isParseRequired()) { return; } if (fileToParse.sourceFile.parse(this._configOptions, this._importResolver, content)) { this._parsedFileCount++; this._updateSourceFileImports(fileToParse, this._configOptions); } if (fileToParse.sourceFile.isFileDeleted()) { fileToParse.isTracked = false; // Mark any files that depend on this file as dirty // also. This will retrigger analysis of these other files. const markDirtyMap = new Map<string, boolean>(); this._markFileDirtyRecursive(fileToParse, markDirtyMap); // Invalidate the import resolver's cache as well. this._importResolver.invalidateCache(); } } // Binds the specified file and all of its dependencies, recursively. If // it runs out of time, it returns true. If it completes, it returns false. private _bindFile(fileToAnalyze: SourceFileInfo, content?: string): void { if (!this._isFileNeeded(fileToAnalyze) || !fileToAnalyze.sourceFile.isBindingRequired()) { return; } this._parseFile(fileToAnalyze, content); const getScopeIfAvailable = (fileInfo: SourceFileInfo | undefined) => { if (!fileInfo || fileInfo === fileToAnalyze) { return undefined; } this._bindFile(fileInfo); if (fileInfo.sourceFile.isFileDeleted()) { return undefined; } const parseResults = fileInfo.sourceFile.getParseResults(); if (!parseResults) { return undefined; } const scope = AnalyzerNodeInfo.getScope(parseResults.parseTree); assert(scope !== undefined); return scope; }; let builtinsScope: Scope | undefined; if (fileToAnalyze.builtinsImport && fileToAnalyze.builtinsImport !== fileToAnalyze) { // If it is not builtin module itself, we need to parse and bind // the ipython display import if required. Otherwise, get builtin module. builtinsScope = getScopeIfAvailable(fileToAnalyze.chainedSourceFile) ?? getScopeIfAvailable(fileToAnalyze.ipythonDisplayImport) ?? getScopeIfAvailable(fileToAnalyze.builtinsImport); } fileToAnalyze.sourceFile.bind(this._configOptions, this._lookUpImport, builtinsScope); } private _lookUpImport = (filePathOrModule: string | AbsoluteModuleDescriptor): ImportLookupResult | undefined => { let sourceFileInfo: SourceFileInfo | undefined; if (typeof filePathOrModule === 'string') { sourceFileInfo = this._getSourceFileInfoFromPath(filePathOrModule); } else { // Resolve the import. const importResult = this._importResolver.resolveImport( filePathOrModule.importingFilePath, this._configOptions.findExecEnvironment(filePathOrModule.importingFilePath), { leadingDots: 0, nameParts: filePathOrModule.nameParts, importedSymbols: undefined, } ); if (importResult.isImportFound && !importResult.isNativeLib && importResult.resolvedPaths.length > 0) { let resolvedPath = importResult.resolvedPaths[importResult.resolvedPaths.length - 1]; if (resolvedPath) { // See if the source file already exists in the program. sourceFileInfo = this._getSourceFileInfoFromPath(resolvedPath); if (!sourceFileInfo) { resolvedPath = normalizePathCase(this._fs, resolvedPath); // Start tracking the source file. this.addTrackedFile(resolvedPath); sourceFileInfo = this._getSourceFileInfoFromPath(resolvedPath); } } } } if (!sourceFileInfo) { return undefined; } if (sourceFileInfo.sourceFile.isBindingRequired()) { // Bind the file if it's not already bound. Don't count this time // against the type checker. timingStats.typeCheckerTime.subtractFromTime(() => { this._bindFile(sourceFileInfo!); }); } const symbolTable = sourceFileInfo.sourceFile.getModuleSymbolTable(); if (!symbolTable) { return undefined; } const parseResults = sourceFileInfo.sourceFile.getParseResults(); const moduleNode = parseResults!.parseTree; const dunderAllInfo = AnalyzerNodeInfo.getDunderAllInfo(parseResults!.parseTree); return { symbolTable, dunderAllNames: dunderAllInfo?.names, usesUnsupportedDunderAllForm: dunderAllInfo?.usesUnsupportedDunderAllForm ?? false, get docString() { return getDocString(moduleNode.statements); }, }; }; // Build a map of all modules within this program and the module- // level scope that contains the symbol table for the module. private _buildModuleSymbolsMap( sourceFileToExclude: SourceFileInfo, userFileOnly: boolean, includeIndexUserSymbols: boolean, token: CancellationToken ): ModuleSymbolMap { // If we have library map, always use the map for library symbols. return buildModuleSymbolsMap( this._sourceFileList.filter( (s) => s !== sourceFileToExclude && (userFileOnly ? this._isUserCode(s) : true) ), includeIndexUserSymbols, token ); } private _shouldCheckFile(fileInfo: SourceFileInfo) { // Always do a full checking for a file that's open in the editor. if (fileInfo.isOpenByClient) { return true; } // If the file isn't currently open, only perform full checking for // files that are tracked, and only if the checkOnlyOpenFiles is disabled. if (!this._configOptions.checkOnlyOpenFiles && fileInfo.isTracked) { return true; } return false; } private _checkTypes(fileToCheck: SourceFileInfo) { return this._logTracker.log(`analyzing: ${fileToCheck.sourceFile.getFilePath()}`, (logState) => { // If the file isn't needed because it was eliminated from the // transitive closure or deleted, skip the file rather than wasting // time on it. if (!this._isFileNeeded(fileToCheck)) { logState.suppress(); return false; } if (!fileToCheck.sourceFile.isCheckingRequired()) { logState.suppress(); return false; } if (!this._shouldCheckFile(fileToCheck)) { logState.suppress(); return false; } this._bindFile(fileToCheck); if (this._preCheckCallback) { const parseResults = fileToCheck.sourceFile.getParseResults(); if (parseResults) { this._preCheckCallback(parseResults, this._evaluator!); } } if (!this._disableChecker) { fileToCheck.sourceFile.check(this._importResolver, this._evaluator!); } // For very large programs, we may need to discard the evaluator and // its cached types to avoid running out of heap space. this._handleMemoryHighUsage(); // Detect import cycles that involve the file. if (this._configOptions.diagnosticRuleSet.reportImportCycles !== 'none') { // Don't detect import cycles when doing type stub generation. Some // third-party modules are pretty convoluted. if (!this._allowedThirdPartyImports) { // We need to force all of the files to be parsed and build // a closure map for the files. const closureMap = new Map<string, SourceFileInfo>(); this._getImportsRecursive(fileToCheck, closureMap, 0); closureMap.forEach((file) => { timingStats.cycleDetectionTime.timeOperation(() => { const filesVisitedMap = new Map<string, SourceFileInfo>(); if (!this._detectAndReportImportCycles(file, filesVisitedMap)) { // If no cycles were reported, set a flag in all of the visited files // so we don't need to visit them again on subsequent cycle checks. filesVisitedMap.forEach((sourceFileInfo) => { sourceFileInfo.sourceFile.setNoCircularDependencyConfirmed(); }); } }); }); } } return true; }); } // Builds a map of files that includes the specified file and all of the files // it imports (recursively) and ensures that all such files. If any of these files // have already been checked (they and their recursive imports have completed the // check phase), they are not included in the results. private _getImportsRecursive( file: SourceFileInfo, closureMap: Map<string, SourceFileInfo>, recursionCount: number ) { // If the file is already in the closure map, we found a cyclical // dependency. Don't recur further. const filePath = normalizePathCase(this._fs, file.sourceFile.getFilePath()); if (closureMap.has(filePath)) { return; } // If the import chain is too long, emit an error. Otherwise we // risk blowing the stack. if (recursionCount > _maxImportDepth) { file.sourceFile.setHitMaxImportDepth(_maxImportDepth); return; } // Add the file to the closure map. closureMap.set(filePath, file); // Recursively add the file's imports. for (const importedFileInfo of file.imports) { this._getImportsRecursive(importedFileInfo, closureMap, recursionCount + 1); } } private _detectAndReportImportCycles( sourceFileInfo: SourceFileInfo, filesVisited: Map<string, SourceFileInfo>, dependencyChain: SourceFileInfo[] = [], dependencyMap = new Map<string, boolean>() ): boolean { // Don't bother checking for typestub files or third-party files. if (sourceFileInfo.sourceFile.isStubFile() || sourceFileInfo.isThirdPartyImport) { return false; } // If we've already confirmed that this source file isn't part of a // cycle, we can skip it entirely. if (sourceFileInfo.sourceFile.isNoCircularDependencyConfirmed()) { return false; } filesVisited.set(sourceFileInfo.sourceFile.getFilePath(), sourceFileInfo); let detectedCycle = false; const filePath = normalizePathCase(this._fs, sourceFileInfo.sourceFile.getFilePath()); if (dependencyMap.has(filePath)) { // Look for chains at least two in length. A file that contains // an "import . from X" will technically create a cycle with // itself, but those are not interesting to report. if (dependencyChain.length > 1 && sourceFileInfo === dependencyChain[0]) { this._logImportCycle(dependencyChain); detectedCycle = true; } } else { // If we've already checked this dependency along // some other path, we can skip it. if (dependencyMap.has(filePath)) { return false; } // We use both a map (for fast lookups) and a list // (for ordering information). Set the dependency map // entry to true to indicate that we're actively exploring // that dependency. dependencyMap.set(filePath, true); dependencyChain.push(sourceFileInfo); for (const imp of sourceFileInfo.imports) { if (this._detectAndReportImportCycles(imp, filesVisited, dependencyChain, dependencyMap)) { detectedCycle = true; } } // Set the dependencyMap entry to false to indicate that we have // already explored this file and don't need to explore it again. dependencyMap.set(filePath, false); dependencyChain.pop(); } return detectedCycle; } private _logImportCycle(dependencyChain: SourceFileInfo[]) { const circDep = new CircularDependency(); dependencyChain.forEach((sourceFileInfo) => { circDep.appendPath(sourceFileInfo.sourceFile.getFilePath()); }); circDep.normalizeOrder(); const firstFilePath = circDep.getPaths()[0]; const firstSourceFile = this._getSourceFileInfoFromPath(firstFilePath)!; assert(firstSourceFile !== undefined); firstSourceFile.sourceFile.addCircularDependency(circDep); } private _markFileDirtyRecursive( sourceFileInfo: SourceFileInfo, markMap: Map<string, boolean>, forceRebinding = false ) { const filePath = normalizePathCase(this._fs, sourceFileInfo.sourceFile.getFilePath()); // Don't mark it again if it's already been visited. if (!markMap.has(filePath)) { sourceFileInfo.sourceFile.markReanalysisRequired(forceRebinding); markMap.set(filePath, true); sourceFileInfo.importedBy.forEach((dep) => { // Changes on chained source file can change symbols in the symbol table and // dependencies on the dependent file. Force rebinding. const forceRebinding = dep.chainedSourceFile === sourceFileInfo; this._markFileDirtyRecursive(dep, markMap, forceRebinding); }); } } getTextOnRange(filePath: string, range: Range, token: CancellationToken): string | undefined { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { return undefined; } const sourceFile = sourceFileInfo.sourceFile; const fileContents = sourceFile.getOpenFileContents(); if (fileContents === undefined) { // this only works with opened file return undefined; } return this._runEvaluatorWithCancellationToken(token, () => { this._parseFile(sourceFileInfo); const parseTree = sourceFile.getParseResults()!; const textRange = convertRangeToTextRange(range, parseTree.tokenizerOutput.lines); if (!textRange) { return undefined; } return fileContents.substr(textRange.start, textRange.length); }); } getAutoImports( filePath: string, range: Range, similarityLimit: number, nameMap: AbbreviationMap | undefined, libraryMap: Map<string, IndexResults> | undefined, lazyEdit: boolean, allowVariableInAll: boolean, token: CancellationToken ): AutoImportResult[] { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { return []; } const sourceFile = sourceFileInfo.sourceFile; const fileContents = sourceFile.getOpenFileContents(); if (fileContents === undefined) { // this only works with opened file return []; } return this._runEvaluatorWithCancellationToken(token, () => { this._bindFile(sourceFileInfo); const parseTree = sourceFile.getParseResults()!; const textRange = convertRangeToTextRange(range, parseTree.tokenizerOutput.lines); if (!textRange) { return []; } const currentNode = findNodeByOffset(parseTree.parseTree, textRange.start); if (!currentNode) { return []; } const writtenWord = fileContents.substr(textRange.start, textRange.length); const map = this._buildModuleSymbolsMap( sourceFileInfo, !!libraryMap, /* includeIndexUserSymbols */ true, token ); const autoImporter = new AutoImporter( this._configOptions.findExecEnvironment(filePath), this._importResolver, parseTree, range.start, new CompletionMap(), map, { lazyEdit, allowVariableInAll, libraryMap, patternMatcher: (p, t) => computeCompletionSimilarity(p, t) > similarityLimit, } ); // Filter out any name that is already defined in the current scope. const results: AutoImportResult[] = []; const currentScope = getScopeForNode(currentNode); if (currentScope) { const info = nameMap?.get(writtenWord); if (info) { // No scope filter is needed since we only do exact match. appendArray(results, autoImporter.getAutoImportCandidatesForAbbr(writtenWord, info, token)); } results.push( ...autoImporter .getAutoImportCandidates(writtenWord, similarityLimit, /* abbrFromUsers */ undefined, token) .filter((r) => !currentScope.lookUpSymbolRecursive(r.name)) ); } return results; }); } getDiagnostics(options: ConfigOptions): FileDiagnostics[] { const fileDiagnostics: FileDiagnostics[] = this._removeUnneededFiles(); this._sourceFileList.forEach((sourceFileInfo) => { if (this._shouldCheckFile(sourceFileInfo)) { const diagnostics = sourceFileInfo.sourceFile.getDiagnostics( options, sourceFileInfo.diagnosticsVersion ); if (diagnostics !== undefined) { fileDiagnostics.push({ filePath: sourceFileInfo.sourceFile.getFilePath(), version: sourceFileInfo.sourceFile.getClientVersion(), diagnostics, }); // Update the cached diagnosticsVersion so we can determine // whether there are any updates next time we call getDiagnostics. sourceFileInfo.diagnosticsVersion = sourceFileInfo.sourceFile.getDiagnosticVersion(); } } else if ( !sourceFileInfo.isOpenByClient && options.checkOnlyOpenFiles && sourceFileInfo.diagnosticsVersion !== undefined ) { // This condition occurs when the user switches from workspace to // "open files only" mode. Clear all diagnostics for this file. fileDiagnostics.push({ filePath: sourceFileInfo.sourceFile.getFilePath(), version: sourceFileInfo.sourceFile.getClientVersion(), diagnostics: [], }); sourceFileInfo.diagnosticsVersion = undefined; } }); return fileDiagnostics; } getDiagnosticsForRange(filePath: string, range: Range): Diagnostic[] { const sourceFile = this.getSourceFile(filePath); if (!sourceFile) { return []; } const unfilteredDiagnostics = sourceFile.getDiagnostics(this._configOptions); if (!unfilteredDiagnostics) { return []; } return unfilteredDiagnostics.filter((diag) => { return doRangesIntersect(diag.range, range); }); } getDefinitionsForPosition( filePath: string, position: Position, filter: DefinitionFilter, token: CancellationToken ): DocumentRange[] | undefined { return this._runEvaluatorWithCancellationToken(token, () => { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { return undefined; } this._bindFile(sourceFileInfo); const execEnv = this._configOptions.findExecEnvironment(filePath); return sourceFileInfo.sourceFile.getDefinitionsForPosition( this._createSourceMapper(execEnv), position, filter, this._evaluator!, token ); }); } getTypeDefinitionsForPosition( filePath: string, position: Position, token: CancellationToken ): DocumentRange[] | undefined { return this._runEvaluatorWithCancellationToken(token, () => { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { return undefined; } this._bindFile(sourceFileInfo); const execEnv = this._configOptions.findExecEnvironment(filePath); return sourceFileInfo.sourceFile.getTypeDefinitionsForPosition( this._createSourceMapper(execEnv, /* mapCompiled */ false, /* preferStubs */ true), position, this._evaluator!, filePath, token ); }); } reportReferencesForPosition( filePath: string, position: Position, includeDeclaration: boolean, reporter: ReferenceCallback, token: CancellationToken ) { this._runEvaluatorWithCancellationToken(token, () => { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { return; } const invokedFromUserFile = this._isUserCode(sourceFileInfo); this._bindFile(sourceFileInfo); const execEnv = this._configOptions.findExecEnvironment(filePath); const referencesResult = sourceFileInfo.sourceFile.getDeclarationForPosition( this._createSourceMapper(execEnv), position, this._evaluator!, reporter, token ); if (!referencesResult) { return; } // Do we need to do a global search as well? if (referencesResult.requiresGlobalSearch) { for (const curSourceFileInfo of this._sourceFileList) { throwIfCancellationRequested(token); // "Find all references" will only include references from user code // unless the file is explicitly opened in the editor or it is invoked from non user files. if ( curSourceFileInfo.isOpenByClient || !invokedFromUserFile || this._isUserCode(curSourceFileInfo) ) { // See if the reference symbol's string is located somewhere within the file. // If not, we can skip additional processing for the file. const fileContents = curSourceFileInfo.sourceFile.getFileContent(); if (!fileContents || fileContents.search(referencesResult.symbolName) >= 0) { this._bindFile(curSourceFileInfo); curSourceFileInfo.sourceFile.addReferences( referencesResult, includeDeclaration, this._evaluator!, token ); } // This operation can consume significant memory, so check // for situations where we need to discard the type cache. this._handleMemoryHighUsage(); } } // Make sure to include declarations regardless where they are defined // if includeDeclaration is set. if (includeDeclaration) { for (const decl of referencesResult.declarations) { throwIfCancellationRequested(token); if (referencesResult.locations.some((l) => l.path === decl.path)) { // Already included. continue; } const declFileInfo = this._getSourceFileInfoFromPath(decl.path); if (!declFileInfo) { // The file the declaration belongs to doesn't belong to the program. continue; } const tempResult = new ReferencesResult( referencesResult.requiresGlobalSearch, referencesResult.nodeAtOffset, referencesResult.symbolName, referencesResult.declarations ); declFileInfo.sourceFile.addReferences(tempResult, includeDeclaration, this._evaluator!, token); for (const loc of tempResult.locations) { // Include declarations only. And throw away any references if (loc.path === decl.path && doesRangeContain(decl.range, loc.range)) { referencesResult.addLocations(loc); } } } } } else { sourceFileInfo.sourceFile.addReferences(referencesResult, includeDeclaration, this._evaluator!, token); } }); } getFileIndex(filePath: string, options: IndexOptions, token: CancellationToken): IndexResults | undefined { if (options.indexingForAutoImportMode) { // Memory optimization. We only want to hold onto symbols // usable outside when importSymbolsOnly is on. const name = stripFileExtension(getFileName(filePath)); if (isPrivateOrProtectedName(name)) { return undefined; } } this._handleMemoryHighUsage(); return this._runEvaluatorWithCancellationToken(token, () => { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { return undefined; } const content = sourceFileInfo.sourceFile.getFileContent() ?? ''; if ( options.indexingForAutoImportMode && !options.forceIndexing && !sourceFileInfo.sourceFile.isStubFile() && !sourceFileInfo.sourceFile.isThirdPartyPyTypedPresent() ) { // Perf optimization. if py file doesn't contain __all__ // No need to parse and bind. if (content.indexOf('__all__') < 0) { return undefined; } } this._bindFile(sourceFileInfo, content); return sourceFileInfo.sourceFile.index(options, token); }); } addSymbolsForDocument(filePath: string, symbolList: DocumentSymbol[], token: CancellationToken) { return this._runEvaluatorWithCancellationToken(token, () => { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (sourceFileInfo) { if (!sourceFileInfo.sourceFile.getCachedIndexResults()) { // If we already have cached index for this file, no need to bind this file. this._bindFile(sourceFileInfo); } sourceFileInfo.sourceFile.addHierarchicalSymbolsForDocument(symbolList, token); } }); } reportSymbolsForWorkspace(query: string, reporter: WorkspaceSymbolCallback, token: CancellationToken) { this._runEvaluatorWithCancellationToken(token, () => { // Don't do a search if the query is empty. We'll return // too many results in this case. if (!query) { return; } // "Workspace symbols" searches symbols only from user code. for (const sourceFileInfo of this._sourceFileList) { if (!this._isUserCode(sourceFileInfo)) { continue; } if (!sourceFileInfo.sourceFile.getCachedIndexResults()) { // If we already have cached index for this file, no need to bind this file. this._bindFile(sourceFileInfo); } const symbolList = sourceFileInfo.sourceFile.getSymbolsForDocument(query, token); if (symbolList.length > 0) { reporter(symbolList); } // This operation can consume significant memory, so check // for situations where we need to discard the type cache. this._handleMemoryHighUsage(); } }); } getHoverForPosition( filePath: string, position: Position, format: MarkupKind, token: CancellationToken ): HoverResults | undefined { return this._runEvaluatorWithCancellationToken(token, () => { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { return undefined; } this._bindFile(sourceFileInfo); const execEnv = this._configOptions.findExecEnvironment(filePath); return sourceFileInfo.sourceFile.getHoverForPosition( this._createSourceMapper(execEnv, /* mapCompiled */ true), position, format, this._evaluator!, token ); }); } getDocumentHighlight( filePath: string, position: Position, token: CancellationToken ): DocumentHighlight[] | undefined { return this._runEvaluatorWithCancellationToken(token, () => { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { return undefined; } this._bindFile(sourceFileInfo); const execEnv = this._configOptions.findExecEnvironment(filePath); return sourceFileInfo.sourceFile.getDocumentHighlight( this._createSourceMapper(execEnv), position, this._evaluator!, token ); }); } getSignatureHelpForPosition( filePath: string, position: Position, format: MarkupKind, token: CancellationToken ): SignatureHelpResults | undefined { return this._runEvaluatorWithCancellationToken(token, () => { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { return undefined; } this._bindFile(sourceFileInfo); const execEnv = this._configOptions.findExecEnvironment(filePath); return sourceFileInfo.sourceFile.getSignatureHelpForPosition( position, this._createSourceMapper(execEnv, /* mapCompiled */ true), this._evaluator!, format, token ); }); } async getCompletionsForPosition( filePath: string, position: Position, workspacePath: string, options: CompletionOptions, nameMap: AbbreviationMap | undefined, libraryMap: Map<string, IndexResults> | undefined, token: CancellationToken ): Promise<CompletionResultsList | undefined> { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { return undefined; } const completionResult = this._logTracker.log( `completion at ${filePath}:${position.line}:${position.character}`, (ls) => { const result = this._runEvaluatorWithCancellationToken(token, () => { this._bindFile(sourceFileInfo); const execEnv = this._configOptions.findExecEnvironment(filePath); return sourceFileInfo.sourceFile.getCompletionsForPosition( position, workspacePath, this._configOptions, this._importResolver, this._lookUpImport, this._evaluator!, options, this._createSourceMapper(execEnv, /* mapCompiled */ true), nameMap, libraryMap, () => this._buildModuleSymbolsMap( sourceFileInfo, !!libraryMap, /* includeIndexUserSymbols */ false, token ), token ); }); ls.add(`found ${result?.completionMap?.size ?? 'null'} items`); return result; } ); const completionResultsList: CompletionResultsList = { completionList: CompletionList.create(completionResult?.completionMap?.toArray()), memberAccessInfo: completionResult?.memberAccessInfo, autoImportInfo: completionResult?.autoImportInfo, extensionInfo: completionResult?.extensionInfo, }; if (!completionResult?.completionMap || !this._extension?.completionListExtension) { return completionResultsList; } const parseResults = sourceFileInfo.sourceFile.getParseResults(); if (parseResults?.parseTree && parseResults?.text) { const offset = convertPositionToOffset(position, parseResults.tokenizerOutput.lines); if (offset !== undefined) { await this._extension.completionListExtension.updateCompletionResults( completionResultsList, parseResults, offset, token ); } } return completionResultsList; } resolveCompletionItem( filePath: string, completionItem: CompletionItem, options: CompletionOptions, nameMap: AbbreviationMap | undefined, libraryMap: Map<string, IndexResults> | undefined, token: CancellationToken ) { return this._runEvaluatorWithCancellationToken(token, () => { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { return; } this._bindFile(sourceFileInfo); const execEnv = this._configOptions.findExecEnvironment(filePath); sourceFileInfo.sourceFile.resolveCompletionItem( this._configOptions, this._importResolver, this._lookUpImport, this._evaluator!, options, this._createSourceMapper(execEnv, /* mapCompiled */ true), nameMap, libraryMap, () => this._buildModuleSymbolsMap( sourceFileInfo, !!libraryMap, /* includeIndexUserSymbols */ false, token ), completionItem, token ); }); } renameModule(path: string, newPath: string, token: CancellationToken): FileEditActions | undefined { return this._runEvaluatorWithCancellationToken(token, () => { if (isFile(this._fs, path)) { const fileInfo = this._getSourceFileInfoFromPath(path); if (!fileInfo) { return undefined; } } const renameModuleProvider = RenameModuleProvider.createForModule( this._importResolver, this._configOptions, this._evaluator!, path, newPath, token ); if (!renameModuleProvider) { return undefined; } this._processModuleReferences(renameModuleProvider, renameModuleProvider.lastModuleName, path); return { edits: renameModuleProvider.getEdits(), fileOperations: [] }; }); } moveSymbolAtPosition( filePath: string, newFilePath: string, position: Position, token: CancellationToken ): FileEditActions | undefined { return this._runEvaluatorWithCancellationToken(token, () => { const fileInfo = this._getSourceFileInfoFromPath(filePath); if (!fileInfo) { return undefined; } this._bindFile(fileInfo); const parseResults = fileInfo.sourceFile.getParseResults(); if (!parseResults) { return undefined; } const offset = convertPositionToOffset(position, parseResults.tokenizerOutput.lines); if (offset === undefined) { return undefined; } const node = findNodeByOffset(parseResults.parseTree, offset); if (node === undefined) { return undefined; } // If this isn't a name node, there are no references to be found. if (node.nodeType !== ParseNodeType.Name) { return undefined; } const execEnv = this._configOptions.findExecEnvironment(filePath); const declarations = DocumentSymbolCollector.getDeclarationsForNode( node, this._evaluator!, /* resolveLocalNames */ false, token, this._createSourceMapper(execEnv) ); const renameModuleProvider = RenameModuleProvider.createForSymbol( this._importResolver, this._configOptions, this._evaluator!, filePath, newFilePath, declarations, token ); if (!renameModuleProvider) { return undefined; } this._processModuleReferences(renameModuleProvider, node.value, filePath); return { edits: renameModuleProvider.getEdits(), fileOperations: [] }; }); } canRenameSymbolAtPosition( filePath: string, position: Position, isDefaultWorkspace: boolean, allowModuleRename: boolean, token: CancellationToken ): Range | undefined { return this._runEvaluatorWithCancellationToken(token, () => { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { return undefined; } this._bindFile(sourceFileInfo); const referencesResult = this._getReferenceResult( sourceFileInfo, filePath, position, allowModuleRename, token ); if (!referencesResult) { return undefined; } if ( referencesResult.containsOnlyImportDecls && !this._supportRenameModule(referencesResult.declarations, isDefaultWorkspace) ) { return undefined; } const renameMode = this._getRenameSymbolMode(sourceFileInfo, referencesResult, isDefaultWorkspace); if (renameMode === 'none') { return undefined; } // Return the range of the symbol. const parseResult = sourceFileInfo.sourceFile.getParseResults()!; return convertTextRangeToRange(referencesResult.nodeAtOffset, parseResult.tokenizerOutput.lines); }); } renameSymbolAtPosition( filePath: string, position: Position, newName: string, isDefaultWorkspace: boolean, allowModuleRename: boolean, token: CancellationToken ): FileEditActions | undefined { return this._runEvaluatorWithCancellationToken(token, () => { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { return undefined; } this._bindFile(sourceFileInfo); const referencesResult = this._getReferenceResult( sourceFileInfo, filePath, position, allowModuleRename, token ); if (!referencesResult) { return undefined; } if (referencesResult.containsOnlyImportDecls) { // All decls must be on a user file. if (!this._supportRenameModule(referencesResult.declarations, isDefaultWorkspace)) { return undefined; } const moduleInfo = RenameModuleProvider.getRenameModulePathInfo( RenameModuleProvider.getRenameModulePath(referencesResult.declarations), newName ); if (!moduleInfo) { // Can't figure out module to rename. return undefined; } const editActions = this.renameModule(moduleInfo.filePath, moduleInfo.newFilePath, token); // Add file system rename. editActions?.fileOperations.push({ kind: 'rename', oldFilePath: moduleInfo.filePath, newFilePath: moduleInfo.newFilePath, }); if (isStubFile(moduleInfo.filePath)) { const matchingFiles = this._importResolver.getSourceFilesFromStub( moduleInfo.filePath, this._configOptions.findExecEnvironment(filePath), /* mapCompiled */ false ); for (const matchingFile of matchingFiles) { const matchingFileInfo = RenameModuleProvider.getRenameModulePathInfo(matchingFile, newName); if (matchingFileInfo) { editActions?.fileOperations.push({ kind: 'rename', oldFilePath: matchingFileInfo.filePath, newFilePath: matchingFileInfo.newFilePath, }); } } } return editActions; } const renameMode = this._getRenameSymbolMode(sourceFileInfo, referencesResult, isDefaultWorkspace); switch (renameMode) { case 'singleFileMode': sourceFileInfo.sourceFile.addReferences(referencesResult, true, this._evaluator!, token); break; case 'multiFileMode': { for (const curSourceFileInfo of this._sourceFileList) { // Make sure we only add user code to the references to prevent us // from accidentally changing third party library or type stub. if (this._isUserCode(curSourceFileInfo)) { // Make sure searching symbol name exists in the file. const content = curSourceFileInfo.sourceFile.getFileContent() ?? ''; if (content.indexOf(referencesResult.symbolName) < 0) { continue; } this._bindFile(curSourceFileInfo, content); curSourceFileInfo.sourceFile.addReferences(referencesResult, true, this._evaluator!, token); } // This operation can consume significant memory, so check // for situations where we need to discard the type cache. this._handleMemoryHighUsage(); } break; } case 'none': // Rename is not allowed. // ex) rename symbols from libraries. return undefined; default: assertNever(renameMode); } const edits: FileEditAction[] = []; referencesResult.locations.forEach((loc) => { edits.push({ filePath: loc.path, range: loc.range, replacementText: newName, }); }); return { edits, fileOperations: [] }; }); } getCallForPosition(filePath: string, position: Position, token: CancellationToken): CallHierarchyItem | undefined { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { return undefined; } this._bindFile(sourceFileInfo); const execEnv = this._configOptions.findExecEnvironment(filePath); const referencesResult = sourceFileInfo.sourceFile.getDeclarationForPosition( this._createSourceMapper(execEnv), position, this._evaluator!, undefined, token ); if (!referencesResult || referencesResult.declarations.length === 0) { return undefined; } const targetDecl = CallHierarchyProvider.getTargetDeclaration( referencesResult.declarations, referencesResult.nodeAtOffset ); return CallHierarchyProvider.getCallForDeclaration( referencesResult.symbolName, targetDecl, this._evaluator!, token ); } getIncomingCallsForPosition( filePath: string, position: Position, token: CancellationToken ): CallHierarchyIncomingCall[] | undefined { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { return undefined; } this._bindFile(sourceFileInfo); const execEnv = this._configOptions.findExecEnvironment(filePath); const referencesResult = sourceFileInfo.sourceFile.getDeclarationForPosition( this._createSourceMapper(execEnv), position, this._evaluator!, undefined, token ); if (!referencesResult || referencesResult.declarations.length === 0) { return undefined; } const targetDecl = CallHierarchyProvider.getTargetDeclaration( referencesResult.declarations, referencesResult.nodeAtOffset ); let items: CallHierarchyIncomingCall[] = []; for (const curSourceFileInfo of this._sourceFileList) { if (this._isUserCode(curSourceFileInfo) || curSourceFileInfo.isOpenByClient) { this._bindFile(curSourceFileInfo); const itemsToAdd = CallHierarchyProvider.getIncomingCallsForDeclaration( curSourceFileInfo.sourceFile.getFilePath(), referencesResult.symbolName, targetDecl, curSourceFileInfo.sourceFile.getParseResults()!, this._evaluator!, token ); if (itemsToAdd) { items = items.concat(...itemsToAdd); } // This operation can consume significant memory, so check // for situations where we need to discard the type cache. this._handleMemoryHighUsage(); } } return items; } getOutgoingCallsForPosition( filePath: string, position: Position, token: CancellationToken ): CallHierarchyOutgoingCall[] | undefined { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { return undefined; } this._bindFile(sourceFileInfo); const execEnv = this._configOptions.findExecEnvironment(filePath); const referencesResult = sourceFileInfo.sourceFile.getDeclarationForPosition( this._createSourceMapper(execEnv), position, this._evaluator!, undefined, token ); if (!referencesResult || referencesResult.declarations.length === 0) { return undefined; } const targetDecl = CallHierarchyProvider.getTargetDeclaration( referencesResult.declarations, referencesResult.nodeAtOffset ); return CallHierarchyProvider.getOutgoingCallsForDeclaration( targetDecl, sourceFileInfo.sourceFile.getParseResults()!, this._evaluator!, token ); } performQuickAction( filePath: string, command: string, args: any[], token: CancellationToken ): TextEditAction[] | undefined { const sourceFileInfo = this._getSourceFileInfoFromPath(filePath); if (!sourceFileInfo) { return undefined; } this._bindFile(sourceFileInfo); return sourceFileInfo.sourceFile.performQuickAction(command, args, token); } test_createSourceMapper(execEnv: ExecutionEnvironment) { return this._createSourceMapper(execEnv, /* mapCompiled */ false); } private _getRenameSymbolMode( sourceFileInfo: SourceFileInfo, referencesResult: ReferencesResult, isDefaultWorkspace: boolean ) { // We have 2 different cases // Single file mode. // 1. rename on default workspace (ex, standalone file mode). // 2. rename local symbols. // 3. rename symbols defined in the non user open file. // // and Multi file mode. // 1. rename public symbols defined in user files on regular workspace (ex, open folder mode). const userFile = this._isUserCode(sourceFileInfo); if ( isDefaultWorkspace || (userFile && !referencesResult.requiresGlobalSearch) || (!userFile && sourceFileInfo.isOpenByClient && referencesResult.declarations.every((d) => this._getSourceFileInfoFromPath(d.path) === sourceFileInfo)) ) { return 'singleFileMode'; } if (referencesResult.declarations.every((d) => this._isUserCode(this._getSourceFileInfoFromPath(d.path)))) { return 'multiFileMode'; } // Rename is not allowed. // ex) rename symbols from libraries. return 'none'; } private _supportRenameModule(declarations: Declaration[], isDefaultWorkspace: boolean) { // Rename module is not supported for standalone file and all decls must be on a user file. return ( !isDefaultWorkspace && declarations.every((d) => this._isUserCode(this._getSourceFileInfoFromPath(d.path))) ); } private _getReferenceResult( sourceFileInfo: SourceFileInfo, filePath: string, position: Position, allowModuleRename: boolean, token: CancellationToken ) { const execEnv = this._configOptions.findExecEnvironment(filePath); const referencesResult = sourceFileInfo.sourceFile.getDeclarationForPosition( this._createSourceMapper(execEnv), position, this._evaluator!, undefined, token ); if (!referencesResult) { return undefined; } if (allowModuleRename && referencesResult.containsOnlyImportDecls) { return referencesResult; } if (referencesResult.nonImportDeclarations.length === 0) { // There is no symbol we can rename. return undefined; } // Use declarations that doesn't contain import decls. return new ReferencesResult( referencesResult.requiresGlobalSearch, referencesResult.nodeAtOffset, referencesResult.symbolName, referencesResult.nonImportDeclarations ); } private _processModuleReferences( renameModuleProvider: RenameModuleProvider, filteringText: string, currentFilePath: string ) { // _sourceFileList contains every user files that match "include" pattern including // py file even if corresponding pyi exists. for (const currentFileInfo of this._sourceFileList) { // Make sure we only touch user code to prevent us // from accidentally changing third party library or type stub. if (!this._isUserCode(currentFileInfo)) { continue; } // If module name isn't mentioned in the current file, skip the file // except the file that got actually renamed/moved. // The file that got moved might have relative import paths we need to update. const filePath = currentFileInfo.sourceFile.getFilePath(); const content = currentFileInfo.sourceFile.getFileContent() ?? ''; if (filePath !== currentFilePath && content.indexOf(filteringText) < 0) { continue; } this._bindFile(currentFileInfo, content); const parseResult = currentFileInfo.sourceFile.getParseResults(); if (!parseResult) { continue; } renameModuleProvider.renameReferences(filePath, parseResult); // This operation can consume significant memory, so check // for situations where we need to discard the type cache. this._handleMemoryHighUsage(); } } private _handleMemoryHighUsage() { const typeCacheEntryCount = this._evaluator!.getTypeCacheEntryCount(); const convertToMB = (bytes: number) => { return `${Math.round(bytes / (1024 * 1024))}MB`; }; // If the type cache size has exceeded a high-water mark, query the heap usage. // Don't bother doing this until we hit this point because the heap usage may not // drop immediately after we empty the cache due to garbage collection timing. if (typeCacheEntryCount > 750000 || this._parsedFileCount > 1000) { const heapStats = getHeapStatistics(); if (this._configOptions.verboseOutput) { this._console.info( `Heap stats: ` + `total_heap_size=${convertToMB(heapStats.total_heap_size)}, ` + `used_heap_size=${convertToMB(heapStats.used_heap_size)}, ` + `total_physical_size=${convertToMB(heapStats.total_physical_size)}, ` + `total_available_size=${convertToMB(heapStats.total_available_size)}, ` + `heap_size_limit=${convertToMB(heapStats.heap_size_limit)}` ); } // The type cache uses a Map, which has an absolute limit of 2^24 entries // before it will fail. If we cross the 95% mark, we'll empty the cache. const absoluteMaxCacheEntryCount = (1 << 24) * 0.9; // If we use more than 90% of the heap size limit, avoid a crash // by emptying the type cache. if ( typeCacheEntryCount > absoluteMaxCacheEntryCount || heapStats.used_heap_size > heapStats.heap_size_limit * 0.9 ) { this._console.info( `Emptying type cache to avoid heap overflow. Used ${convertToMB( heapStats.used_heap_size )} out of ${convertToMB(heapStats.heap_size_limit)} (${typeCacheEntryCount} cache entries).` ); this._createNewEvaluator(); this._discardCachedParseResults(); this._parsedFileCount = 0; } } } // Discards all cached parse results and file contents to free up memory. // It does not discard cached index results or diagnostics for files. private _discardCachedParseResults() { for (const sourceFileInfo of this._sourceFileList) { sourceFileInfo.sourceFile.dropParseAndBindInfo(); } } private _isUserCode(fileInfo: SourceFileInfo | undefined) { return fileInfo && fileInfo.isTracked && !fileInfo.isThirdPartyImport && !fileInfo.isTypeshedFile; } // Wrapper function that should be used when invoking this._evaluator // with a cancellation token. It handles cancellation exceptions and // any other unexpected exceptions. private _runEvaluatorWithCancellationToken<T>(token: CancellationToken | undefined, callback: () => T): T { try { if (token) { return this._evaluator!.runWithCancellationToken(token, callback); } else { return callback(); } } catch (e: any) { // An unexpected exception occurred, potentially leaving the current evaluator // in an inconsistent state. Discard it and replace it with a fresh one. It is // Cancellation exceptions are known to handle this correctly. if (!(e instanceof OperationCanceledException)) { this._createNewEvaluator(); } throw e; } } // Returns a list of empty file diagnostic entries for the files // that have been removed. This is needed to clear out the // errors for files that have been deleted or closed. private _removeUnneededFiles(): FileDiagnostics[] { const fileDiagnostics: FileDiagnostics[] = []; // If a file is no longer tracked, opened or shadowed, it can // be removed from the program. for (let i = 0; i < this._sourceFileList.length; ) { const fileInfo = this._sourceFileList[i]; if (!this._isFileNeeded(fileInfo)) { fileDiagnostics.push({ filePath: fileInfo.sourceFile.getFilePath(), version: fileInfo.sourceFile.getClientVersion(), diagnostics: [], }); fileInfo.sourceFile.prepareForClose(); this._removeSourceFileFromListAndMap(fileInfo.sourceFile.getFilePath(), i); // Unlink any imports and remove them from the list if // they are no longer referenced. fileInfo.imports.forEach((importedFile) => { const indexToRemove = importedFile.importedBy.findIndex((fi) => fi === fileInfo); if (indexToRemove < 0) { return; } importedFile.importedBy.splice(indexToRemove, 1); // See if we need to remove the imported file because it // is no longer needed. If its index is >= i, it will be // removed when we get to it. if (!this._isFileNeeded(importedFile)) { const indexToRemove = this._sourceFileList.findIndex((fi) => fi === importedFile); if (indexToRemove >= 0 && indexToRemove < i) { fileDiagnostics.push({ filePath: importedFile.sourceFile.getFilePath(), version: importedFile.sourceFile.getClientVersion(), diagnostics: [], }); importedFile.sourceFile.prepareForClose(); this._removeSourceFileFromListAndMap(importedFile.sourceFile.getFilePath(), indexToRemove); i--; } } }); // Remove any shadowed files corresponding to this file. fileInfo.shadowedBy.forEach((shadowedFile) => { shadowedFile.shadows = shadowedFile.shadows.filter((f) => f !== fileInfo); }); fileInfo.shadowedBy = []; } else { // If we're showing the user errors only for open files, clear // out the errors for the now-closed file. if (!this._shouldCheckFile(fileInfo) && fileInfo.diagnosticsVersion !== undefined) { fileDiagnostics.push({ filePath: fileInfo.sourceFile.getFilePath(), version: fileInfo.sourceFile.getClientVersion(), diagnostics: [], }); fileInfo.diagnosticsVersion = undefined; } i++; } } return fileDiagnostics; } private _isFileNeeded(fileInfo: SourceFileInfo) { if (fileInfo.sourceFile.isFileDeleted()) { return false; } if (fileInfo.isTracked || fileInfo.isOpenByClient) { return true; } if (fileInfo.shadows.length > 0) { return true; } if (fileInfo.importedBy.length === 0) { return false; } // It's possible for a cycle of files to be imported // by a tracked file but then abandoned. The import cycle // will keep the entire group "alive" if we don't detect // the condition and garbage collect them. return this._isImportNeededRecursive(fileInfo, new Map<string, boolean>()); } private _isImportNeededRecursive(fileInfo: SourceFileInfo, recursionMap: Map<string, boolean>) { if (fileInfo.isTracked || fileInfo.isOpenByClient || fileInfo.shadows.length > 0) { return true; } const filePath = normalizePathCase(this._fs, fileInfo.sourceFile.getFilePath()); // Avoid infinite recursion. if (recursionMap.has(filePath)) { return false; } recursionMap.set(filePath, true); for (const importerInfo of fileInfo.importedBy) { if (this._isImportNeededRecursive(importerInfo, recursionMap)) { return true; } } return false; } private _createSourceMapper(execEnv: ExecutionEnvironment, mapCompiled?: boolean, preferStubs?: boolean) { const sourceMapper = new SourceMapper( this._importResolver, execEnv, this._evaluator!, (stubFilePath: string, implFilePath: string) => { const stubFileInfo = this._getSourceFileInfoFromPath(stubFilePath); if (!stubFileInfo) { return undefined; } this._addShadowedFile(stubFileInfo, implFilePath); return this.getBoundSourceFile(implFilePath); }, (f) => this.getBoundSourceFile(f), mapCompiled ?? false, preferStubs ?? false ); return sourceMapper; } private _isImportAllowed(importer: SourceFileInfo, importResult: ImportResult, isImportStubFile: boolean): boolean { // Don't import native libs. We don't want to track these files, // and we definitely don't want to attempt to parse them. if (importResult.isNativeLib) { return false; } let thirdPartyImportAllowed = this._configOptions.useLibraryCodeForTypes || (importResult.importType === ImportType.ThirdParty && !!importResult.pyTypedInfo) || (importResult.importType === ImportType.Local && importer.isThirdPartyPyTypedPresent); if ( importResult.importType === ImportType.ThirdParty || (importer.isThirdPartyImport && importResult.importType === ImportType.Local) ) { if (this._allowedThirdPartyImports) { if (importResult.isRelative) { // If it's a relative import, we'll allow it because the // importer was already deemed to be allowed. thirdPartyImportAllowed = true; } else if ( this._allowedThirdPartyImports.some((importName: string) => { // If this import name is the one that was explicitly // allowed or is a child of that import name, // it's considered allowed. if (importResult.importName === importName) { return true; } if (importResult.importName.startsWith(importName + '.')) { return true; } return false; }) ) { thirdPartyImportAllowed = true; } } // Some libraries ship with stub files that import from non-stubs. Don't // explore those. // Don't explore any third-party files unless they're type stub files // or we've been told explicitly that third-party imports are OK. if (!isImportStubFile) { return thirdPartyImportAllowed; } } return true; } private _updateSourceFileImports(sourceFileInfo: SourceFileInfo, options: ConfigOptions): SourceFileInfo[] { const filesAdded: SourceFileInfo[] = []; // Get the new list of imports and see if it changed from the last // list of imports for this file. const imports = sourceFileInfo.sourceFile.getImports(); // Create a local function that determines whether the import should // be considered a "third-party import" and whether it is coming from // a third-party package that claims to be typed. An import is // considered third-party if it is external to the importer // or is internal but the importer is itself a third-party package. const getThirdPartyImportInfo = (importResult: ImportResult) => { let isThirdPartyImport = false; let isPyTypedPresent = false; if (importResult.importType === ImportType.ThirdParty) { isThirdPartyImport = true; if (importResult.pyTypedInfo) { isPyTypedPresent = true; } } else if (sourceFileInfo.isThirdPartyImport && importResult.importType === ImportType.Local) { isThirdPartyImport = true; if (sourceFileInfo.isThirdPartyPyTypedPresent) { isPyTypedPresent = true; } } return { isThirdPartyImport, isPyTypedPresent, }; }; // Create a map of unique imports, since imports can appear more than once. const newImportPathMap = new Map<string, UpdateImportInfo>(); // Add chained source file as import if it exists. if (sourceFileInfo.chainedSourceFile) { if (sourceFileInfo.chainedSourceFile.sourceFile.isFileDeleted()) { sourceFileInfo.chainedSourceFile = undefined; } else { const filePath = sourceFileInfo.chainedSourceFile.sourceFile.getFilePath(); newImportPathMap.set(normalizePathCase(this._fs, filePath), { path: filePath, isTypeshedFile: false, isThirdPartyImport: false, isPyTypedPresent: false, }); } } imports.forEach((importResult) => { if (importResult.isImportFound) { if (this._isImportAllowed(sourceFileInfo, importResult, importResult.isStubFile)) { if (importResult.resolvedPaths.length > 0) { const filePath = importResult.resolvedPaths[importResult.resolvedPaths.length - 1]; if (filePath) { const thirdPartyTypeInfo = getThirdPartyImportInfo(importResult); newImportPathMap.set(normalizePathCase(this._fs, filePath), { path: filePath, isTypeshedFile: !!importResult.isTypeshedFile, isThirdPartyImport: thirdPartyTypeInfo.isThirdPartyImport, isPyTypedPresent: thirdPartyTypeInfo.isPyTypedPresent, }); } } } importResult.filteredImplicitImports.forEach((implicitImport) => { if (this._isImportAllowed(sourceFileInfo, importResult, implicitImport.isStubFile)) { if (!implicitImport.isNativeLib) { const thirdPartyTypeInfo = getThirdPartyImportInfo(importResult); newImportPathMap.set(normalizePathCase(this._fs, implicitImport.path), { path: implicitImport.path, isTypeshedFile: !!importResult.isTypeshedFile, isThirdPartyImport: thirdPartyTypeInfo.isThirdPartyImport, isPyTypedPresent: thirdPartyTypeInfo.isPyTypedPresent, }); } } }); } else if (options.verboseOutput) { this._console.info( `Could not import '${importResult.importName}' ` + `in file '${sourceFileInfo.sourceFile.getFilePath()}'` ); if (importResult.importFailureInfo) { importResult.importFailureInfo.forEach((diag) => { this._console.info(` ${diag}`); }); } } }); const updatedImportMap = new Map<string, SourceFileInfo>(); sourceFileInfo.imports.forEach((importInfo) => { const oldFilePath = normalizePathCase(this._fs, importInfo.sourceFile.getFilePath()); // A previous import was removed. if (!newImportPathMap.has(oldFilePath)) { importInfo.importedBy = importInfo.importedBy.filter( (fi) => normalizePathCase(this._fs, fi.sourceFile.getFilePath()) !== normalizePathCase(this._fs, sourceFileInfo.sourceFile.getFilePath()) ); } else { updatedImportMap.set(oldFilePath, importInfo); } }); // See if there are any new imports to be added. newImportPathMap.forEach((importInfo, normalizedImportPath) => { if (!updatedImportMap.has(normalizedImportPath)) { // We found a new import to add. See if it's already part // of the program. let importedFileInfo: SourceFileInfo; if (this._getSourceFileInfoFromPath(importInfo.path)) { importedFileInfo = this._getSourceFileInfoFromPath(importInfo.path)!; } else { const importName = this._getImportNameForFile(importInfo.path); const sourceFile = new SourceFile( this._fs, importInfo.path, importName, importInfo.isThirdPartyImport, importInfo.isPyTypedPresent, this._console, this._logTracker ); importedFileInfo = { sourceFile, isTracked: false, isOpenByClient: false, isTypeshedFile: importInfo.isTypeshedFile, isThirdPartyImport: importInfo.isThirdPartyImport, isThirdPartyPyTypedPresent: importInfo.isPyTypedPresent, diagnosticsVersion: undefined, imports: [], importedBy: [], shadows: [], shadowedBy: [], }; this._addToSourceFileListAndMap(importedFileInfo); filesAdded.push(importedFileInfo); } importedFileInfo.importedBy.push(sourceFileInfo); updatedImportMap.set(normalizedImportPath, importedFileInfo); } }); // Update the imports list. It should now map the set of imports // specified by the source file. sourceFileInfo.imports = []; newImportPathMap.forEach((_, path) => { if (this._getSourceFileInfoFromPath(path)) { sourceFileInfo.imports.push(this._getSourceFileInfoFromPath(path)!); } }); // Resolve the builtins import for the file. This needs to be // analyzed before the file can be analyzed. sourceFileInfo.builtinsImport = undefined; const builtinsImport = sourceFileInfo.sourceFile.getBuiltinsImport(); if (builtinsImport && builtinsImport.isImportFound) { const resolvedBuiltinsPath = builtinsImport.resolvedPaths[builtinsImport.resolvedPaths.length - 1]; sourceFileInfo.builtinsImport = this._getSourceFileInfoFromPath(resolvedBuiltinsPath); } // Resolve the ipython display import for the file. This needs to be // analyzed before the file can be analyzed. sourceFileInfo.ipythonDisplayImport = undefined; const ipythonDisplayImport = sourceFileInfo.sourceFile.getIPythonDisplayImport(); if (ipythonDisplayImport && ipythonDisplayImport.isImportFound) { const resolvedIPythonDisplayPath = ipythonDisplayImport.resolvedPaths[ipythonDisplayImport.resolvedPaths.length - 1]; sourceFileInfo.ipythonDisplayImport = this._getSourceFileInfoFromPath(resolvedIPythonDisplayPath); } return filesAdded; } private _getSourceFileInfoFromPath(filePath: string): SourceFileInfo | undefined { return this._sourceFileMap.get(normalizePathCase(this._fs, filePath)); } private _removeSourceFileFromListAndMap(filePath: string, indexToRemove: number) { this._sourceFileMap.delete(normalizePathCase(this._fs, filePath)); this._sourceFileList.splice(indexToRemove, 1); } private _addToSourceFileListAndMap(fileInfo: SourceFileInfo) { const filePath = normalizePathCase(this._fs, fileInfo.sourceFile.getFilePath()); // We should never add a file with the same path twice. assert(!this._sourceFileMap.has(filePath)); this._sourceFileList.push(fileInfo); this._sourceFileMap.set(filePath, fileInfo); } }
the_stack
import { expect } from "chai"; import { Angle } from "../../geometry3d/Angle"; import { GrowableBlockedArray } from "../../geometry3d/GrowableBlockedArray"; import { GrowableFloat64Array } from "../../geometry3d/GrowableFloat64Array"; import { GrowableXYZArray } from "../../geometry3d/GrowableXYZArray"; import { Matrix3d } from "../../geometry3d/Matrix3d"; import { Plane3dByOriginAndUnitNormal } from "../../geometry3d/Plane3dByOriginAndUnitNormal"; import { Point2d, Vector2d } from "../../geometry3d/Point2dVector2d"; import { Point3dArrayCarrier } from "../../geometry3d/Point3dArrayCarrier"; import { Point3d, Vector3d } from "../../geometry3d/Point3dVector3d"; import { Point3dArray } from "../../geometry3d/PointHelpers"; import { Transform } from "../../geometry3d/Transform"; import { ClusterableArray } from "../../numerics/ClusterableArray"; import { PolyfaceQuery } from "../../polyface/PolyfaceQuery"; import { Sample } from "../../serialization/GeometrySamples"; import { Checker } from "../Checker"; import { prettyPrint } from "../testFunctions"; /* eslint-disable no-console */ /** point whose coordinates are a function of i only. */ function testPointI(i: number): Point3d { return Point3d.create(i, 2 * i + 1, i * i * 3 + i * 2 - 4); } describe("GrowableFloat64Array.HelloWorld", () => { it("SizeChanges", () => { const ck = new Checker(); const arr = new GrowableFloat64Array(); arr.ensureCapacity(16); const b = 5.4; const c = 12.9; ck.testExactNumber(arr.capacity(), 16); arr.push(1); arr.push(c); const l = arr.length; ck.testExactNumber(c, arr.atUncheckedIndex(l - 1)); arr.setAtUncheckedIndex(l - 1, b); ck.testExactNumber(arr.atUncheckedIndex(l - 1), b); arr.resize(1); ck.testExactNumber(arr.length, 1); arr.resize(5); ck.testExactNumber(arr.length, 5); ck.testExactNumber(arr.front(), 1); ck.testExactNumber(arr.atUncheckedIndex(1), 0); ck.testExactNumber(arr.back(), 0); const capacityB = 100; const lB = arr.length; arr.ensureCapacity(capacityB); ck.testLE(capacityB, arr.capacity(), "adequate ensure capacity"); ck.testExactNumber(lB, arr.length, "length after expanding capacity"); ck.checkpoint("GrowableArray.float64"); expect(ck.getNumErrors()).equals(0); }); it("FilterToInterval", () => { const ck = new Checker(); const arr = new GrowableFloat64Array(); arr.ensureCapacity(16); const data = Sample.createGrowableArrayCountedSteps(0, 1, 101); const numRemaining = 3; data.restrictToInterval(9.5, 9.5 + numRemaining); ck.testExactNumber(numRemaining, data.length, "restrictToInterval"); ck.checkpoint("GrowableArray.FilterToInterval"); expect(ck.getNumErrors()).equals(0); }); it("move", () => { const ck = new Checker(); const arr = new GrowableFloat64Array(); arr.ensureCapacity(16); const data = Sample.createGrowableArrayCountedSteps(0, 1, 101); const numRemaining = 11; data.restrictToInterval(9.5, 9.5 + numRemaining); ck.testExactNumber(numRemaining, data.length, "restrictToInterval"); const data0 = data.clone(); const data1 = data.clone(true); ck.testExactNumber(data0.length, data1.length); ck.testExactNumber(data.length, data0.capacity()); ck.testExactNumber(data.capacity(), data1.capacity()); const n = data.length; // tedious reverse to use methods ... for (let i = 0, j = n - 1; i < j; i++, j--) { // swap odd i by logic at this level. others swap with single method call .swap if ((i % 2) === 1) { const a = data.atUncheckedIndex(i); data.move(j, i); data.setAtUncheckedIndex(j, a); } else { data.swap(i, j); } } for (let i = 0; i < n; i++) ck.testExactNumber(data0.atUncheckedIndex(i), data.atUncheckedIndex(n - 1 - i)); // block copy a subset to the end .... const numCopy = n - 4; const c0 = 2; data.pushBlockCopy(2, numCopy); for (let i = 0; i < numCopy; i++) ck.testExactNumber(data.atUncheckedIndex(c0 + i), data.atUncheckedIndex(n + i)); ck.checkpoint("GrowableArray.move"); expect(ck.getNumErrors()).equals(0); }); }); describe("BlockedArray", () => { it("Cluster", () => { const ck = new Checker(); Checker.noisy.cluster = false; const blocks = new ClusterableArray(2, 1, 20); ck.testExactNumber(blocks.numPerBlock, 4); const e = 0.00001; const tolerance = 0.1; // This is the vector perpendicular to the sort direction. // points on these lines get considered for clusters. const perp = Vector2d.create( ClusterableArray.sortVectorComponent(1), -ClusterableArray.sortVectorComponent(0)); // these points are distinct ... const xy0 = Point2d.create(1, 2); const xy1 = Point2d.create(3, 2); const xy2 = xy1.plusScaled(perp, 1.0); const xy3 = Point2d.create(3, 4.35); const xy4 = xy3.plusScaled(perp, 1.2); const xy5 = xy4.plusScaled(perp, -3.2); const points = [xy0, xy1, xy2, xy3, xy4, xy5]; // add points, not in order, some shifted be vectors of size around e. // But the shifted things are marked as known to be with the same base point. blocks.addPoint2d(xy0, 0); blocks.addPoint2d(xy0.plusXY(e, 0), 0); blocks.addPoint2d(xy3.plusXY(-e, 0.5 * e), 3); blocks.addPoint2d(xy1, 1); blocks.addPoint2d(xy1.plusXY(e, 0), 1); blocks.addPoint2d(xy2, 2); blocks.addPoint2d(xy4.plusXY(e, -e), 4); blocks.addPoint2d(xy5, 5); blocks.addPoint2d(xy3, 3); blocks.addPoint2d(xy3.plusXY(e, e), 3); blocks.addPoint2d(xy1.plusXY(-e, 0), 1); blocks.addPoint2d(xy4.plusXY(0, -e), 4); blocks.addPoint2d(xy4.plusXY(0, -0.2 * e), 4); blocks.addPoint2d(xy4.plusXY(0.3 * e, -0.2 * e), 4); // get clusters !!!! // note that the order the clusters appear has no relationship to 012345 above. if (Checker.noisy.cluster) console.log(blocks.toJSON()); const clusterIndices = blocks.clusterIndicesLexical(tolerance); if (Checker.noisy.cluster) console.log(blocks.toJSON()); if (Checker.noisy.cluster) console.log(JSON.stringify(clusterIndices)); for (let i = 0; i < clusterIndices.length; i++) { const k0 = clusterIndices[i]; if (!ClusterableArray.isClusterTerminator(k0)) { const clusterIndex0 = blocks.getExtraData(k0, 0); const uv0 = blocks.getPoint2d(k0); if (Checker.noisy.cluster) console.log("cluster seed ", k0, uv0); for (; i < clusterIndices.length; i++) { const k1 = clusterIndices[i]; if (ClusterableArray.isClusterTerminator(k1)) break; const uv1 = blocks.getPoint2d(k1); if (Checker.noisy.cluster) console.log(" cluster member", k1, uv1); const clusterIndex1 = blocks.getExtraData(k1, 0); ck.testExactNumber(clusterIndex0, clusterIndex1); ck.testLE( blocks.distanceBetweenBlocks(k0, k1), tolerance, "confirm cluster tolerance"); // k0, k1 should match each other and the original cluster point ck.testLE(uv0.distance(uv1), tolerance, "query cluster", k0, k1); ck.testLE(uv1.distance(points[clusterIndex1]), tolerance, "original cluster"); } } } // verify the various forms of index . .. const clusterToClusterStart = blocks.createIndexClusterToClusterStart(clusterIndices); const blockToClusterStart = blocks.createIndexBlockToClusterStart(clusterIndices); const blockToClusterIndex = blocks.createIndexBlockToClusterIndex(clusterIndices); const n = clusterIndices.length; ck.testExactNumber(blockToClusterStart.length, blocks.numBlocks); ck.testExactNumber(blockToClusterIndex.length, blocks.numBlocks); for (let clusterIndex = 0; clusterIndex < clusterToClusterStart.length; clusterIndex++) { const clusterStart = clusterToClusterStart[clusterIndex]; for (let i = clusterStart; i < n && !ClusterableArray.isClusterTerminator(clusterIndices[i]); i++) { const b = clusterIndices[i]; ck.testExactNumber(blockToClusterStart[b], clusterStart, "blockToClusterStart"); ck.testExactNumber(clusterIndex, blockToClusterIndex[b], blockToClusterIndex); } } blocks.clear(); ck.testExactNumber(blocks.numBlocks, 0); blocks.addBlock([3, 2, 1]); blocks.addDirect(5, 6, 7, 8, 9); blocks.addBlock([1, 2, 3]); const sortedView = blocks.sortIndicesLexical(); ck.testPoint2d(blocks.getPoint2d(sortedView[0]), Point2d.create(1, 2)); const blocks2 = new ClusterableArray(2, 3, 5); blocks2.addPoint2d(Point2d.create(1, 2), 5, 6, 7); blocks2.addPoint3d(Point3d.create(1, 2, 3), 5, 6, 7); ck.testPoint3d(blocks2.getPoint3d(1), Point3d.create(1, 2, 3)); const obj = blocks2.toJSON(); ck.testTrue(obj[0][2][0] === 1 && obj[0][2][1] === 2); ck.testTrue(obj[1][2][0] === 1 && obj[1][2][1] === 2); blocks2.popBlock(); ck.testExactNumber(blocks2.numBlocks, 1); ck.testExactNumber(blocks2.checkedComponent(0, 1)!, 1); ck.testUndefined(blocks2.checkedComponent(1, 2)); ck.checkpoint("GrowableArray.annotateClusters"); expect(ck.getNumErrors()).equals(0); }); it("HelloWorld", () => { // REMARK: GrowableBlockedArray gets significant testing via GrowableXYZArray. const ck = new Checker(); const numPerBlock = 5; const numInitialBlocks = 7; const data0 = new GrowableBlockedArray(numPerBlock, numInitialBlocks); ck.testExactNumber(numPerBlock, data0.numPerBlock); ck.testExactNumber(0, data0.numBlocks); const blockStep = 10; const baseBlock = [1, 3, 5, 7, 9]; // all less than blockStep to simplify testing. const numAdd = 9; for (let i = 0; i < numAdd; i++) { const newBlock = []; const blockBaseValue = blockStep * data0.numBlocks; for (const a of baseBlock) newBlock.push(a + blockBaseValue); if (i === 3 || i === 7) newBlock.push(999); // an extraneous value to test handling of oversize inputs data0.addBlock(newBlock); } for (let blockIndex = 0; blockIndex < numAdd; blockIndex++) { for (let j = 0; j < numPerBlock; j++) { ck.testExactNumber(baseBlock[j] + blockIndex * blockStep, data0.component(blockIndex, j)); } } ck.testExactNumber(numAdd, data0.numBlocks); ck.checkpoint("GrowableBlockedArray.HelloWorld"); expect(ck.getNumErrors()).equals(0); }); }); describe("GrowablePoint3dArray", () => { it("PointMoments", () => { const ck = new Checker(); for (let n = 3; n < 100; n *= 2) { const pointA = new GrowableXYZArray(); const pointB = []; ck.testExactNumber(pointA.length, 0); // load pointB for (let i = 0; i < n; i++) { pointB.push(Point3d.create(Math.cos(i * i), i + 0.25, i + 0.5)); // pointB.push(Point3d.create(i, i + 0.25, i + 0.5)); // pointB.push(Point3d.create(-i, i + 0.25, i + 0.5)); } // verify undefined returns from empty array ck.testUndefined(pointA.front()); ck.testUndefined(pointA.back()); ck.testFalse(pointA.isIndexValid(4)); for (const p of pointB) { pointA.push(p); ck.testPoint3d(p, pointA.back() as Point3d); ck.testPoint3d(pointB[0], pointA.front() as Point3d); } for (let i = 0; i < n; i++) ck.testPoint3d(pointB[i], pointA.getPoint3dAtUncheckedPointIndex(i)); ck.testExactNumber(pointA.length, pointB.length, "array lengths"); let lengthA = 0; for (let i = 0; i + 1 < n; i++) { lengthA += pointA.getPoint3dAtUncheckedPointIndex(i).distance(pointA.getPoint3dAtUncheckedPointIndex(i + 1)); const d0 = pointA.distanceIndexIndex(i, i + 1); const d1 = pointA.distanceIndexIndex(i, i + 1); const d1Squared = pointA.distanceSquaredIndexIndex(i, i + 1); ck.testCoordinate(d0!, d1!); ck.testFalse(d1Squared === undefined); ck.testCoordinate(d0! * d0!, d1Squared!); } const lengthA1 = pointA.sumLengths(); ck.testCoordinate(lengthA, lengthA1, "polyline length"); ck.testExactNumber(pointA.length, n); // we are confident that all x coordinates are distinct ... const sortOrder = pointA.sortIndicesLexical(); for (let i = 1; i < sortOrder.length; i++) { const a = sortOrder[i - 1]; const b = sortOrder[i]; ck.testTrue(pointA.compareLexicalBlock(a, b) < 0, " confirm lexical sort order"); ck.testTrue(pointA.component(a, 0) <= pointA.component(b, 0), "confirm sort order x"); } ck.testUndefined(pointA.distanceIndexIndex(0, 1000)); ck.testUndefined(pointA.distanceIndexIndex(-1, 0)); ck.testUndefined(pointA.distanceSquaredIndexIndex(0, 1000)); ck.testUndefined(pointA.distanceSquaredIndexIndex(-1, 0)); } ck.checkpoint("GrowablePoint3dArray.HelloWorld"); expect(ck.getNumErrors()).equals(0); }); it("Wrap", () => { const ck = new Checker(); const numWrap = 3; for (let n = 5; n < 100; n *= 2) { const pointA = Sample.createGrowableArrayCirclePoints(1.0, n, false); pointA.pushWrap(numWrap); ck.testExactNumber(n + numWrap, pointA.length, "pushWrap increases length"); for (let i = 0; i < numWrap; i++) { ck.testPoint3d(pointA.getPoint3dAtUncheckedPointIndex(i), pointA.getPoint3dAtUncheckedPointIndex(n + i), "wrapped point"); } let numDup = 0; const sortOrder = pointA.sortIndicesLexical(); for (let i = 0; i + 1 < pointA.length; i++) { const k0 = sortOrder[i]; const k1 = sortOrder[i + 1]; if (pointA.getPoint3dAtUncheckedPointIndex(k0).isAlmostEqual(pointA.getPoint3dAtUncheckedPointIndex(k1))) { ck.testLT(k0, k1, "lexical sort preserves order for duplicates"); numDup++; } else { const s = pointA.compareLexicalBlock(k0, k1); ck.testExactNumber(-1, s); const s1 = pointA.compareLexicalBlock(k1, k0); ck.testExactNumber(1, s1); } ck.testExactNumber(i, pointA.cyclicIndex(i)); ck.testExactNumber(i, pointA.cyclicIndex(i + pointA.length)); } ck.testExactNumber(numWrap, numDup, "confirm numWrap duplicates"); } ck.checkpoint("GrowablePoint3dArray.Wrap"); expect(ck.getNumErrors()).equals(0); }); it("PolyfaceMoments", () => { const ck = new Checker(); ck.checkpoint("Solids.PointMoments"); // https://en.wikipedia.org/wiki/List_of_second_moments_of_area // https://en.wikipedia.org/wiki/List_of_moments_of_inertia // Filled rectangular area with x size b, y size h, centered at origin. const b = 6.0; const h = 2.0; const IX = b * h * h * h / 12.0; const IY = b * b * b * h / 12.0; for (const origin of [Point3d.create(-b / 2, -h / 2, 0), Point3d.create(1, 1, 0)]) { const polyface = Sample.createTriangularUnitGridPolyface( origin, Vector3d.create(b, 0, 0), Vector3d.create(0, h, 0), 2, 2, false, false, false); const moments = PolyfaceQuery.computePrincipalAreaMoments(polyface); if (Checker.noisy.rectangleMoments) { console.log("Rectangle lower left", origin); console.log(prettyPrint(polyface)); console.log(prettyPrint(moments!)); console.log("expected IX", IX); console.log("expected IY", IY); } } expect(ck.getNumErrors()).equals(0); }); /** Basic output testing on appendages, sorting, transforming of a known inverse, and testing recognition of plane proximity within correct tolerance */ it("BlackBoxTests", () => { const ck = new Checker(); const arr = new GrowableXYZArray(); arr.ensureCapacity(9); arr.push(Point3d.create(1, 2, 3)); arr.push(Point3d.create(4, 5, 6)); arr.push(Point3d.create(7, 8, 9)); arr.resize(2); ck.testExactNumber(arr.length, 2); ck.testTrue(arr.compareLexicalBlock(0, 1) < 0 && arr.compareLexicalBlock(1, 0) > 0); const point = Point3d.create(); arr.getPoint3dAtCheckedPointIndex(1, point); const vector = arr.getVector3dAtCheckedVectorIndex(1)!; ck.testTrue(point.isAlmostEqual(vector)); ck.testPoint3d(point, Point3d.create(4, 5, 6)); const transform = Transform.createOriginAndMatrix(Point3d.create(0, 0, 0), Matrix3d.createRowValues( 2, 1, 0, 2, 0, 0, 2, 0, 1, )); const noInverseTransform = Transform.createOriginAndMatrix(Point3d.create(0, 0, 0), Matrix3d.createRowValues( 1, 6, 4, 2, 4, -1, -1, 2, 5, )); ck.testTrue(arr.tryTransformInverseInPlace(transform)); ck.testFalse(arr.tryTransformInverseInPlace(noInverseTransform)); ck.testPoint3d(arr.getPoint3dAtUncheckedPointIndex(0), Point3d.create(1, -1, 1)); arr.resize(1); const closePlane = Plane3dByOriginAndUnitNormal.create(Point3d.create(1, -1 + 1.0e-10, 1), Vector3d.create(1, 1, 1)); const nonClosePlane = Plane3dByOriginAndUnitNormal.create(Point3d.create(1, -1 + 1.0e-4, 1), Vector3d.create(1, 1, 1)); ck.testTrue(arr.isCloseToPlane(closePlane!)); ck.testFalse(arr.isCloseToPlane(nonClosePlane!)); expect(ck.getNumErrors()).equals(0); }); it("IndexedXYZCollection", () => { const ck = new Checker(); const points = Sample.createFractalDiamondConvexPattern(1, -0.5); const frame = Transform.createFixedPointAndMatrix(Point3d.create(1, 2, 3), Matrix3d.createRotationAroundVector(Vector3d.create(0.3, -0.2, 1.2), Angle.createDegrees(15.7))!); frame.multiplyPoint3dArrayInPlace(points); const gPoints = new GrowableXYZArray(); gPoints.pushAll(points); const iPoints = new Point3dArrayCarrier(points); const iOrigin = iPoints.getPoint3dAtCheckedPointIndex(0)!; const gOrigin = gPoints.getPoint3dAtCheckedPointIndex(0)!; ck.testPoint3d(iOrigin, gOrigin, "point 0 access"); for (let i = 1; i + 1 < points.length; i++) { const j = i + 1; const pointIA = iPoints.getPoint3dAtCheckedPointIndex(i)!; const pointGA = gPoints.getPoint3dAtCheckedPointIndex(i)!; const pointIB = iPoints.getPoint3dAtCheckedPointIndex(j)!; const pointGB = gPoints.getPoint3dAtCheckedPointIndex(j)!; const vectorIA = iPoints.vectorIndexIndex(i, j)!; const vectorGA = gPoints.vectorIndexIndex(i, j)!; const vectorIA1 = iPoints.vectorXYAndZIndex(pointIA, j)!; const vectorGA1 = gPoints.vectorXYAndZIndex(pointIA, j)!; ck.testVector3d(vectorIA1, vectorGA1, "vectorXYAndZIndex"); ck.testPoint3d(pointIA, pointGA, "atPoint3dIndex"); ck.testVector3d(vectorIA, pointIA.vectorTo(pointIB)); ck.testVector3d(vectorGA, pointIA.vectorTo(pointGB)); ck.testVector3d( iPoints.crossProductIndexIndexIndex(0, i, j)!, gPoints.crossProductIndexIndexIndex(0, i, j)!); ck.testVector3d( iPoints.crossProductXYAndZIndexIndex(iOrigin, i, j)!, gPoints.crossProductXYAndZIndexIndex(gOrigin, i, j)!); ck.testVector3d( iPoints.getVector3dAtCheckedVectorIndex(i)!, gPoints.getVector3dAtCheckedVectorIndex(i)!, "atVector3dIndex"); ck.testPoint3d(Point3dArray.centroid(iPoints), Point3dArray.centroid(gPoints), "centroid"); } expect(ck.getNumErrors()).equals(0); }); it("resizeAndBoundsChecks", () => { const ck = new Checker(); const points = Sample.createFractalDiamondConvexPattern(1, -0.5); const xyzPoints = new GrowableXYZArray(points.length); // just enough so we know the initial capacity. for (const p of points) xyzPoints.push(p); ck.testTrue(GrowableXYZArray.isAlmostEqual(xyzPoints, xyzPoints), "isAlmostEqual duplicate pair"); ck.testTrue(GrowableXYZArray.isAlmostEqual(undefined, undefined), "isAlmostEqual undefined pair"); ck.testFalse(GrowableXYZArray.isAlmostEqual(undefined, xyzPoints), "isAlmostEqual one undefined"); ck.testFalse(GrowableXYZArray.isAlmostEqual(xyzPoints, undefined), "isAlmostEqual one undefined"); const n0 = xyzPoints.length; ck.testExactNumber(n0, points.length); const deltaN = 5; const n1 = n0 + deltaN; xyzPoints.resize(n1); ck.testExactNumber(n1, xyzPoints.length); const n2 = n0 - deltaN; xyzPoints.resize(n2); // blow away some points. ck.testUndefined(xyzPoints.getVector3dAtCheckedVectorIndex(-4)); ck.testUndefined(xyzPoints.getVector3dAtCheckedVectorIndex(n2)); // verify duplicate methods .... for (let i0 = 3; i0 < n2; i0 += 5) { for (let i1 = 0; i1 < n2; i1 += 3) { const vectorA = points[i0].vectorTo(points[i1]); const vectorB = xyzPoints.vectorIndexIndex(i0, i1); if (vectorB) ck.testVector3d(vectorA, vectorB); else ck.announceError("vectorIndexIndex?", i0, i1, vectorA, vectorB); } } const spacePoint = Point3d.create(1, 4, 3); for (let i0 = 2; i0 < n2; i0 += 6) { const distance0 = xyzPoints.distanceIndexToPoint(i0, spacePoint); const distance1 = xyzPoints.getPoint3dAtCheckedPointIndex(i0)!.distance(spacePoint); const vectorI0 = xyzPoints.vectorXYAndZIndex(spacePoint, i0); if (ck.testPointer(vectorI0) && distance0 !== undefined) { ck.testCoordinate(vectorI0.magnitude(), distance0)!; ck.testCoordinate(distance0, distance1); } } ck.testUndefined(xyzPoints.distanceIndexIndex(-1, 0), "distance to invalid indexA"); ck.testUndefined(xyzPoints.distanceIndexIndex(0, -1), "distance to invalid indexB"); ck.testUndefined(xyzPoints.distanceIndexToPoint(-1, spacePoint), "distance to invalid indexA"); ck.testFalse(xyzPoints.setXYZAtCheckedPointIndex(-5, 1, 2, 3), "negative index for setCoordinates"); ck.testFalse(xyzPoints.setXYZAtCheckedPointIndex(100, 1, 2, 3), "huge index for setCoordinates"); ck.testFalse(xyzPoints.setAtCheckedPointIndex(-5, spacePoint), "negative index for setAt"); ck.testFalse(xyzPoints.setAtCheckedPointIndex(100, spacePoint), "huge index for setAt"); ck.testUndefined(xyzPoints.vectorXYAndZIndex(spacePoint, -5), "negative index for vectorXYAndZIndex"); expect(ck.getNumErrors()).equals(0); }); it("transferAndSet", () => { const ck = new Checker(); const points = Sample.createFractalDiamondConvexPattern(1, -0.5); const array0 = new GrowableXYZArray(points.length); // just enough so we know the initial capacity. for (const p of points) array0.push(p); const n0 = array0.length; const array1 = new GrowableXYZArray(); // transfers with bad source index ck.testExactNumber(0, array1.pushFromGrowableXYZArray(array0, -1), "invalid source index for pushFromGrowable"); ck.testExactNumber(0, array1.pushFromGrowableXYZArray(array0, n0 + 1), "invalid source index for pushFromGrowable"); // Any transfer into empty array is bad . .. ck.testFalse(array1.transferFromGrowableXYZArray(-1, array0, 1), "invalid source index transferFromGrowable"); ck.testFalse(array1.transferFromGrowableXYZArray(0, array0, 1), "invalid source index transferFromGrowable"); ck.testFalse(array1.transferFromGrowableXYZArray(100, array0, 1), "invalid source index transferFromGrowable"); ck.testUndefined(array1.crossProductIndexIndexIndex(-1, 0, 1), "bad index0 for cross product"); ck.testUndefined(array1.crossProductIndexIndexIndex(0, 100, 1), "bad index1 for cross product"); ck.testUndefined(array1.crossProductIndexIndexIndex(0, 1, 100), "bad index2 for cross product"); const spacePoint = Point3d.create(1, 2, 3); ck.testUndefined(array1.crossProductXYAndZIndexIndex(spacePoint, -1, 0), "bad indexA for cross product"); ck.testUndefined(array1.crossProductXYAndZIndexIndex(spacePoint, 0, -1), "bad indexB for cross product"); const resultA = Point3d.create(); const interpolationFraction = 0.321; for (let k = 1; k + 2 < n0; k++) { ck.testExactNumber(1, array1.pushFromGrowableXYZArray(array0, k), "transformFromGrowable"); ck.testUndefined(array1.interpolate(-1, 0.3, k), "interpolate with bad index"); ck.testUndefined(array1.interpolate(100, 0.3, k), "interpolate with bad index"); ck.testUndefined(array1.vectorIndexIndex(-1, k), "invalid index vectorIndexIndex"); ck.testUndefined(array1.vectorIndexIndex(k, -1), "invalid index vectorIndexIndex"); ck.testUndefined(array1.interpolate(k, 0.3, n0 + 1), "interpolate with bad index"); ck.testUndefined(array1.interpolate(k, 0.3, n0 + 3), "interpolate with bad index"); const k1 = (2 * k) % n0; // this should be a valid index !!! if (ck.testTrue(array0.isIndexValid(k1) && ck.testPointer(array0.interpolate(k, interpolationFraction, k1, resultA)))) { const k2 = (2 * k + 1) % n0; const point0 = array0.getPoint3dAtUncheckedPointIndex(k); const point1 = array0.getPoint3dAtUncheckedPointIndex(k1); const resultB = point0.interpolate(interpolationFraction, point1); ck.testPoint3d(resultA, resultB, "compare interpolation paths"); const crossA = array0.crossProductIndexIndexIndex(k, k1, k2); const crossB = array0.crossProductXYAndZIndexIndex(point0, k1, k2); if (ck.testPointer(crossA) && ck.testPointer(crossB)) { ck.testVector3d(crossA, crossB, "cross products to indexed points"); } } } // bad transfers when the dest is not empty . . . ck.testFalse(array1.transferFromGrowableXYZArray(-1, array0, 1), "invalid source index transferFromGrowable"); ck.testFalse(array1.transferFromGrowableXYZArray(100, array0, 1), "invalid source index transferFromGrowable"); expect(ck.getNumErrors()).equals(0); }); it("Compress", () => { const ck = new Checker(); const data = new GrowableFloat64Array(); data.compressAdjacentDuplicates(); // nothing happens on empty array. const n0 = 22; for (let i = 0; i < n0; i++) { const c = Math.cos(i * i); let n = 1; if (c < -0.6) n = 3; else if (c > 0.1) { if (c < 0.8) n = 2; else n = 4; } for (let k = 0; k < n; k++) data.push(i); } const n1 = data.length; data.compressAdjacentDuplicates(0.0001); ck.testExactNumber(n0, data.length, "compressed array big length", n1); expect(ck.getNumErrors()).equals(0); }); it("Coverage", () => { const ck = new Checker(); const dataA = new GrowableXYZArray(); const dataB = new GrowableXYZArray(); for (let i = 0; i < 5; i++) { dataA.push(testPointI(i)); } for (let j = 0; j < 3; j++) { dataB.push(testPointI(2 * j)); } for (let i = 0; i < dataA.length; i++) { for (let j = 0; j < dataB.length; j++) { ck.testCoordinate(GrowableXYZArray.distanceBetweenPointsIn2Arrays(dataA, i, dataB, j)!, testPointI(i).distance(testPointI(2 * j))); const pointA2 = dataA.getPoint2dAtCheckedPointIndex(i)!; const pointB2 = dataB.getPoint2dAtUncheckedPointIndex(j); const pointA3 = dataA.getPoint3dAtCheckedPointIndex(i)!; const pointB3 = dataB.getPoint3dAtUncheckedPointIndex(j); ck.testCoordinate(pointA2.distance(pointB2), pointB3.distanceXY(pointA3)); } } for (const i of [-2, 12]) { ck.testUndefined(dataA.getPoint2dAtCheckedPointIndex(i)); for (const j of [24, -3]) { ck.testUndefined(GrowableXYZArray.distanceBetweenPointsIn2Arrays(dataA, i, dataB, j)); } } expect(ck.getNumErrors()).equals(0); }); it("TransformingNormals", () => { const ck = new Checker(); const dataA = new GrowableXYZArray(); ck.testFalse(dataA.multiplyAndRenormalizeMatrix3dInverseTransposeInPlace(Matrix3d.createScale(0, 1, 0)), "Singular Matrix should fail"); const matrix = Matrix3d.createRowValues( 6, -3, 1, 4, 9, 2, -1, 4, 8); const matrixTranspose = matrix.transpose(); dataA.pushXYZ(1, 0, 0); ck.testTrue(dataA.multiplyAndRenormalizeMatrix3dInverseTransposeInPlace(matrix), "Normal transform with good data"); dataA.pushXYZ(0, 0, 0); ck.testFalse(dataA.multiplyAndRenormalizeMatrix3dInverseTransposeInPlace(matrix), "Normal transform with bad data"); dataA.clear(); for (let i = 0; i < 5; i++) { dataA.push(testPointI(i)); } const matrixInverseTranspose = matrixTranspose.inverse()!; const dataB = dataA.clone(); ck.testTrue(dataA.multiplyAndRenormalizeMatrix3dInverseTransposeInPlace(matrix)); dataB.multiplyMatrix3dInPlace(matrixInverseTranspose); for (let i = 0; i < dataA.length; i++) { const vectorA = dataA.getVector3dAtCheckedVectorIndex(i)!; const vectorB = dataB.getVector3dAtCheckedVectorIndex(i)!; ck.testCoordinate(vectorA.magnitude(), 1.0); ck.testParallel(vectorA, vectorB); } expect(ck.getNumErrors()).equals(0); }); it("pushFrom", () => { const ck = new Checker(); const dataA = new GrowableXYZArray(); const dataB = new GrowableXYZArray(); const dataC = new GrowableXYZArray(); const dataD = new GrowableXYZArray(); const dataA0 = new GrowableXYZArray(); const dataB0 = new GrowableXYZArray(); const dataC0 = new GrowableXYZArray(); const points = [ Point3d.create(1, 2, 3), Point3d.create(2, 4, 10)]; /** Assemble the points into GrowableXYZArray with variant input parse ... */ dataA.pushFrom(points); for (const p of points) { dataB.pushFrom(p); dataC.pushFrom({ x: p.x, y: p.y, z: p.z }); dataD.pushFrom([p.x, p.y, p.z]); } for (const p of points) { const p2 = Point2d.create(p.x, p.y); dataA0.pushFrom(p2); dataB0.pushFrom({ x: p.x, y: p.y }); dataC0.pushFrom([p.x, p.y]); } ck.testTrue(GrowableXYZArray.isAlmostEqual(dataA, dataB)); ck.testTrue(GrowableXYZArray.isAlmostEqual(dataA, dataC)); ck.testTrue(GrowableXYZArray.isAlmostEqual(dataA0, dataB0)); ck.testTrue(GrowableXYZArray.isAlmostEqual(dataA0, dataC0)); expect(ck.getNumErrors()).equals(0); }); it("pushFront", () => { const ck = new Checker(); const dataA = new GrowableXYZArray(); const dataB = new GrowableXYZArray(); // push front and back, forcing several reallocations for (let i = 0; i < 75; i++) { const xyz = { x: i, y: 10 + i, z: 20 + i }; dataA.push(xyz); dataB.pushFront(xyz); } dataA.reverseInPlace(); ck.testTrue(GrowableXYZArray.isAlmostEqual(dataA, dataB)); expect(ck.getNumErrors()).equals(0); }); });
the_stack
import * as React from 'react' import { LoadingOverlay } from '../lib/loading' import { encodePathAsUrl } from '../../lib/path' import { Repository } from '../../models/repository' import { MenuIDs } from '../../models/menu-ids' import { IMenu, MenuItem } from '../../models/app-menu' import memoizeOne from 'memoize-one' import { getPlatformSpecificNameOrSymbolForModifier } from '../../lib/menu-item' import { MenuBackedSuggestedAction, SuggestedActionGroup, } from '../suggested-actions' import { IRepositoryState } from '../../lib/app-state' import { TipState, IValidBranch } from '../../models/tip' import { Ref } from '../lib/ref' import { IAheadBehind } from '../../models/branch' import { IRemote } from '../../models/remote' import { isCurrentBranchForcePush } from '../../lib/rebase' import { StashedChangesLoadStates } from '../../models/stash-entry' export function formatParentMenuLabel(menuItem: IMenuItemInfo) { return menuItem.parentMenuLabels.join(' -> ') } const PaperStackImage = encodePathAsUrl(__dirname, 'static/paper-stack.svg') interface INoChangesProps { readonly loadingDiff: number | null /** * The currently selected repository */ readonly repository: Repository /** * The top-level application menu item. */ readonly appMenu: IMenu | undefined /** * An object describing the current state of * the selected repository. Used to determine * whether to render push, pull, publish, or * 'open pr' actions. */ readonly repositoryState: IRepositoryState } /** * Helper projection interface used to hold * computed information about a particular menu item. * Used internally in the NoChanges component to * trace whether a menu item is enabled, what its * keyboard shortcut is and so forth. */ export interface IMenuItemInfo { /** * The textual representation of the menu item, * this is what's shown in the application menu */ readonly label: string /** * Any accelerator keys (i.e. keyboard shortcut) * for the menu item. A menu item which can be * triggered using Command+Shift+K would be * represented here as three elements in the * array. Used to format and display the keyboard * shortcut for activating an action. */ readonly acceleratorKeys: ReadonlyArray<string> /** * An ordered list of the labels for parent menus * of a particular menu item. Used to provide * a textual representation of where to locate * a particular action in the menu system. */ readonly parentMenuLabels: ReadonlyArray<string> /** * Whether or not the menu item is currently * enabled. */ readonly enabled: boolean } interface INoChangesState { /** * Whether or not to enable the slide in and * slide out transitions for the remote actions. * * Disabled initially and enabled 500ms after * component mounting in order to provide instant * loading of the remote action when the view is * initially appearing. */ readonly enableTransitions: boolean } function getItemAcceleratorKeys(item: MenuItem) { if (item.type === 'separator' || item.type === 'submenuItem') { return [] } if (item.accelerator === null) { return [] } return item.accelerator .split('+') .map(getPlatformSpecificNameOrSymbolForModifier) } export function buildMenuItemInfoMap( menu: IMenu, map = new Map<string, IMenuItemInfo>(), parent?: IMenuItemInfo ): ReadonlyMap<string, IMenuItemInfo> { for (const item of menu.items) { if (item.type === 'separator') { continue } const infoItem: IMenuItemInfo = { label: item.label, acceleratorKeys: getItemAcceleratorKeys(item), parentMenuLabels: parent === undefined ? [] : [parent.label, ...parent.parentMenuLabels], enabled: item.enabled, } map.set(item.id, infoItem) if (item.type === 'submenuItem') { buildMenuItemInfoMap(item.menu, map, infoItem) } } return map } /** The component to display when there are no local changes. */ export class NoChanges extends React.Component< INoChangesProps, INoChangesState > { private getMenuInfoMap = memoizeOne((menu: IMenu | undefined) => menu === undefined ? new Map<string, IMenuItemInfo>() : buildMenuItemInfoMap(menu) ) /** * ID for the timer that's activated when the component * mounts. See componentDidMount/componentWillUnmount. */ private transitionTimer: number | null = null public constructor(props: INoChangesProps) { super(props) this.state = { enableTransitions: false, } } private getMenuItemInfo(menuItemId: MenuIDs): IMenuItemInfo | undefined { return this.getMenuInfoMap(this.props.appMenu).get(menuItemId) } private renderDiscoverabilityElements(menuItem: IMenuItemInfo) { const parentMenusText = formatParentMenuLabel(menuItem) return ( <> {parentMenusText} menu{' '} {menuItem.acceleratorKeys.length ? ( <span>or {this.renderDiscoverabilityKeyboardShortcut(menuItem)}</span> ) : null} </> ) } private renderDiscoverabilityKeyboardShortcut(menuItem: IMenuItemInfo) { return menuItem.acceleratorKeys.map((k, i) => <kbd key={k + i}>{k}</kbd>) } private renderMenuBackedAction( itemId: MenuIDs, title: string, description?: string | JSX.Element, onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void ) { const menuItem = this.getMenuItemInfo(itemId) if (menuItem === undefined) { log.error(`Could not find matching menu item for ${itemId}`) return null } return ( <MenuBackedSuggestedAction title={title} description={description} discoverabilityContent={this.renderDiscoverabilityElements(menuItem)} menuItemId={itemId} buttonText={menuItem.label} disabled={!menuItem.enabled} onClick={onClick} /> ) } private renderShowInFileManager() { return this.renderMenuBackedAction( 'open-working-directory', `View the files in your repository in Finder` ) } private renderCreateNewSketchFile() { return this.renderMenuBackedAction( 'create-sketch-file', `Create a new Sketch file` ) } private renderViewOnGitHub() { const isGitHub = this.props.repository.gitHubRepository !== null if (!isGitHub) { return null } return this.renderMenuBackedAction( 'view-repository-on-github', `Open the repository page on GitHub in your browser` ) } private renderRemoteAction() { const { remote, aheadBehind, branchesState, tagsToPush, } = this.props.repositoryState const { tip, defaultBranch, currentPullRequest } = branchesState if (tip.kind !== TipState.Valid) { return null } if (remote === null) { return this.renderPublishRepositoryAction() } // Branch not published if (aheadBehind === null) { return this.renderPublishBranchAction(tip) } const isForcePush = isCurrentBranchForcePush(branchesState, aheadBehind) if (isForcePush) { // do not render an action currently after the rebase has completed, as // the default behaviour is currently to pull in changes from the tracking // branch which will could potentially lead to a more confusing history return null } if (aheadBehind.behind > 0) { return this.renderPullBranchAction(tip, remote, aheadBehind) } if ( aheadBehind.ahead > 0 || (tagsToPush !== null && tagsToPush.length > 0) ) { return this.renderPushBranchAction(tip, remote, aheadBehind, tagsToPush) } const isGitHub = this.props.repository.gitHubRepository !== null const hasOpenPullRequest = currentPullRequest !== null const isDefaultBranch = defaultBranch !== null && tip.branch.name === defaultBranch.name if (isGitHub && !hasOpenPullRequest && !isDefaultBranch) { return this.renderCreatePullRequestAction(tip) } return null } private renderViewStashAction() { const { changesState, branchesState } = this.props.repositoryState const { tip } = branchesState if (tip.kind !== TipState.Valid) { return null } const { stashEntry } = changesState if (stashEntry === null) { return null } if (stashEntry.files.kind !== StashedChangesLoadStates.Loaded) { return null } const numChanges = stashEntry.files.files.length const description = ( <> You have {numChanges} {numChanges === 1 ? 'change' : 'changes'} in progress that you have not yet committed. </> ) const discoverabilityContent = ( <> When a stash exists, access it at the bottom of the Changes tab to the left. </> ) const itemId: MenuIDs = 'toggle-stashed-changes' const menuItem = this.getMenuItemInfo(itemId) if (menuItem === undefined) { log.error(`Could not find matching menu item for ${itemId}`) return null } return ( <MenuBackedSuggestedAction key="view-stash-action" title="View your stashed changes" menuItemId={itemId} description={description} discoverabilityContent={discoverabilityContent} buttonText="View stash" type="primary" disabled={menuItem !== null && !menuItem.enabled} /> ) } private renderPublishRepositoryAction() { // This is a bit confusing, there's no dedicated // publish menu item, the 'Push' menu item will initiate // a publish if the repository doesn't have a remote. We'll // use it here for the keyboard shortcut only. const itemId: MenuIDs = 'push' const menuItem = this.getMenuItemInfo(itemId) if (menuItem === undefined) { log.error(`Could not find matching menu item for ${itemId}`) return null } const discoverabilityContent = ( <> Always available in the toolbar for local repositories or{' '} {this.renderDiscoverabilityKeyboardShortcut(menuItem)} </> ) return ( <MenuBackedSuggestedAction key="publish-repository-action" title="Publish your repository to GitHub" description="This repository is currently only available on your local machine. By publishing it on GitHub you can share it, and collaborate with others." discoverabilityContent={discoverabilityContent} buttonText="Publish repository" menuItemId={itemId} type="primary" disabled={!menuItem.enabled} /> ) } private renderPublishBranchAction(tip: IValidBranch) { // This is a bit confusing, there's no dedicated // publish branch menu item, the 'Push' menu item will initiate // a publish if the branch doesn't have a remote tracking branch. // We'll use it here for the keyboard shortcut only. const itemId: MenuIDs = 'push' const menuItem = this.getMenuItemInfo(itemId) if (menuItem === undefined) { log.error(`Could not find matching menu item for ${itemId}`) return null } const isGitHub = this.props.repository.gitHubRepository !== null const description = ( <> The current branch (<Ref>{tip.branch.name}</Ref>) hasn't been published to the remote yet. By publishing it {isGitHub ? 'to GitHub' : ''} you can share it, {isGitHub ? 'open a pull request, ' : ''} and collaborate with others. </> ) const discoverabilityContent = ( <> Always available in the toolbar or{' '} {this.renderDiscoverabilityKeyboardShortcut(menuItem)} </> ) return ( <MenuBackedSuggestedAction key="publish-branch-action" title="Publish your branch" menuItemId={itemId} description={description} discoverabilityContent={discoverabilityContent} buttonText="Publish branch" type="primary" disabled={!menuItem.enabled} /> ) } private renderPullBranchAction( tip: IValidBranch, remote: IRemote, aheadBehind: IAheadBehind ) { const itemId: MenuIDs = 'pull' const menuItem = this.getMenuItemInfo(itemId) if (menuItem === undefined) { log.error(`Could not find matching menu item for ${itemId}`) return null } const isGitHub = this.props.repository.gitHubRepository !== null const description = ( <> The current branch (<Ref>{tip.branch.name}</Ref>) has{' '} {aheadBehind.behind === 1 ? 'a commit' : 'commits'} on{' '} {isGitHub ? 'GitHub' : 'the remote'} that{' '} {aheadBehind.behind === 1 ? 'does not' : 'do not'} exist on your machine. </> ) const discoverabilityContent = ( <> Always available in the toolbar when there are remote changes or{' '} {this.renderDiscoverabilityKeyboardShortcut(menuItem)} </> ) const title = `Pull ${aheadBehind.behind} ${ aheadBehind.behind === 1 ? 'commit' : 'commits' } from the ${remote.name} remote` const buttonText = `Pull ${remote.name}` return ( <MenuBackedSuggestedAction key="pull-branch-action" title={title} menuItemId={itemId} description={description} discoverabilityContent={discoverabilityContent} buttonText={buttonText} type="primary" disabled={!menuItem.enabled} /> ) } private renderPushBranchAction( tip: IValidBranch, remote: IRemote, aheadBehind: IAheadBehind, tagsToPush: ReadonlyArray<string> | null ) { const itemId: MenuIDs = 'push' const menuItem = this.getMenuItemInfo(itemId) if (menuItem === undefined) { log.error(`Could not find matching menu item for ${itemId}`) return null } const isGitHub = this.props.repository.gitHubRepository !== null const itemsToPushTypes = [] const itemsToPushDescriptions = [] if (aheadBehind.ahead > 0) { itemsToPushTypes.push('commits') itemsToPushDescriptions.push( aheadBehind.ahead === 1 ? '1 local commit' : `${aheadBehind.ahead} local commits` ) } if (tagsToPush !== null && tagsToPush.length > 0) { itemsToPushTypes.push('tags') itemsToPushDescriptions.push( tagsToPush.length === 1 ? '1 tag' : `${tagsToPush.length} tags` ) } const description = `You have ${itemsToPushDescriptions.join( ' and ' )} waiting to be pushed to ${isGitHub ? 'GitHub' : 'the remote'}.` const discoverabilityContent = ( <> Always available in the toolbar when there are local commits waiting to be pushed or {this.renderDiscoverabilityKeyboardShortcut(menuItem)} </> ) const title = `Push ${itemsToPushTypes.join(' and ')} to the ${ remote.name } remote` const buttonText = `Push ${remote.name}` return ( <MenuBackedSuggestedAction key="push-branch-action" title={title} menuItemId={itemId} description={description} discoverabilityContent={discoverabilityContent} buttonText={buttonText} type="primary" disabled={!menuItem.enabled} /> ) } private renderCreatePullRequestAction(tip: IValidBranch) { const itemId: MenuIDs = 'create-pull-request' const menuItem = this.getMenuItemInfo(itemId) if (menuItem === undefined) { log.error(`Could not find matching menu item for ${itemId}`) return null } const description = ( <> The current branch (<Ref>{tip.branch.name}</Ref>) is already published to GitHub. Create a pull request to propose and collaborate on your changes. </> ) const title = `Create a Pull Request from your current branch` const buttonText = `Create Pull Request` return ( <MenuBackedSuggestedAction key="create-pr-action" title={title} menuItemId={itemId} description={description} buttonText={buttonText} discoverabilityContent={this.renderDiscoverabilityElements(menuItem)} type="primary" disabled={!menuItem.enabled} /> ) } private renderActions() { return ( <> <SuggestedActionGroup type="primary" transitions={'replace'} enableTransitions={this.state.enableTransitions} > {this.renderViewStashAction() || this.renderRemoteAction()} </SuggestedActionGroup> <SuggestedActionGroup> {this.renderCreateNewSketchFile()} {this.renderShowInFileManager()} {this.renderViewOnGitHub()} </SuggestedActionGroup> </> ) } public componentDidMount() { this.transitionTimer = window.setTimeout(() => { this.setState({ enableTransitions: true }) this.transitionTimer = null }, 500) } public componentWillUnmount() { if (this.transitionTimer !== null) { clearTimeout(this.transitionTimer) } } public render() { return ( <div id="no-changes"> <div className="content"> <div className="header"> <div className="text"> <h1>No local changes</h1> <p> There are no uncommitted changes in this repository. Here are some friendly suggestions for what to do next. </p> </div> <img src={PaperStackImage} className="blankslate-image" /> </div> {this.renderActions()} </div> {this.props.loadingDiff && <LoadingOverlay />} </div> ) } }
the_stack
import { randomUUID } from 'crypto'; import { getRepository } from 'typeorm'; import TheMovieDb from '../../api/themoviedb'; import { MediaStatus, MediaType } from '../../constants/media'; import Media from '../../entity/Media'; import Season from '../../entity/Season'; import logger from '../../logger'; import AsyncLock from '../../utils/asyncLock'; import { getSettings } from '../settings'; // Default scan rates (can be overidden) const BUNDLE_SIZE = 20; const UPDATE_RATE = 4 * 1000; export type StatusBase = { running: boolean; progress: number; total: number; }; export interface RunnableScanner<T> { run: () => Promise<void>; status: () => T & StatusBase; } export interface MediaIds { tmdbId: number; imdbId?: string; tvdbId?: number; isHama?: boolean; } interface ProcessOptions { is4k?: boolean; mediaAddedAt?: Date; ratingKey?: string; serviceId?: number; externalServiceId?: number; externalServiceSlug?: string; title?: string; processing?: boolean; } export interface ProcessableSeason { seasonNumber: number; totalEpisodes: number; episodes: number; episodes4k: number; is4kOverride?: boolean; processing?: boolean; } class BaseScanner<T> { private bundleSize; private updateRate; protected progress = 0; protected items: T[] = []; protected totalSize?: number = 0; protected scannerName: string; protected enable4kMovie = false; protected enable4kShow = false; protected sessionId: string; protected running = false; readonly asyncLock = new AsyncLock(); readonly tmdb = new TheMovieDb(); protected constructor( scannerName: string, { updateRate, bundleSize, }: { updateRate?: number; bundleSize?: number; } = {} ) { this.scannerName = scannerName; this.bundleSize = bundleSize ?? BUNDLE_SIZE; this.updateRate = updateRate ?? UPDATE_RATE; } private async getExisting(tmdbId: number, mediaType: MediaType) { const mediaRepository = getRepository(Media); const existing = await mediaRepository.findOne({ where: { tmdbId: tmdbId, mediaType }, }); return existing; } protected async processMovie( tmdbId: number, { is4k = false, mediaAddedAt, ratingKey, serviceId, externalServiceId, externalServiceSlug, processing = false, title = 'Unknown Title', }: ProcessOptions = {} ): Promise<void> { const mediaRepository = getRepository(Media); await this.asyncLock.dispatch(tmdbId, async () => { const existing = await this.getExisting(tmdbId, MediaType.MOVIE); if (existing) { let changedExisting = false; if (existing[is4k ? 'status4k' : 'status'] !== MediaStatus.AVAILABLE) { existing[is4k ? 'status4k' : 'status'] = processing ? MediaStatus.PROCESSING : MediaStatus.AVAILABLE; if (mediaAddedAt) { existing.mediaAddedAt = mediaAddedAt; } changedExisting = true; } if (!changedExisting && !existing.mediaAddedAt && mediaAddedAt) { existing.mediaAddedAt = mediaAddedAt; changedExisting = true; } if ( ratingKey && existing[is4k ? 'ratingKey4k' : 'ratingKey'] !== ratingKey ) { existing[is4k ? 'ratingKey4k' : 'ratingKey'] = ratingKey; changedExisting = true; } if ( serviceId !== undefined && existing[is4k ? 'serviceId4k' : 'serviceId'] !== serviceId ) { existing[is4k ? 'serviceId4k' : 'serviceId'] = serviceId; changedExisting = true; } if ( externalServiceId !== undefined && existing[is4k ? 'externalServiceId4k' : 'externalServiceId'] !== externalServiceId ) { existing[is4k ? 'externalServiceId4k' : 'externalServiceId'] = externalServiceId; changedExisting = true; } if ( externalServiceSlug !== undefined && existing[is4k ? 'externalServiceSlug4k' : 'externalServiceSlug'] !== externalServiceSlug ) { existing[is4k ? 'externalServiceSlug4k' : 'externalServiceSlug'] = externalServiceSlug; changedExisting = true; } if (changedExisting) { await mediaRepository.save(existing); this.log( `Media for ${title} exists. Changes were detected and the title will be updated.`, 'info' ); } else { this.log(`Title already exists and no changes detected for ${title}`); } } else { const newMedia = new Media(); newMedia.tmdbId = tmdbId; newMedia.status = !is4k && !processing ? MediaStatus.AVAILABLE : !is4k && processing ? MediaStatus.PROCESSING : MediaStatus.UNKNOWN; newMedia.status4k = is4k && this.enable4kMovie && !processing ? MediaStatus.AVAILABLE : is4k && this.enable4kMovie && processing ? MediaStatus.PROCESSING : MediaStatus.UNKNOWN; newMedia.mediaType = MediaType.MOVIE; newMedia.serviceId = !is4k ? serviceId : undefined; newMedia.serviceId4k = is4k ? serviceId : undefined; newMedia.externalServiceId = !is4k ? externalServiceId : undefined; newMedia.externalServiceId4k = is4k ? externalServiceId : undefined; newMedia.externalServiceSlug = !is4k ? externalServiceSlug : undefined; newMedia.externalServiceSlug4k = is4k ? externalServiceSlug : undefined; if (mediaAddedAt) { newMedia.mediaAddedAt = mediaAddedAt; } if (ratingKey) { newMedia.ratingKey = !is4k ? ratingKey : undefined; newMedia.ratingKey4k = is4k && this.enable4kMovie ? ratingKey : undefined; } await mediaRepository.save(newMedia); this.log(`Saved new media: ${title}`); } }); } /** * processShow takes a TMDb ID and an array of ProcessableSeasons, which * should include the total episodes a sesaon has + the total available * episodes that each season currently has. Unlike processMovie, this method * does not take an `is4k` option. We handle both the 4k _and_ non 4k status * in one method. * * Note: If 4k is not enable, ProcessableSeasons should combine their episode counts * into the normal episodes properties and avoid using the 4k properties. */ protected async processShow( tmdbId: number, tvdbId: number, seasons: ProcessableSeason[], { mediaAddedAt, ratingKey, serviceId, externalServiceId, externalServiceSlug, is4k = false, title = 'Unknown Title', }: ProcessOptions = {} ): Promise<void> { const mediaRepository = getRepository(Media); await this.asyncLock.dispatch(tmdbId, async () => { const media = await this.getExisting(tmdbId, MediaType.TV); const newSeasons: Season[] = []; const currentStandardSeasonsAvailable = ( media?.seasons.filter( (season) => season.status === MediaStatus.AVAILABLE ) ?? [] ).length; const current4kSeasonsAvailable = ( media?.seasons.filter( (season) => season.status4k === MediaStatus.AVAILABLE ) ?? [] ).length; for (const season of seasons) { const existingSeason = media?.seasons.find( (es) => es.seasonNumber === season.seasonNumber ); // We update the rating keys in the seasons loop because we need episode counts if (media && season.episodes > 0 && media.ratingKey !== ratingKey) { media.ratingKey = ratingKey; } if ( media && season.episodes4k > 0 && this.enable4kShow && media.ratingKey4k !== ratingKey ) { media.ratingKey4k = ratingKey; } if (existingSeason) { // Here we update seasons if they already exist. // If the season is already marked as available, we // force it to stay available (to avoid competing scanners) existingSeason.status = (season.totalEpisodes === season.episodes && season.episodes > 0) || existingSeason.status === MediaStatus.AVAILABLE ? MediaStatus.AVAILABLE : season.episodes > 0 ? MediaStatus.PARTIALLY_AVAILABLE : !season.is4kOverride && season.processing ? MediaStatus.PROCESSING : existingSeason.status; // Same thing here, except we only do updates if 4k is enabled existingSeason.status4k = (this.enable4kShow && season.episodes4k === season.totalEpisodes && season.episodes4k > 0) || existingSeason.status4k === MediaStatus.AVAILABLE ? MediaStatus.AVAILABLE : this.enable4kShow && season.episodes4k > 0 ? MediaStatus.PARTIALLY_AVAILABLE : season.is4kOverride && season.processing ? MediaStatus.PROCESSING : existingSeason.status4k; } else { newSeasons.push( new Season({ seasonNumber: season.seasonNumber, status: season.totalEpisodes === season.episodes && season.episodes > 0 ? MediaStatus.AVAILABLE : season.episodes > 0 ? MediaStatus.PARTIALLY_AVAILABLE : !season.is4kOverride && season.processing ? MediaStatus.PROCESSING : MediaStatus.UNKNOWN, status4k: this.enable4kShow && season.totalEpisodes === season.episodes4k && season.episodes4k > 0 ? MediaStatus.AVAILABLE : this.enable4kShow && season.episodes4k > 0 ? MediaStatus.PARTIALLY_AVAILABLE : season.is4kOverride && season.processing ? MediaStatus.PROCESSING : MediaStatus.UNKNOWN, }) ); } } const isAllStandardSeasons = seasons.length && seasons.every( (season) => season.episodes === season.totalEpisodes && season.episodes > 0 ); const isAll4kSeasons = seasons.length && seasons.every( (season) => season.episodes4k === season.totalEpisodes && season.episodes4k > 0 ); if (media) { media.seasons = [...media.seasons, ...newSeasons]; const newStandardSeasonsAvailable = ( media.seasons.filter( (season) => season.status === MediaStatus.AVAILABLE ) ?? [] ).length; const new4kSeasonsAvailable = ( media.seasons.filter( (season) => season.status4k === MediaStatus.AVAILABLE ) ?? [] ).length; // If at least one new season has become available, update // the lastSeasonChange field so we can trigger notifications if (newStandardSeasonsAvailable > currentStandardSeasonsAvailable) { this.log( `Detected ${ newStandardSeasonsAvailable - currentStandardSeasonsAvailable } new standard season(s) for ${title}`, 'debug' ); media.lastSeasonChange = new Date(); if (mediaAddedAt) { media.mediaAddedAt = mediaAddedAt; } } if (new4kSeasonsAvailable > current4kSeasonsAvailable) { this.log( `Detected ${ new4kSeasonsAvailable - current4kSeasonsAvailable } new 4K season(s) for ${title}`, 'debug' ); media.lastSeasonChange = new Date(); } if (!media.mediaAddedAt && mediaAddedAt) { media.mediaAddedAt = mediaAddedAt; } if (serviceId !== undefined) { media[is4k ? 'serviceId4k' : 'serviceId'] = serviceId; } if (externalServiceId !== undefined) { media[is4k ? 'externalServiceId4k' : 'externalServiceId'] = externalServiceId; } if (externalServiceSlug !== undefined) { media[is4k ? 'externalServiceSlug4k' : 'externalServiceSlug'] = externalServiceSlug; } // If the show is already available, and there are no new seasons, dont adjust // the status const shouldStayAvailable = media.status === MediaStatus.AVAILABLE && newSeasons.filter((season) => season.status !== MediaStatus.UNKNOWN) .length === 0; const shouldStayAvailable4k = media.status4k === MediaStatus.AVAILABLE && newSeasons.filter((season) => season.status4k !== MediaStatus.UNKNOWN) .length === 0; media.status = isAllStandardSeasons || shouldStayAvailable ? MediaStatus.AVAILABLE : media.seasons.some( (season) => season.status === MediaStatus.PARTIALLY_AVAILABLE || season.status === MediaStatus.AVAILABLE ) ? MediaStatus.PARTIALLY_AVAILABLE : !seasons.length || media.seasons.some( (season) => season.status === MediaStatus.PROCESSING ) ? MediaStatus.PROCESSING : MediaStatus.UNKNOWN; media.status4k = (isAll4kSeasons || shouldStayAvailable4k) && this.enable4kShow ? MediaStatus.AVAILABLE : this.enable4kShow && media.seasons.some( (season) => season.status4k === MediaStatus.PARTIALLY_AVAILABLE || season.status4k === MediaStatus.AVAILABLE ) ? MediaStatus.PARTIALLY_AVAILABLE : !seasons.length || media.seasons.some( (season) => season.status4k === MediaStatus.PROCESSING ) ? MediaStatus.PROCESSING : MediaStatus.UNKNOWN; await mediaRepository.save(media); this.log(`Updating existing title: ${title}`); } else { const newMedia = new Media({ mediaType: MediaType.TV, seasons: newSeasons, tmdbId, tvdbId, mediaAddedAt, serviceId: !is4k ? serviceId : undefined, serviceId4k: is4k ? serviceId : undefined, externalServiceId: !is4k ? externalServiceId : undefined, externalServiceId4k: is4k ? externalServiceId : undefined, externalServiceSlug: !is4k ? externalServiceSlug : undefined, externalServiceSlug4k: is4k ? externalServiceSlug : undefined, ratingKey: newSeasons.some( (sn) => sn.status === MediaStatus.PARTIALLY_AVAILABLE || sn.status === MediaStatus.AVAILABLE ) ? ratingKey : undefined, ratingKey4k: this.enable4kShow && newSeasons.some( (sn) => sn.status4k === MediaStatus.PARTIALLY_AVAILABLE || sn.status4k === MediaStatus.AVAILABLE ) ? ratingKey : undefined, status: isAllStandardSeasons ? MediaStatus.AVAILABLE : newSeasons.some( (season) => season.status === MediaStatus.PARTIALLY_AVAILABLE || season.status === MediaStatus.AVAILABLE ) ? MediaStatus.PARTIALLY_AVAILABLE : newSeasons.some( (season) => season.status === MediaStatus.PROCESSING ) ? MediaStatus.PROCESSING : MediaStatus.UNKNOWN, status4k: isAll4kSeasons && this.enable4kShow ? MediaStatus.AVAILABLE : this.enable4kShow && newSeasons.some( (season) => season.status4k === MediaStatus.PARTIALLY_AVAILABLE || season.status4k === MediaStatus.AVAILABLE ) ? MediaStatus.PARTIALLY_AVAILABLE : newSeasons.some( (season) => season.status4k === MediaStatus.PROCESSING ) ? MediaStatus.PROCESSING : MediaStatus.UNKNOWN, }); await mediaRepository.save(newMedia); this.log(`Saved ${title}`); } }); } /** * Call startRun from child class whenever a run is starting to * ensure required values are set * * Returns the session ID which is requried for the cleanup method */ protected startRun(): string { const settings = getSettings(); const sessionId = randomUUID(); this.sessionId = sessionId; this.log('Scan starting', 'info', { sessionId }); this.enable4kMovie = settings.radarr.some((radarr) => radarr.is4k); if (this.enable4kMovie) { this.log( 'At least one 4K Radarr server was detected. 4K movie detection is now enabled', 'info' ); } this.enable4kShow = settings.sonarr.some((sonarr) => sonarr.is4k); if (this.enable4kShow) { this.log( 'At least one 4K Sonarr server was detected. 4K series detection is now enabled', 'info' ); } this.running = true; return sessionId; } /** * Call at end of run loop to perform cleanup */ protected endRun(sessionId: string): void { if (this.sessionId === sessionId) { this.running = false; } } public cancel(): void { this.running = false; } protected async loop( processFn: (item: T) => Promise<void>, { start = 0, end = this.bundleSize, sessionId, }: { start?: number; end?: number; sessionId?: string; } = {} ): Promise<void> { const slicedItems = this.items.slice(start, end); if (!this.running) { throw new Error('Sync was aborted.'); } if (this.sessionId !== sessionId) { throw new Error('New session was started. Old session aborted.'); } if (start < this.items.length) { this.progress = start; await this.processItems(processFn, slicedItems); await new Promise<void>((resolve, reject) => setTimeout(() => { this.loop(processFn, { start: start + this.bundleSize, end: end + this.bundleSize, sessionId, }) .then(() => resolve()) .catch((e) => reject(new Error(e.message))); }, this.updateRate) ); } } private async processItems( processFn: (items: T) => Promise<void>, items: T[] ) { await Promise.all( items.map(async (item) => { await processFn(item); }) ); } protected log( message: string, level: 'info' | 'error' | 'debug' | 'warn' = 'debug', optional?: Record<string, unknown> ): void { logger[level](message, { label: this.scannerName, ...optional }); } get protectedUpdateRate(): number { return this.updateRate; } get protectedBundleSize(): number { return this.bundleSize; } } export default BaseScanner;
the_stack
import * as crypto from 'crypto' import * as fs from 'fs-extra' import * as path from 'path' import archiver from 'archiver' import * as glob from 'glob' import {Builder, PreRenderedManifest} from '@sls-next/lambda-at-edge' const nextBuildDir = '.ness/.next' const nextLambdaDir = '.ness/.next/__lambdas' export type DynamicPageKeyValue = { [key: string]: { file: string regex: string } } export type OriginRequestApiHandlerManifest = { apis: { dynamic: DynamicPageKeyValue nonDynamic: { [key: string]: string } } domainRedirects: { [key: string]: string } enableHTTPCompression: boolean authentication?: { username: string password: string } } export type OriginRequestDefaultHandlerManifest = { buildId: string logLambdaExecutionTimes: boolean pages: { ssr: { dynamic: DynamicPageKeyValue nonDynamic: { [key: string]: string } } html: { nonDynamic: { [path: string]: string } dynamic: DynamicPageKeyValue } ssg: { nonDynamic: { [path: string]: unknown } dynamic: { [path: string]: unknown } } } publicFiles: { [key: string]: string } trailingSlash: boolean enableHTTPCompression: boolean domainRedirects: { [key: string]: string } authentication?: { username: string password: string } } export type OriginRequestImageHandlerManifest = { enableHTTPCompression: boolean domainRedirects: { [key: string]: string } } export type RedirectData = { statusCode: number source: string destination: string regex: string internal?: boolean } export type RewriteData = { source: string destination: string regex: string } export type Header = { key: string value: string } export type HeaderData = { source: string headers: Header[] regex: string } export type I18nData = { locales: string[] defaultLocale: string } export type RoutesManifest = { basePath: string redirects: RedirectData[] rewrites: RewriteData[] headers: HeaderData[] i18n?: I18nData } const PUBLIC_DIR_CACHE_CONTROL = 'public, max-age=31536000, must-revalidate' const IMMUTABLE_CACHE_CONTROL = 'public, max-age=31536000, immutable' const SERVER_CACHE_CONTROL = 'public, max-age=0, s-maxage=2678400, must-revalidate' type CacheConfig = Record< string, { cacheControl: string path: string prefix: string } > const filterNonExistentPathKeys = (config: CacheConfig) => { return Object.keys(config).reduce( (newConfig, nextConfigKey) => ({ ...newConfig, ...(fs.pathExistsSync(config[nextConfigKey].path) ? {[nextConfigKey]: config[nextConfigKey]} : {}), }), {} as CacheConfig, ) } const readAssetsDirectory = (dir: string): CacheConfig => { const publicFiles = path.join(dir, 'public') const staticFiles = path.join(dir, 'static') const staticPages = path.join(dir, 'static-pages') const nextData = path.join(dir, '_next', 'data') const nextStatic = path.join(dir, '_next', 'static') return filterNonExistentPathKeys({ publicFiles: { path: publicFiles, cacheControl: PUBLIC_DIR_CACHE_CONTROL, prefix: path.relative(dir, publicFiles) + '/', }, staticFiles: { path: staticFiles, cacheControl: PUBLIC_DIR_CACHE_CONTROL, prefix: path.relative(dir, staticFiles) + '/', }, staticPages: { path: staticPages, cacheControl: SERVER_CACHE_CONTROL, prefix: path.relative(dir, staticPages) + '/', }, nextData: { path: nextData, cacheControl: SERVER_CACHE_CONTROL, prefix: path.relative(dir, nextData) + '/', }, nextStatic: { path: nextStatic, cacheControl: IMMUTABLE_CACHE_CONTROL, prefix: path.relative(dir, nextStatic) + '/', }, }) } /** * We don't need to invalidate sub paths if a parent has a wild card * invalidation. i.e. if `/users/*` exists, we don't need to invalidate `/users/details/*` */ export const reduceInvalidationPaths = (invalidationPaths: string[]): string[] => { const wildCardDirectories = invalidationPaths .filter((invalidationPath) => invalidationPath.endsWith('/*')) .map((invalidationPath) => invalidationPath.replace('/*', '')) return invalidationPaths.filter((invalidationPath) => { return !wildCardDirectories.some( (wildCardDirectory) => invalidationPath.startsWith(wildCardDirectory) && invalidationPath !== `${wildCardDirectory}*` && invalidationPath !== `${wildCardDirectory}/*` && wildCardDirectory !== invalidationPath, ) }) } const dynamicPathToInvalidationPath = (dynamicPath: string) => { const [base] = dynamicPath.split('/:') const [firstSegment] = base.split('/[') // Ensure this is posix path as CloudFront needs forward slash in invalidation return path.posix.join(firstSegment || '/', '*') } export const readInvalidationPathsFromManifest = ( manifest: OriginRequestDefaultHandlerManifest, ): string[] => { return [ ...Object.keys(manifest.pages.html.dynamic).map(dynamicPathToInvalidationPath), ...Object.keys(manifest.pages.html.nonDynamic), ...Object.keys(manifest.pages.ssr.dynamic).map(dynamicPathToInvalidationPath), ...Object.keys(manifest.pages.ssr.nonDynamic), ...Object.keys(manifest.pages.ssg?.dynamic || {}).map(dynamicPathToInvalidationPath), ...Object.keys(manifest.pages.ssg?.nonDynamic || {}), ] } async function readJsonFile<T>(pathToFile: string): Promise<T | undefined> { try { await fs.access(pathToFile) const contents = await fs.readFile(pathToFile, {encoding: 'utf-8'}) return JSON.parse(contents) as T } catch { return undefined } } const getNextApiBuildManifest = async (): Promise<OriginRequestApiHandlerManifest | undefined> => { return readJsonFile(path.join(nextBuildDir, 'api-lambda/manifest.json')) } const getNextDefaultManifest = async (): Promise< OriginRequestDefaultHandlerManifest | undefined > => { return readJsonFile(path.join(nextBuildDir, 'default-lambda/manifest.json')) } const getNextImageBuildManifest = async (): Promise< OriginRequestImageHandlerManifest | undefined > => { return readJsonFile(path.join(nextBuildDir, 'image-lambda/manifest.json')) } const getNextRoutesManifest = async (): Promise<RoutesManifest | undefined> => { return readJsonFile(path.join(nextBuildDir, 'default-lambda/routes-manifest.json')) } const getNextPrerenderManifest = async (): Promise<PreRenderedManifest | undefined> => { return readJsonFile(path.join(nextBuildDir, 'default-lambda/prerender-manifest.json')) } function zipDirectory(directory: string, outputFile: string): Promise<string> { return new Promise(async (resolve, reject) => { // The below options are needed to support following symlinks when building zip files: // - nodir: This will prevent symlinks themselves from being copied into the zip. // - follow: This will follow symlinks and copy the files within. const globOptions = { dot: true, nodir: true, follow: true, cwd: directory, } const files = glob.sync('**', globOptions) // The output here is already sorted const shasum = crypto.createHash('sha256') const output = fs.createWriteStream(outputFile) const archive = archiver('zip') archive.on('warning', reject) archive.on('error', reject) archive.on('data', (data) => { shasum.update(data) }) // archive has been finalized and the output file descriptor has closed, resolve promise // this has to be done before calling `finalize` since the events may fire immediately after. // see https://www.npmjs.com/package/archiver output.once('close', () => { const hash = shasum.digest('hex') resolve(hash) }) archive.pipe(output) // Append files serially to ensure file order for (const file of files) { const fullPath = path.resolve(directory, file) const [data, stat] = await Promise.all([fs.readFile(fullPath), fs.stat(fullPath)]) archive.append(data, { name: file, mode: stat.mode, }) } await archive.finalize() }) } export type NextBuild = { lambdaBuildDir: string defaultLambdaPath: string imageLambdaPath?: string apiLambdaPath?: string regenerationLambdaPath?: string assets: CacheConfig basePath: string staticPath: string dataPath: string imagePath?: string apiPath?: string invalidationPaths?: string[] } export const buildNextApp = async (entry: string = process.cwd()): Promise<NextBuild> => { const buildDir = path.resolve(entry, nextBuildDir) await fs.remove(buildDir) const builder = new Builder(entry, nextBuildDir, {args: ['build']}) await builder.build() const [ defaultManifest, apiBuildManifest, imageBuildManifest, routesManifest, prerenderManifest, ] = await Promise.all([ getNextDefaultManifest(), getNextApiBuildManifest(), getNextImageBuildManifest(), getNextRoutesManifest(), getNextPrerenderManifest(), ]) const lambdaBuildDir = path.resolve(entry, nextLambdaDir) await fs.mkdir(lambdaBuildDir, {recursive: true}) const zipLambda = async (lambdaName: string): Promise<string> => { const zipped = path.join(lambdaBuildDir, `${lambdaName}.zip`) const hash = await zipDirectory(path.join(buildDir, lambdaName), zipped) const output = path.join(lambdaBuildDir, `${lambdaName}.${hash}.zip`) await fs.rename(zipped, output) return path.basename(output) } const pathPattern = (pattern: string): string => { const {basePath} = routesManifest || {} return basePath && basePath.length > 0 ? `${basePath.slice(1)}/${pattern}` : pattern } const defaultLambdaPath = await zipLambda('default-lambda') let apiLambdaPath = undefined let imageLambdaPath = undefined let regenerationLambdaPath = undefined const apis = apiBuildManifest?.apis const hasApi = apis && (Object.keys(apis.nonDynamic).length > 0 || Object.keys(apis.dynamic).length > 0) if (hasApi) { apiLambdaPath = await zipLambda('api-lambda') } const hasImages = !!imageBuildManifest if (hasImages) { imageLambdaPath = await zipLambda('image-lambda') } const hasISRPages = prerenderManifest && Object.keys(prerenderManifest.routes).some( (key) => typeof prerenderManifest.routes[key].initialRevalidateSeconds === 'number', ) if (hasISRPages) { regenerationLambdaPath = await zipLambda('regeneration-lambda') } const assetsDir = path.join(buildDir, 'assets') const assets = readAssetsDirectory(assetsDir) return { lambdaBuildDir, defaultLambdaPath, apiLambdaPath, imageLambdaPath, regenerationLambdaPath, assets, imagePath: hasImages ? pathPattern('_next/image*') : undefined, dataPath: pathPattern('_next/data/*'), basePath: pathPattern('_next/*'), staticPath: pathPattern('static/*'), apiPath: hasApi ? pathPattern('api/*') : undefined, invalidationPaths: defaultManifest ? reduceInvalidationPaths(readInvalidationPathsFromManifest(defaultManifest)) : undefined, } }
the_stack
import { b2_maxManifoldPoints } from "../common/b2_settings.js"; import { b2Min, b2Vec2, b2Rot, b2Transform } from "../common/b2_math.js"; import { b2ContactFeatureType, b2ContactID } from "./b2_collision.js"; import { b2Manifold, b2ManifoldType, b2ManifoldPoint, b2ClipVertex, b2ClipSegmentToLine } from "./b2_collision.js"; import { b2CircleShape } from "./b2_circle_shape.js"; import { b2PolygonShape } from "./b2_polygon_shape.js"; import { b2EdgeShape } from "./b2_edge_shape.js"; const b2CollideEdgeAndCircle_s_Q: b2Vec2 = new b2Vec2(); const b2CollideEdgeAndCircle_s_e: b2Vec2 = new b2Vec2(); const b2CollideEdgeAndCircle_s_d: b2Vec2 = new b2Vec2(); const b2CollideEdgeAndCircle_s_e1: b2Vec2 = new b2Vec2(); const b2CollideEdgeAndCircle_s_e2: b2Vec2 = new b2Vec2(); const b2CollideEdgeAndCircle_s_P: b2Vec2 = new b2Vec2(); const b2CollideEdgeAndCircle_s_n: b2Vec2 = new b2Vec2(); const b2CollideEdgeAndCircle_s_id: b2ContactID = new b2ContactID(); export function b2CollideEdgeAndCircle(manifold: b2Manifold, edgeA: b2EdgeShape, xfA: b2Transform, circleB: b2CircleShape, xfB: b2Transform): void { manifold.pointCount = 0; // Compute circle in frame of edge const Q: b2Vec2 = b2Transform.MulTXV(xfA, b2Transform.MulXV(xfB, circleB.m_p, b2Vec2.s_t0), b2CollideEdgeAndCircle_s_Q); const A: b2Vec2 = edgeA.m_vertex1; const B: b2Vec2 = edgeA.m_vertex2; const e: b2Vec2 = b2Vec2.SubVV(B, A, b2CollideEdgeAndCircle_s_e); // Normal points to the right for a CCW winding // b2Vec2 n(e.y, -e.x); // const n: b2Vec2 = b2CollideEdgeAndCircle_s_n.Set(-e.y, e.x); const n: b2Vec2 = b2CollideEdgeAndCircle_s_n.Set(e.y, -e.x); // float offset = b2Dot(n, Q - A); const offset: number = b2Vec2.DotVV(n, b2Vec2.SubVV(Q, A, b2Vec2.s_t0)); const oneSided: boolean = edgeA.m_oneSided; if (oneSided && offset < 0.0) { return; } // Barycentric coordinates const u: number = b2Vec2.DotVV(e, b2Vec2.SubVV(B, Q, b2Vec2.s_t0)); const v: number = b2Vec2.DotVV(e, b2Vec2.SubVV(Q, A, b2Vec2.s_t0)); const radius: number = edgeA.m_radius + circleB.m_radius; // const cf: b2ContactFeature = new b2ContactFeature(); const id: b2ContactID = b2CollideEdgeAndCircle_s_id; id.cf.indexB = 0; id.cf.typeB = b2ContactFeatureType.e_vertex; // Region A if (v <= 0) { const P: b2Vec2 = A; const d: b2Vec2 = b2Vec2.SubVV(Q, P, b2CollideEdgeAndCircle_s_d); const dd: number = b2Vec2.DotVV(d, d); if (dd > radius * radius) { return; } // Is there an edge connected to A? if (edgeA.m_oneSided) { const A1: b2Vec2 = edgeA.m_vertex0; const B1: b2Vec2 = A; const e1: b2Vec2 = b2Vec2.SubVV(B1, A1, b2CollideEdgeAndCircle_s_e1); const u1: number = b2Vec2.DotVV(e1, b2Vec2.SubVV(B1, Q, b2Vec2.s_t0)); // Is the circle in Region AB of the previous edge? if (u1 > 0) { return; } } id.cf.indexA = 0; id.cf.typeA = b2ContactFeatureType.e_vertex; manifold.pointCount = 1; manifold.type = b2ManifoldType.e_circles; manifold.localNormal.SetZero(); manifold.localPoint.Copy(P); manifold.points[0].id.Copy(id); // manifold.points[0].id.key = 0; // manifold.points[0].id.cf = cf; manifold.points[0].localPoint.Copy(circleB.m_p); return; } // Region B if (u <= 0) { const P: b2Vec2 = B; const d: b2Vec2 = b2Vec2.SubVV(Q, P, b2CollideEdgeAndCircle_s_d); const dd: number = b2Vec2.DotVV(d, d); if (dd > radius * radius) { return; } // Is there an edge connected to B? if (edgeA.m_oneSided) { const B2: b2Vec2 = edgeA.m_vertex3; const A2: b2Vec2 = B; const e2: b2Vec2 = b2Vec2.SubVV(B2, A2, b2CollideEdgeAndCircle_s_e2); const v2: number = b2Vec2.DotVV(e2, b2Vec2.SubVV(Q, A2, b2Vec2.s_t0)); // Is the circle in Region AB of the next edge? if (v2 > 0) { return; } } id.cf.indexA = 1; id.cf.typeA = b2ContactFeatureType.e_vertex; manifold.pointCount = 1; manifold.type = b2ManifoldType.e_circles; manifold.localNormal.SetZero(); manifold.localPoint.Copy(P); manifold.points[0].id.Copy(id); // manifold.points[0].id.key = 0; // manifold.points[0].id.cf = cf; manifold.points[0].localPoint.Copy(circleB.m_p); return; } // Region AB const den: number = b2Vec2.DotVV(e, e); // DEBUG: b2Assert(den > 0); const P: b2Vec2 = b2CollideEdgeAndCircle_s_P; P.x = (1 / den) * (u * A.x + v * B.x); P.y = (1 / den) * (u * A.y + v * B.y); const d: b2Vec2 = b2Vec2.SubVV(Q, P, b2CollideEdgeAndCircle_s_d); const dd: number = b2Vec2.DotVV(d, d); if (dd > radius * radius) { return; } if (offset < 0) { n.Set(-n.x, -n.y); } n.Normalize(); id.cf.indexA = 0; id.cf.typeA = b2ContactFeatureType.e_face; manifold.pointCount = 1; manifold.type = b2ManifoldType.e_faceA; manifold.localNormal.Copy(n); manifold.localPoint.Copy(A); manifold.points[0].id.Copy(id); // manifold.points[0].id.key = 0; // manifold.points[0].id.cf = cf; manifold.points[0].localPoint.Copy(circleB.m_p); } enum b2EPAxisType { e_unknown = 0, e_edgeA = 1, e_edgeB = 2, } class b2EPAxis { public normal: b2Vec2 = new b2Vec2(); public type: b2EPAxisType = b2EPAxisType.e_unknown; public index: number = 0; public separation: number = 0; } class b2TempPolygon { public vertices: b2Vec2[] = []; public normals: b2Vec2[] = []; public count: number = 0; } class b2ReferenceFace { public i1: number = 0; public i2: number = 0; public readonly v1: b2Vec2 = new b2Vec2(); public readonly v2: b2Vec2 = new b2Vec2(); public readonly normal: b2Vec2 = new b2Vec2(); public readonly sideNormal1: b2Vec2 = new b2Vec2(); public sideOffset1: number = 0; public readonly sideNormal2: b2Vec2 = new b2Vec2(); public sideOffset2: number = 0; } // static b2EPAxis b2ComputeEdgeSeparation(const b2TempPolygon& polygonB, const b2Vec2& v1, const b2Vec2& normal1) const b2ComputeEdgeSeparation_s_axis = new b2EPAxis(); const b2ComputeEdgeSeparation_s_axes: [ b2Vec2, b2Vec2 ] = [ new b2Vec2(), new b2Vec2() ]; function b2ComputeEdgeSeparation(polygonB: Readonly<b2TempPolygon>, v1: Readonly<b2Vec2>, normal1: Readonly<b2Vec2>): b2EPAxis { // b2EPAxis axis; const axis: b2EPAxis = b2ComputeEdgeSeparation_s_axis; axis.type = b2EPAxisType.e_edgeA; axis.index = -1; axis.separation = -Number.MAX_VALUE; // -FLT_MAX; axis.normal.SetZero(); // b2Vec2 axes[2] = { normal1, -normal1 }; const axes: [b2Vec2, b2Vec2] = b2ComputeEdgeSeparation_s_axes; axes[0].Copy(normal1); axes[1].Copy(normal1).SelfNeg(); // Find axis with least overlap (min-max problem) for (let j = 0; j < 2; ++j) { let sj: number = Number.MAX_VALUE; // FLT_MAX; // Find deepest polygon vertex along axis j for (let i = 0; i < polygonB.count; ++i) { // float si = b2Dot(axes[j], polygonB.vertices[i] - v1); const si: number = b2Vec2.DotVV(axes[j], b2Vec2.SubVV(polygonB.vertices[i], v1, b2Vec2.s_t0)); if (si < sj) { sj = si; } } if (sj > axis.separation) { axis.index = j; axis.separation = sj; axis.normal.Copy(axes[j]); } } return axis; } // static b2EPAxis b2ComputePolygonSeparation(const b2TempPolygon& polygonB, const b2Vec2& v1, const b2Vec2& v2) const b2ComputePolygonSeparation_s_axis = new b2EPAxis(); const b2ComputePolygonSeparation_s_n = new b2Vec2(); function b2ComputePolygonSeparation(polygonB: Readonly<b2TempPolygon>, v1: Readonly<b2Vec2>, v2: Readonly<b2Vec2>): b2EPAxis { const axis: b2EPAxis = b2ComputePolygonSeparation_s_axis; axis.type = b2EPAxisType.e_unknown; axis.index = -1; axis.separation = -Number.MAX_VALUE; // -FLT_MAX; axis.normal.SetZero(); for (let i = 0; i < polygonB.count; ++i) { // b2Vec2 n = -polygonB.normals[i]; const n: b2Vec2 = b2Vec2.NegV(polygonB.normals[i], b2ComputePolygonSeparation_s_n); // float s1 = b2Dot(n, polygonB.vertices[i] - v1); const s1: number = b2Vec2.DotVV(n, b2Vec2.SubVV(polygonB.vertices[i], v1, b2Vec2.s_t0)); // float s2 = b2Dot(n, polygonB.vertices[i] - v2); const s2: number = b2Vec2.DotVV(n, b2Vec2.SubVV(polygonB.vertices[i], v2, b2Vec2.s_t0)); // float s = b2Min(s1, s2); const s: number = b2Min(s1, s2); if (s > axis.separation) { axis.type = b2EPAxisType.e_edgeB; axis.index = i; axis.separation = s; axis.normal.Copy(n); } } return axis; } const b2CollideEdgeAndPolygon_s_xf = new b2Transform(); const b2CollideEdgeAndPolygon_s_centroidB = new b2Vec2(); const b2CollideEdgeAndPolygon_s_edge1 = new b2Vec2(); const b2CollideEdgeAndPolygon_s_normal1 = new b2Vec2(); const b2CollideEdgeAndPolygon_s_edge0 = new b2Vec2(); const b2CollideEdgeAndPolygon_s_normal0 = new b2Vec2(); const b2CollideEdgeAndPolygon_s_edge2 = new b2Vec2(); const b2CollideEdgeAndPolygon_s_normal2 = new b2Vec2(); const b2CollideEdgeAndPolygon_s_tempPolygonB = new b2TempPolygon(); const b2CollideEdgeAndPolygon_s_ref = new b2ReferenceFace(); const b2CollideEdgeAndPolygon_s_clipPoints: [b2ClipVertex, b2ClipVertex] = [ new b2ClipVertex(), new b2ClipVertex() ]; const b2CollideEdgeAndPolygon_s_clipPoints1: [b2ClipVertex, b2ClipVertex] = [ new b2ClipVertex(), new b2ClipVertex() ]; const b2CollideEdgeAndPolygon_s_clipPoints2: [b2ClipVertex, b2ClipVertex] = [ new b2ClipVertex(), new b2ClipVertex() ]; export function b2CollideEdgeAndPolygon(manifold: b2Manifold, edgeA: b2EdgeShape, xfA: b2Transform, polygonB: b2PolygonShape, xfB: b2Transform): void { manifold.pointCount = 0; // b2Transform xf = b2MulT(xfA, xfB); const xf = b2Transform.MulTXX(xfA, xfB, b2CollideEdgeAndPolygon_s_xf); // b2Vec2 centroidB = b2Mul(xf, polygonB.m_centroid); const centroidB: b2Vec2 = b2Transform.MulXV(xf, polygonB.m_centroid, b2CollideEdgeAndPolygon_s_centroidB); // b2Vec2 v1 = edgeA.m_vertex1; const v1: b2Vec2 = edgeA.m_vertex1; // b2Vec2 v2 = edgeA.m_vertex2; const v2: b2Vec2 = edgeA.m_vertex2; // b2Vec2 edge1 = v2 - v1; const edge1: b2Vec2 = b2Vec2.SubVV(v2, v1, b2CollideEdgeAndPolygon_s_edge1); edge1.Normalize(); // Normal points to the right for a CCW winding // b2Vec2 normal1(edge1.y, -edge1.x); const normal1 = b2CollideEdgeAndPolygon_s_normal1.Set(edge1.y, -edge1.x); // float offset1 = b2Dot(normal1, centroidB - v1); const offset1: number = b2Vec2.DotVV(normal1, b2Vec2.SubVV(centroidB, v1, b2Vec2.s_t0)); const oneSided: boolean = edgeA.m_oneSided; if (oneSided && offset1 < 0.0) { return; } // Get polygonB in frameA // b2TempPolygon tempPolygonB; const tempPolygonB: b2TempPolygon = b2CollideEdgeAndPolygon_s_tempPolygonB; tempPolygonB.count = polygonB.m_count; for (let i = 0; i < polygonB.m_count; ++i) { if (tempPolygonB.vertices.length <= i) { tempPolygonB.vertices.push(new b2Vec2()); } if (tempPolygonB.normals.length <= i) { tempPolygonB.normals.push(new b2Vec2()); } // tempPolygonB.vertices[i] = b2Mul(xf, polygonB.m_vertices[i]); b2Transform.MulXV(xf, polygonB.m_vertices[i], tempPolygonB.vertices[i]); // tempPolygonB.normals[i] = b2Mul(xf.q, polygonB.m_normals[i]); b2Rot.MulRV(xf.q, polygonB.m_normals[i], tempPolygonB.normals[i]); } const radius: number = polygonB.m_radius + edgeA.m_radius; // b2EPAxis edgeAxis = b2ComputeEdgeSeparation(tempPolygonB, v1, normal1); const edgeAxis: b2EPAxis = b2ComputeEdgeSeparation(tempPolygonB, v1, normal1); if (edgeAxis.separation > radius) { return; } // b2EPAxis polygonAxis = b2ComputePolygonSeparation(tedge0.y, -edge0.xempPolygonB, v1, v2); const polygonAxis: b2EPAxis = b2ComputePolygonSeparation(tempPolygonB, v1, v2); if (polygonAxis.separation > radius) { return; } // Use hysteresis for jitter reduction. const k_relativeTol: number = 0.98; const k_absoluteTol: number = 0.001; // b2EPAxis primaryAxis; let primaryAxis: b2EPAxis; if (polygonAxis.separation - radius > k_relativeTol * (edgeAxis.separation - radius) + k_absoluteTol) { primaryAxis = polygonAxis; } else { primaryAxis = edgeAxis; } if (oneSided) { // Smooth collision // See https://box2d.org/posts/2020/06/ghost-collisions/ // b2Vec2 edge0 = v1 - edgeA.m_vertex0; const edge0: b2Vec2 = b2Vec2.SubVV(v1, edgeA.m_vertex0, b2CollideEdgeAndPolygon_s_edge0); edge0.Normalize(); // b2Vec2 normal0(edge0.y, -edge0.x); const normal0: b2Vec2 = b2CollideEdgeAndPolygon_s_normal0.Set(edge0.y, -edge0.x); const convex1: boolean = b2Vec2.CrossVV(edge0, edge1) >= 0.0; // b2Vec2 edge2 = edgeA.m_vertex3 - v2; const edge2: b2Vec2 = b2Vec2.SubVV(edgeA.m_vertex3, v2, b2CollideEdgeAndPolygon_s_edge2); edge2.Normalize(); // b2Vec2 normal2(edge2.y, -edge2.x); const normal2: b2Vec2 = b2CollideEdgeAndPolygon_s_normal2.Set(edge2.y, -edge2.x); const convex2: boolean = b2Vec2.CrossVV(edge1, edge2) >= 0.0; const sinTol: number = 0.1; const side1: boolean = b2Vec2.DotVV(primaryAxis.normal, edge1) <= 0.0; // Check Gauss Map if (side1) { if (convex1) { if (b2Vec2.CrossVV(primaryAxis.normal, normal0) > sinTol) { // Skip region return; } // Admit region } else { // Snap region primaryAxis = edgeAxis; } } else { if (convex2) { if (b2Vec2.CrossVV(normal2, primaryAxis.normal) > sinTol) { // Skip region return; } // Admit region } else { // Snap region primaryAxis = edgeAxis; } } } // b2ClipVertex clipPoints[2]; const clipPoints: [b2ClipVertex, b2ClipVertex] = b2CollideEdgeAndPolygon_s_clipPoints; // b2ReferenceFace ref; const ref: b2ReferenceFace = b2CollideEdgeAndPolygon_s_ref; if (primaryAxis.type === b2EPAxisType.e_edgeA) { manifold.type = b2ManifoldType.e_faceA; // Search for the polygon normal that is most anti-parallel to the edge normal. let bestIndex: number = 0; let bestValue: number = b2Vec2.DotVV(primaryAxis.normal, tempPolygonB.normals[0]); for (let i = 1; i < tempPolygonB.count; ++i) { const value: number = b2Vec2.DotVV(primaryAxis.normal, tempPolygonB.normals[i]); if (value < bestValue) { bestValue = value; bestIndex = i; } } const i1: number = bestIndex; const i2: number = i1 + 1 < tempPolygonB.count ? i1 + 1 : 0; clipPoints[0].v.Copy(tempPolygonB.vertices[i1]); clipPoints[0].id.cf.indexA = 0; clipPoints[0].id.cf.indexB = i1; clipPoints[0].id.cf.typeA = b2ContactFeatureType.e_face; clipPoints[0].id.cf.typeB = b2ContactFeatureType.e_vertex; clipPoints[1].v.Copy(tempPolygonB.vertices[i2]); clipPoints[1].id.cf.indexA = 0; clipPoints[1].id.cf.indexB = i2; clipPoints[1].id.cf.typeA = b2ContactFeatureType.e_face; clipPoints[1].id.cf.typeB = b2ContactFeatureType.e_vertex; ref.i1 = 0; ref.i2 = 1; ref.v1.Copy(v1); ref.v2.Copy(v2); ref.normal.Copy(primaryAxis.normal); ref.sideNormal1.Copy(edge1).SelfNeg(); // ref.sideNormal1 = -edge1; ref.sideNormal2.Copy(edge1); } else { manifold.type = b2ManifoldType.e_faceB; clipPoints[0].v.Copy(v2); clipPoints[0].id.cf.indexA = 1; clipPoints[0].id.cf.indexB = primaryAxis.index; clipPoints[0].id.cf.typeA = b2ContactFeatureType.e_vertex; clipPoints[0].id.cf.typeB = b2ContactFeatureType.e_face; clipPoints[1].v.Copy(v1); clipPoints[1].id.cf.indexA = 0; clipPoints[1].id.cf.indexB = primaryAxis.index; clipPoints[1].id.cf.typeA = b2ContactFeatureType.e_vertex; clipPoints[1].id.cf.typeB = b2ContactFeatureType.e_face; ref.i1 = primaryAxis.index; ref.i2 = ref.i1 + 1 < tempPolygonB.count ? ref.i1 + 1 : 0; ref.v1.Copy(tempPolygonB.vertices[ref.i1]); ref.v2.Copy(tempPolygonB.vertices[ref.i2]); ref.normal.Copy(tempPolygonB.normals[ref.i1]); // CCW winding ref.sideNormal1.Set(ref.normal.y, -ref.normal.x); ref.sideNormal2.Copy(ref.sideNormal1).SelfNeg(); // ref.sideNormal2 = -ref.sideNormal1; } ref.sideOffset1 = b2Vec2.DotVV(ref.sideNormal1, ref.v1); ref.sideOffset2 = b2Vec2.DotVV(ref.sideNormal2, ref.v2); // Clip incident edge against reference face side planes // b2ClipVertex clipPoints1[2]; const clipPoints1: [b2ClipVertex, b2ClipVertex] = b2CollideEdgeAndPolygon_s_clipPoints1; // [new b2ClipVertex(), new b2ClipVertex()]; // b2ClipVertex clipPoints2[2]; const clipPoints2: [b2ClipVertex, b2ClipVertex] = b2CollideEdgeAndPolygon_s_clipPoints2; // [new b2ClipVertex(), new b2ClipVertex()]; // int32 np; let np: number; // Clip to side 1 np = b2ClipSegmentToLine(clipPoints1, clipPoints, ref.sideNormal1, ref.sideOffset1, ref.i1); if (np < b2_maxManifoldPoints) { return; } // Clip to side 2 np = b2ClipSegmentToLine(clipPoints2, clipPoints1, ref.sideNormal2, ref.sideOffset2, ref.i2); if (np < b2_maxManifoldPoints) { return; } // Now clipPoints2 contains the clipped points. if (primaryAxis.type === b2EPAxisType.e_edgeA) { manifold.localNormal.Copy(ref.normal); manifold.localPoint.Copy(ref.v1); } else { manifold.localNormal.Copy(polygonB.m_normals[ref.i1]); manifold.localPoint.Copy(polygonB.m_vertices[ref.i1]); } let pointCount = 0; for (let i = 0; i < b2_maxManifoldPoints; ++i) { const separation: number = b2Vec2.DotVV(ref.normal, b2Vec2.SubVV(clipPoints2[i].v, ref.v1, b2Vec2.s_t0)); if (separation <= radius) { const cp: b2ManifoldPoint = manifold.points[pointCount]; if (primaryAxis.type === b2EPAxisType.e_edgeA) { b2Transform.MulTXV(xf, clipPoints2[i].v, cp.localPoint); // cp.localPoint = b2MulT(xf, clipPoints2[i].v); cp.id.Copy(clipPoints2[i].id); } else { cp.localPoint.Copy(clipPoints2[i].v); cp.id.cf.typeA = clipPoints2[i].id.cf.typeB; cp.id.cf.typeB = clipPoints2[i].id.cf.typeA; cp.id.cf.indexA = clipPoints2[i].id.cf.indexB; cp.id.cf.indexB = clipPoints2[i].id.cf.indexA; } ++pointCount; } } manifold.pointCount = pointCount; }
the_stack
import { BaseValues } from '../../mol-gl/renderable/schema'; import { Style } from '../../mol-gl/renderer'; import { asciiWrite } from '../../mol-io/common/ascii'; import { IsNativeEndianLittle, flipByteOrder } from '../../mol-io/common/binary'; import { Box3D } from '../../mol-math/geometry'; import { Vec3, Mat4 } from '../../mol-math/linear-algebra'; import { PLUGIN_VERSION } from '../../mol-plugin/version'; import { RuntimeContext } from '../../mol-task'; import { Color } from '../../mol-util/color/color'; import { fillSerial } from '../../mol-util/array'; import { NumberArray } from '../../mol-util/type-helpers'; import { MeshExporter, AddMeshInput } from './mesh-exporter'; // avoiding namespace lookup improved performance in Chrome (Aug 2020) const v3fromArray = Vec3.fromArray; const v3normalize = Vec3.normalize; const v3toArray = Vec3.toArray; // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0 const UNSIGNED_BYTE = 5121; const UNSIGNED_INT = 5125; const FLOAT = 5126; const ARRAY_BUFFER = 34962; const ELEMENT_ARRAY_BUFFER = 34963; export type GlbData = { glb: Uint8Array } export class GlbExporter extends MeshExporter<GlbData> { readonly fileExtension = 'glb'; private nodes: Record<string, any>[] = []; private meshes: Record<string, any>[] = []; private accessors: Record<string, any>[] = []; private bufferViews: Record<string, any>[] = []; private binaryBuffer: ArrayBuffer[] = []; private byteOffset = 0; private centerTransform: Mat4; private static vec3MinMax(a: NumberArray) { const min: number[] = [Infinity, Infinity, Infinity]; const max: number[] = [-Infinity, -Infinity, -Infinity]; for (let i = 0, il = a.length; i < il; i += 3) { for (let j = 0; j < 3; ++j) { min[j] = Math.min(a[i + j], min[j]); max[j] = Math.max(a[i + j], max[j]); } } return [min, max]; } private addBuffer(buffer: ArrayBuffer, componentType: number, type: string, count: number, target: number, min?: any, max?: any, normalized?: boolean) { this.binaryBuffer.push(buffer); const bufferViewOffset = this.bufferViews.length; this.bufferViews.push({ buffer: 0, byteOffset: this.byteOffset, byteLength: buffer.byteLength, target }); this.byteOffset += buffer.byteLength; const accessorOffset = this.accessors.length; this.accessors.push({ bufferView: bufferViewOffset, byteOffset: 0, componentType, count, type, min, max, normalized }); return accessorOffset; } private addGeometryBuffers(vertices: Float32Array, normals: Float32Array, indices: Uint32Array | undefined, vertexCount: number, drawCount: number, isGeoTexture: boolean) { const tmpV = Vec3(); const stride = isGeoTexture ? 4 : 3; const vertexArray = new Float32Array(vertexCount * 3); const normalArray = new Float32Array(vertexCount * 3); let indexArray: Uint32Array | undefined; // position for (let i = 0; i < vertexCount; ++i) { v3fromArray(tmpV, vertices, i * stride); v3toArray(tmpV, vertexArray, i * 3); } // normal for (let i = 0; i < vertexCount; ++i) { v3fromArray(tmpV, normals, i * stride); v3normalize(tmpV, tmpV); v3toArray(tmpV, normalArray, i * 3); } // face if (!isGeoTexture) { indexArray = indices!.slice(0, drawCount); } const [vertexMin, vertexMax] = GlbExporter.vec3MinMax(vertexArray); let vertexBuffer = vertexArray.buffer; let normalBuffer = normalArray.buffer; let indexBuffer = isGeoTexture ? undefined : indexArray!.buffer; if (!IsNativeEndianLittle) { vertexBuffer = flipByteOrder(new Uint8Array(vertexBuffer), 4); normalBuffer = flipByteOrder(new Uint8Array(normalBuffer), 4); if (!isGeoTexture) indexBuffer = flipByteOrder(new Uint8Array(indexBuffer!), 4); } return { vertexAccessorIndex: this.addBuffer(vertexBuffer, FLOAT, 'VEC3', vertexCount, ARRAY_BUFFER, vertexMin, vertexMax), normalAccessorIndex: this.addBuffer(normalBuffer, FLOAT, 'VEC3', vertexCount, ARRAY_BUFFER), indexAccessorIndex: isGeoTexture ? undefined : this.addBuffer(indexBuffer!, UNSIGNED_INT, 'SCALAR', drawCount, ELEMENT_ARRAY_BUFFER) }; } private addColorBuffer(values: BaseValues, groups: Float32Array | Uint8Array, vertexCount: number, instanceIndex: number, isGeoTexture: boolean, interpolatedColors: Uint8Array | undefined) { const groupCount = values.uGroupCount.ref.value; const uAlpha = values.uAlpha.ref.value; const dTransparency = values.dTransparency.ref.value; const tTransparency = values.tTransparency.ref.value; const colorArray = new Uint8Array(vertexCount * 4); for (let i = 0; i < vertexCount; ++i) { let color = GlbExporter.getColor(values, groups, vertexCount, instanceIndex, isGeoTexture, interpolatedColors, i); let alpha = uAlpha; if (dTransparency) { const group = isGeoTexture ? GlbExporter.getGroup(groups, i) : groups[i]; const transparency = tTransparency.array[instanceIndex * groupCount + group] / 255; alpha *= 1 - transparency; } color = Color.sRGBToLinear(color); Color.toArray(color, colorArray, i * 4); colorArray[i * 4 + 3] = Math.round(alpha * 255); } let colorBuffer = colorArray.buffer; if (!IsNativeEndianLittle) { colorBuffer = flipByteOrder(new Uint8Array(colorBuffer), 4); } return this.addBuffer(colorBuffer, UNSIGNED_BYTE, 'VEC4', vertexCount, ARRAY_BUFFER, undefined, undefined, true); } protected async addMeshWithColors(input: AddMeshInput) { const { mesh, values, isGeoTexture, webgl, ctx } = input; const t = Mat4(); const colorType = values.dColorType.ref.value; const dTransparency = values.dTransparency.ref.value; const aTransform = values.aTransform.ref.value; const instanceCount = values.uInstanceCount.ref.value; let interpolatedColors: Uint8Array | undefined; if (colorType === 'volume' || colorType === 'volumeInstance') { const stride = isGeoTexture ? 4 : 3; interpolatedColors = GlbExporter.getInterpolatedColors(mesh!.vertices, mesh!.vertexCount, values, stride, colorType, webgl!); } // instancing const sameGeometryBuffers = mesh !== undefined; const sameColorBuffer = sameGeometryBuffers && colorType !== 'instance' && !colorType.endsWith('Instance') && !dTransparency; let vertexAccessorIndex: number; let normalAccessorIndex: number; let indexAccessorIndex: number | undefined; let colorAccessorIndex: number; let meshIndex: number; await ctx.update({ isIndeterminate: false, current: 0, max: instanceCount }); for (let instanceIndex = 0; instanceIndex < instanceCount; ++instanceIndex) { if (ctx.shouldUpdate) await ctx.update({ current: instanceIndex + 1 }); // create a glTF mesh if needed if (instanceIndex === 0 || !sameGeometryBuffers || !sameColorBuffer) { const { vertices, normals, indices, groups, vertexCount, drawCount } = GlbExporter.getInstance(input, instanceIndex); // create geometry buffers if needed if (instanceIndex === 0 || !sameGeometryBuffers) { const accessorIndices = this.addGeometryBuffers(vertices, normals, indices, vertexCount, drawCount, isGeoTexture); vertexAccessorIndex = accessorIndices.vertexAccessorIndex; normalAccessorIndex = accessorIndices.normalAccessorIndex; indexAccessorIndex = accessorIndices.indexAccessorIndex; } // create a color buffer if needed if (instanceIndex === 0 || !sameColorBuffer) { colorAccessorIndex = this.addColorBuffer(values, groups, vertexCount, instanceIndex, isGeoTexture, interpolatedColors); } // glTF mesh meshIndex = this.meshes.length; this.meshes.push({ primitives: [{ attributes: { POSITION: vertexAccessorIndex!, NORMAL: normalAccessorIndex!, COLOR_0: colorAccessorIndex! }, indices: indexAccessorIndex, material: 0 }] }); } // node Mat4.fromArray(t, aTransform, instanceIndex * 16); Mat4.mul(t, this.centerTransform, t); const node: Record<string, any> = { mesh: meshIndex!, matrix: t.slice() }; this.nodes.push(node); } } async getData() { const binaryBufferLength = this.byteOffset; const gltf = { asset: { version: '2.0', generator: `Mol* ${PLUGIN_VERSION}` }, scenes: [{ nodes: fillSerial(new Array(this.nodes.length) as number[]) }], nodes: this.nodes, meshes: this.meshes, buffers: [{ byteLength: binaryBufferLength, }], bufferViews: this.bufferViews, accessors: this.accessors, materials: [{ pbrMetallicRoughness: { baseColorFactor: [1, 1, 1, 1], metallicFactor: this.style.metalness, roughnessFactor: this.style.roughness } }] }; const createChunk = (chunkType: number, data: ArrayBuffer[], byteLength: number, padChar: number): [ArrayBuffer[], number] => { let padding = null; if (byteLength % 4 !== 0) { const pad = 4 - (byteLength % 4); byteLength += pad; padding = new Uint8Array(pad); padding.fill(padChar); } const preamble = new ArrayBuffer(8); const preambleDataView = new DataView(preamble); preambleDataView.setUint32(0, byteLength, true); preambleDataView.setUint32(4, chunkType, true); const chunk = [preamble, ...data]; if (padding) { chunk.push(padding.buffer); } return [chunk, 8 + byteLength]; }; const jsonString = JSON.stringify(gltf); const jsonBuffer = new Uint8Array(jsonString.length); asciiWrite(jsonBuffer, jsonString); const [jsonChunk, jsonChunkLength] = createChunk(0x4E4F534A, [jsonBuffer.buffer], jsonBuffer.length, 0x20); const [binaryChunk, binaryChunkLength] = createChunk(0x004E4942, this.binaryBuffer, binaryBufferLength, 0x00); const glbBufferLength = 12 + jsonChunkLength + binaryChunkLength; const header = new ArrayBuffer(12); const headerDataView = new DataView(header); headerDataView.setUint32(0, 0x46546C67, true); // magic number "glTF" headerDataView.setUint32(4, 2, true); // version headerDataView.setUint32(8, glbBufferLength, true); // length const glbBuffer = [header, ...jsonChunk, ...binaryChunk]; const glb = new Uint8Array(glbBufferLength); let offset = 0; for (const buffer of glbBuffer) { glb.set(new Uint8Array(buffer), offset); offset += buffer.byteLength; } return { glb }; } async getBlob(ctx: RuntimeContext) { return new Blob([(await this.getData()).glb], { type: 'model/gltf-binary' }); } constructor(private style: Style, boundingBox: Box3D) { super(); const tmpV = Vec3(); Vec3.add(tmpV, boundingBox.min, boundingBox.max); Vec3.scale(tmpV, tmpV, -0.5); this.centerTransform = Mat4.fromTranslation(Mat4(), tmpV); } }
the_stack
import React from 'react'; // eslint-disable-next-line react-memo/require-memo,react/display-name export const PixienautToiletSvg: React.FC<React.SVGProps<SVGSVGElement>> = (props) => ( /* eslint-disable max-len */ <svg {...props} width='882' height='1045' viewBox='0 0 882 1045' fill='none' xmlns='http://www.w3.org/2000/svg'> <path d='M184.025 691.843L275.173 695.709C294.849 696.544 304.686 696.961 312.753 700.741C319.769 704.028 325.802 709.094 330.256 715.434C335.376 722.724 337.491 732.34 341.721 751.574L341.721 751.574C348.015 780.193 351.163 794.503 345.206 807.858C340.886 817.545 328.496 828.707 318.412 831.996C304.51 836.531 294.116 833.079 273.33 826.174C222.881 809.417 184.025 771.539 184.025 691.843Z' fill='url(#paint0_linear)' /> <path d='M111.65 481.007C116.702 496.207 126.109 501.706 130.181 502.556L352.331 511.936L409.076 466.62C412.152 435.462 414.963 372.201 401.605 368.427C384.907 363.709 183.57 357.059 173.044 360.208C162.518 363.357 109.215 394.146 106.666 406.361C104.117 418.577 105.334 462.007 111.65 481.007Z' fill='url(#paint1_linear)' /> <path opacity='0.4' d='M181.039 498.256C173.176 466.497 170.494 423.091 170.094 387.709C169.971 376.831 174.022 367.012 180.738 359.569C219.733 358.288 386.474 364.15 401.604 368.426C412.641 371.544 412.64 415.271 410.572 447.947C409.815 459.907 403.794 470.836 394.43 478.315L366.066 500.966C357.242 508.013 346.066 511.435 334.809 510.536L181.039 498.256Z' fill='url(#paint2_linear)' /> <path d='M169.658 691.724C223.47 751.111 286.878 744.147 318.701 740.096L348.997 466.829C280.559 465.706 128.724 468.943 128.231 490.223C127.615 516.823 131.204 649.285 169.658 691.724Z' fill='url(#paint3_linear)' /> <path opacity='0.4' d='M177.083 471.75C222.198 463.626 302.449 462.146 349.837 462.798L318.741 739.9C316.762 740.161 314.711 740.45 312.592 740.749C286.052 744.494 248.855 749.742 208.195 719.229C185.016 656.528 177.484 538.59 177.083 471.75Z' fill='url(#paint4_linear)' /> <path d='M209.644 605.246C225.413 690.406 262.496 716.289 279.066 718.585C311.162 718.72 380.332 712.567 400.247 686.877C425.141 654.765 429.417 634.047 443.175 584.14C456.933 534.232 491.112 340.122 414.664 334.996C338.215 329.871 248.35 345.879 218.237 380.608C188.123 415.336 189.932 498.797 209.644 605.246Z' fill='url(#paint5_linear)' /> <path opacity='0.4' d='M235.284 609.465C249.135 684.677 281.763 707.527 296.345 709.55C324.593 709.658 385.473 704.201 403.008 681.504C424.928 653.133 428.698 634.832 440.822 590.746C452.947 546.66 483.092 375.2 415.811 370.698C348.53 366.196 269.434 380.364 242.92 411.048C216.405 441.732 217.97 515.449 235.284 609.465Z' fill='url(#paint6_linear)' /> <path opacity='0.4' d='M429.048 374.246C425.126 372.248 420.729 371.027 415.811 370.698C348.53 366.196 269.434 380.364 242.92 411.048C216.405 441.732 217.97 515.449 235.284 609.465C242.54 648.867 254.95 673.898 267.218 689.093C272.794 692.98 277.798 694.91 281.585 695.435C309.833 695.543 370.713 690.086 388.248 667.389C408.432 641.265 413.227 623.679 423.326 586.638C424.195 583.452 425.102 580.123 426.063 576.631C435.952 540.672 457.832 419.965 429.048 374.246Z' fill='url(#paint7_linear)' /> <path d='M518.604 973.534C514.737 966.237 512.354 956.54 511.165 945.811L511.165 945.811C505.656 896.084 502.902 871.221 496.238 861.215C489.574 851.21 477.909 844.747 454.578 831.82C404.263 803.942 351.339 782.945 345.664 810.142C335.236 860.115 325.025 915.622 320.326 931.566C291.822 1028.27 535.5 1005.42 518.604 973.534Z' fill='url(#paint8_linear)' /> <path d='M636.243 762.921C636.243 799.029 604.449 908.007 450.407 908.007C296.366 908.007 264.572 799.029 264.572 762.921C264.572 726.814 347.774 697.543 450.407 697.543C553.041 697.543 636.243 726.814 636.243 762.921Z' fill='url(#paint9_linear)' /> <ellipse opacity='0.4' cx='458.549' cy='763.762' rx='185.835' ry='65.3782' fill='url(#paint10_linear)' /> <ellipse opacity='0.4' cx='458.176' cy='753.53' rx='135.839' ry='47.789' fill='url(#paint11_linear)' /> <path d='M573.08 507.336C713.177 507.336 826.748 393.765 826.748 253.668C826.748 113.571 713.177 0 573.08 0C432.983 0 319.412 113.571 319.412 253.668C319.412 393.765 432.983 507.336 573.08 507.336Z' fill='url(#paint12_linear)' /> <mask id='mask0' mask-type='alpha' maskUnits='userSpaceOnUse' x='319' y='0' width='508' height='508'> <path d='M573.08 507.336C713.177 507.336 826.748 393.765 826.748 253.668C826.748 113.571 713.177 0 573.08 0C432.983 0 319.412 113.571 319.412 253.668C319.412 393.765 432.983 507.336 573.08 507.336Z' fill='white' /> </mask> <g mask='url(#mask0)'> <path d='M324.877 113.191C324.877 113.191 415.594 58.835 472.787 58.835C529.981 58.835 605.062 98.8983 677.86 98.8983C750.657 98.8983 751.271 20.6041 751.271 20.6041L517.094 -23.8969L367.046 20.6041L324.877 113.191Z' fill='url(#paint13_linear)' /> <path d='M448.242 -0.94591L454.656 -2.03618C503.14 -10.1176 535.99 -11.7985 566.702 -5.64977C607.144 2.44673 638.621 24.635 661.828 64.495C663.606 67.549 662.571 71.4663 659.517 73.2444C656.463 75.0225 652.546 73.9881 650.768 70.934C629.42 34.267 601.069 14.2821 564.19 6.89888C534.097 0.874201 501.015 2.90418 450.426 11.6641C446.943 12.2671 443.632 9.933 443.029 6.45085C442.426 2.96869 444.76 -0.342952 448.242 -0.94591Z' fill='#17413B' /> <path d='M801.364 108.063C801.364 108.063 784.651 94.328 766.578 101.195C748.504 108.063 746.179 130.972 702.281 143.973C658.383 156.974 584.316 122.532 538.073 143.973C476.999 172.291 436.418 263.996 461.174 365.805C473.641 417.073 555.832 525.554 555.832 525.554L769.661 474.127L866.321 270.777L801.364 108.063Z' fill='url(#paint14_linear)' /> <path d='M535.702 221.876C540.771 209.787 546.758 197.637 553.667 185.427C556.464 180.484 554.724 174.21 549.78 171.413C544.837 168.616 538.563 170.356 535.766 175.299C528.466 188.201 522.121 201.076 516.734 213.923C514.538 219.161 517.003 225.187 522.241 227.383C527.479 229.58 533.506 227.114 535.702 221.876Z' fill='white' fillOpacity='0.326978' /> <path d='M526.152 422.196C531.409 420.047 533.929 414.044 531.78 408.786C521.492 383.613 517.4 354.322 518.225 322.151C518.798 299.798 521.127 282.013 525.63 257.031C526.637 251.441 522.923 246.094 517.333 245.086C511.744 244.079 506.396 247.793 505.388 253.383C500.714 279.316 498.271 297.978 497.664 321.624C496.772 356.418 501.245 388.439 512.741 416.567C514.89 421.825 520.894 424.345 526.152 422.196Z' fill='white' fillOpacity='0.326978' /> </g> <rect x='306.548' y='248.954' width='82.2706' height='100.553' rx='14.6305' transform='rotate(-4 306.548 248.954)' fill='url(#paint15_linear)' /> <rect x='297.576' y='250.699' width='82.2706' height='100.553' rx='14.6305' transform='rotate(-4 297.576 250.699)' fill='url(#paint16_linear)' /> <path opacity='0.482399' d='M382.513 285.995L383.789 304.233C384.305 311.618 382.839 318.684 379.843 324.909L358.189 325.239L354.257 267.503L373.324 262.821C378.536 269.184 381.896 277.166 382.513 285.995Z' fill='url(#paint17_linear)' /> <path d='M357.091 264.863C357.016 263.585 355.356 263.14 354.652 264.209L351.261 269.358L354.386 323.755L358.405 328.749C359.216 329.758 360.844 329.13 360.769 327.838L357.091 264.863Z' fill='#17413B' /> <path d='M800.042 300.37C823.106 293.085 847.682 305.531 855.558 328.238L855.957 329.442L875.446 391.146L875.933 392.723C895.204 456.734 866.322 530.408 769.135 559.018L767.203 559.617L753.276 563.81C729.709 570.905 731.757 542.977 724.662 519.411C717.689 496.25 730.465 471.844 753.276 464.275L754.486 463.892L768.413 459.699C785.579 454.531 795.458 436.689 790.894 419.491L790.458 417.989L770.969 356.286C763.557 332.817 776.573 307.783 800.042 300.37Z' fill='url(#paint18_linear)' /> <path opacity='0.198103' fillRule='evenodd' clipRule='evenodd' d='M740.144 471.234C744 468.266 748.406 465.888 753.267 464.275L754.477 463.892L768.404 459.699C784.487 454.857 794.173 438.89 791.578 422.75C796.393 431.078 802.151 449.363 802.151 489.187C802.151 512.449 800.937 532.029 799.334 547.742C790.108 552.018 780.048 555.803 769.126 559.018L767.194 559.617L753.267 563.81C746.86 565.739 742.346 565.079 739.027 562.622L740.144 471.234Z' fill='url(#paint19_linear)' /> <path fillRule='evenodd' clipRule='evenodd' d='M392.541 402.212C395.066 402.212 397.112 400.166 397.112 397.641C397.112 395.117 395.066 393.071 392.541 393.071C390.017 393.071 387.971 395.117 387.971 397.641C387.971 400.166 390.017 402.212 392.541 402.212Z' fill='url(#paint20_linear)' /> <path fillRule='evenodd' clipRule='evenodd' d='M410.824 420.494C413.349 420.494 415.395 418.448 415.395 415.924C415.395 413.399 413.349 411.353 410.824 411.353C408.3 411.353 406.254 413.399 406.254 415.924C406.254 418.448 408.3 420.494 410.824 420.494Z' fill='url(#paint21_linear)' /> <path fillRule='evenodd' clipRule='evenodd' d='M429.107 434.206C431.631 434.206 433.677 432.16 433.677 429.636C433.677 427.111 431.631 425.065 429.107 425.065C426.582 425.065 424.536 427.111 424.536 429.636C424.536 432.16 426.582 434.206 429.107 434.206Z' fill='url(#paint22_linear)' /> <path d='M387.971 479.912H753.619L765.228 770.145C766.375 798.827 743.432 822.706 714.727 822.706H462.755C378.862 822.706 317.766 743.183 339.382 662.123L387.971 479.912Z' fill='url(#paint23_linear)' /> <mask id='mask1' mask-type='alpha' maskUnits='userSpaceOnUse' x='311' y='479' width='455' height='344'> <path d='M387.971 479.912H753.619L765.228 770.145C766.375 798.827 743.432 822.706 714.727 822.706H362.345C329.138 822.706 304.954 791.228 313.51 759.142L387.971 479.912Z' fill='white' /> </mask> <g mask='url(#mask1)'> <path opacity='0.2' d='M505.565 682C662.365 657.2 745.899 604 768.065 580.5L803.565 725C638.899 721 348.765 706.8 505.565 682Z' fill='url(#paint24_linear)' /> <path d='M623.178 519.843C620.22 519.843 617.787 522.092 617.495 524.972L617.465 525.557V616.262C617.465 619.418 620.023 621.975 623.178 621.975C626.136 621.975 628.57 619.727 628.862 616.846L628.892 616.262V525.557C628.892 522.401 626.334 519.843 623.178 519.843Z' fill='#17413B' /> <rect x='547.942' y='557.613' width='22.853' height='73.1294' fill='#A7DFFF' /> <path d='M721.19 569.553V597.607H707.741V590.751H714.333V576.409L694.184 576.409V569.553H721.19Z' fill='#A7DFFF' /> <path d='M701.147 584.47V617.232H694.291V584.47H701.147Z' fill='#A7DFFF' /> </g> <path fillRule='evenodd' clipRule='evenodd' d='M522.565 735.892C522.565 695.083 555.648 662 596.458 662H741.895C796.098 662 842.649 700.527 852.783 753.775L871.684 853.089C879.313 893.179 852.999 931.863 812.909 939.493C772.819 947.122 734.135 920.808 726.505 880.718L715.671 823.79C714.125 815.664 707.02 809.784 698.748 809.784H596.458C555.648 809.784 522.565 776.702 522.565 735.892Z' fill='url(#paint25_linear)' /> <path opacity='0.3' fillRule='evenodd' clipRule='evenodd' d='M579.31 664C546.769 671.733 522.565 700.986 522.565 735.892C522.565 776.702 555.648 809.784 596.458 809.784H698.748C707.02 809.784 714.125 815.664 715.671 823.79L726.505 880.718C733.905 919.601 770.517 945.525 809.292 940.09C790.023 929.456 772.678 911.795 767.685 881.949L748.808 768.675C738.687 707.943 692.194 664 638.058 664H579.31Z' fill='url(#paint26_linear)' /> <path fillRule='evenodd' clipRule='evenodd' d='M409.065 743.5C409.065 698.489 445.554 662 490.565 662H596.209C668.648 662 725.793 723.605 720.358 795.84L711.836 906.614C708.459 951.499 669.335 985.147 624.451 981.77C579.567 978.393 545.918 939.27 549.295 894.386L553.328 840.775C554.071 830.912 546.268 822.5 536.376 822.5H490.565C445.554 822.5 409.065 788.511 409.065 743.5Z' fill='url(#paint27_linear)' /> <path opacity='0.2' d='M609.481 979.241C572.331 969.338 546.306 934.119 549.295 894.386L553.328 840.775C554.071 830.912 546.268 822.5 536.376 822.5H494.801C522.052 813.312 558.578 800.46 583.565 790C626.565 772 630.065 796 621.065 860C619.477 871.293 617.344 882.928 615.224 894.493C609.44 926.05 603.75 957.089 609.481 979.241Z' fill='url(#paint28_linear)' /> <path fillRule='evenodd' clipRule='evenodd' d='M744.316 436.802C756.21 426.436 774.254 427.673 784.62 439.567C794.986 451.46 793.748 469.505 781.855 479.871C727.23 527.482 647.669 549.102 562.152 545.851C485.57 542.94 412.499 519.825 373.603 485.088C361.836 474.579 360.816 456.52 371.325 444.753C381.577 433.273 399.016 432.022 410.787 441.727L411.659 442.475C439.272 467.135 499.889 486.311 564.322 488.76C636.466 491.502 701.984 473.698 744.316 436.802Z' fill='url(#paint29_linear)' /> <mask id='mask2' mask-type='alpha' maskUnits='userSpaceOnUse' x='364' y='429' width='428' height='118'> <path fillRule='evenodd' clipRule='evenodd' d='M744.316 436.802C756.21 426.436 774.254 427.673 784.62 439.567C794.986 451.46 793.748 469.505 781.855 479.871C727.23 527.482 647.669 549.102 562.152 545.851C485.57 542.94 412.499 519.825 373.603 485.088C361.836 474.579 360.816 456.52 371.325 444.753C381.577 433.273 399.016 432.022 410.787 441.727L411.659 442.475C439.272 467.135 499.889 486.311 564.322 488.76C636.466 491.502 701.984 473.698 744.316 436.802Z' fill='white' /> </mask> <g mask='url(#mask2)'> <path opacity='0.969457' d='M433.239 443.964L436.61 449.934C409.057 465.49 397.017 489.608 400.704 523.283L400.921 525.129L394.118 525.981C389.522 489.264 402.274 462.14 431.676 444.864L433.239 443.964Z' fill='url(#paint30_linear)' /> <path opacity='0.969457' d='M481.575 464.183L487.117 468.218C471.623 489.498 463.038 513.957 460.207 542.475L459.944 545.341L453.112 544.76C455.66 514.791 464.224 488.911 480.023 466.355L481.575 464.183Z' fill='url(#paint31_linear)' /> <path opacity='0.969457' d='M541.544 466.763L548.309 467.875L547.552 472.297L546.275 479.277C540.614 509.769 539.577 527.816 544.099 565.405L544.458 568.335L537.655 569.182L536.946 563.285C532.85 527.863 533.846 509.343 539.099 480.396L541.061 469.626L541.544 466.763Z' fill='url(#paint32_linear)' /> <path opacity='0.969457' d='M602.638 458.812L609.388 457.613L611.002 466.519C618.512 507.543 620.397 529.373 616.749 565.947L616.423 569.119L609.605 568.398C613.489 531.706 611.966 510.557 604.879 471.174L602.638 458.812Z' fill='url(#paint33_linear)' /> <path opacity='0.969457' d='M675.251 456.567C687.865 493.647 693.319 519.042 693.332 552.324L693.318 555.468L686.462 555.403C686.778 522.486 681.854 497.876 669.902 462.157L668.76 458.775L675.251 456.567Z' fill='url(#paint34_linear)' /> <path opacity='0.969457' d='M721.911 435.599L727.716 431.952L729.871 435.372C752.46 471.179 760.086 490.436 758.775 523.592L758.679 525.728L751.832 525.385C753.401 494.02 747.023 476.045 726.79 443.377L721.911 435.599Z' fill='url(#paint35_linear)' /> </g> <path opacity='0.198103' d='M538.93 456.034C544.62 433.388 567.59 419.642 590.235 425.332C612.484 430.921 626.142 453.19 621.219 475.445L620.938 476.637L603.249 547.047C599.509 561.931 592.296 575.717 582.201 587.276C547.301 627.231 473.191 636.295 432.785 602.252L431.446 601.103L397.107 571.109C379.521 555.749 391.429 524.47 406.789 506.884C421.86 489.631 447.854 487.568 465.438 502.004L466.443 502.855L500.782 532.849C506.01 537.415 513.951 536.879 518.517 531.651C519.606 530.404 520.436 528.958 520.962 527.395L521.241 526.445L538.93 456.034Z' fill='url(#paint36_linear)' /> <path d='M520.65 446.893C526.34 424.247 549.31 410.501 571.955 416.19C594.204 421.78 607.862 444.049 602.939 466.303L602.658 467.495L584.969 537.906C581.23 552.79 574.017 566.576 563.921 578.134C529.021 618.09 468.623 622.583 428.217 588.54L426.878 587.391L392.538 557.397C374.953 542.037 373.149 515.329 388.509 497.743C403.58 480.489 429.574 478.427 447.158 492.862L448.163 493.714L482.502 523.707C487.731 528.274 495.671 527.738 500.237 522.509C501.326 521.263 502.156 519.816 502.682 518.254L502.961 517.303L520.65 446.893Z' fill='url(#paint37_linear)' /> <path fillRule='evenodd' clipRule='evenodd' d='M358.525 537.014C349.488 494.003 402.544 448.613 449.558 469.659C463.515 475.907 465.628 500.267 458.788 497.912C423.364 485.714 381.376 515.949 380.816 549.821L380.812 550.869C380.877 558.227 362.358 555.258 358.525 537.014Z' fill='url(#paint38_linear)' /> <defs> <linearGradient id='paint0_linear' x1='-76.7735' y1='729.739' x2='297.509' y2='1013' gradientUnits='userSpaceOnUse' > <stop stopColor='#83D3FF' /> <stop offset='1' stopColor='#456AF1' /> </linearGradient> <linearGradient id='paint1_linear' x1='-48.3672' y1='402.917' x2='416.889' y2='917.291' gradientUnits='userSpaceOnUse' > <stop stopColor='#A0DDFF' /> <stop offset='1' stopColor='#1070A5' /> </linearGradient> <linearGradient id='paint2_linear' x1='135.657' y1='317.267' x2='142.238' y2='560.896' gradientUnits='userSpaceOnUse' > <stop stopColor='#0E7AB5' /> <stop offset='1' stopColor='#0F38CD' /> </linearGradient> <linearGradient id='paint3_linear' x1='-2.53793' y1='647.938' x2='498.636' y2='887.63' gradientUnits='userSpaceOnUse' > <stop stopColor='#A0DDFF' /> <stop offset='1' stopColor='#1070A5' /> </linearGradient> <linearGradient id='paint4_linear' x1='148.782' y1='428.248' x2='249.946' y2='791.453' gradientUnits='userSpaceOnUse' > <stop stopColor='#0E7AB5' /> <stop offset='1' stopColor='#0F38CD' /> </linearGradient> <linearGradient id='paint5_linear' x1='64.4099' y1='561.154' x2='620.564' y2='824.707' gradientUnits='userSpaceOnUse' > <stop stopColor='#A0DDFF' /> <stop offset='1' stopColor='#1070A5' /> </linearGradient> <linearGradient id='paint6_linear' x1='208.336' y1='370.447' x2='370.64' y2='771.995' gradientUnits='userSpaceOnUse' > <stop stopColor='#0E7AB5' /> <stop offset='1' stopColor='#0F38CD' /> </linearGradient> <linearGradient id='paint7_linear' x1='193.576' y1='356.332' x2='355.881' y2='757.88' gradientUnits='userSpaceOnUse' > <stop stopColor='#0E7AB5' /> <stop offset='1' stopColor='#0F38CD' /> </linearGradient> <linearGradient id='paint8_linear' x1='56.4783' y1='905.454' x2='494.374' y2='1156.11' gradientUnits='userSpaceOnUse' > <stop stopColor='#83D3FF' /> <stop offset='1' stopColor='#456AF1' /> </linearGradient> <linearGradient id='paint9_linear' x1='97.9902' y1='836.287' x2='587.021' y2='1290.12' gradientUnits='userSpaceOnUse' > <stop stopColor='#A0DDFF' /> <stop offset='1' stopColor='#1070A5' /> </linearGradient> <linearGradient id='paint10_linear' x1='232.777' y1='706.209' x2='255.329' y2='886.777' gradientUnits='userSpaceOnUse' > <stop stopColor='#0E7AB5' /> <stop offset='1' stopColor='#0F38CD' /> </linearGradient> <linearGradient id='paint11_linear' x1='293.145' y1='711.461' x2='309.629' y2='843.449' gradientUnits='userSpaceOnUse' > <stop stopColor='#0E7AB5' /> <stop offset='1' stopColor='#0F38CD' /> </linearGradient> <linearGradient id='paint12_linear' x1='319.412' y1='-0.000173113' x2='319.412' y2='507.336' gradientUnits='userSpaceOnUse' > <stop stopColor='#52EFFF' /> <stop offset='1' stopColor='#25A0B3' /> </linearGradient> <linearGradient id='paint13_linear' x1='244.174' y1='362.046' x2='371.313' y2='38.0894' gradientUnits='userSpaceOnUse' > <stop stopColor='#34D7E8' /> <stop offset='0.85' stopColor='#259EB1' /> <stop offset='1' stopColor='#25A0B3' /> </linearGradient> <linearGradient id='paint14_linear' x1='352.69' y1='449.27' x2='910.703' y2='686.952' gradientUnits='userSpaceOnUse' > <stop stopColor='#165B7A' /> <stop offset='1' stopColor='#001431' /> </linearGradient> <linearGradient id='paint15_linear' x1='290.977' y1='532.04' x2='417.8' y2='447.035' gradientUnits='userSpaceOnUse' > <stop stopColor='#34D7E8' /> <stop offset='0.85' stopColor='#259EB1' /> <stop offset='1' stopColor='#25A0B3' /> </linearGradient> <linearGradient id='paint16_linear' x1='204.684' y1='456.19' x2='439.106' y2='481.444' gradientUnits='userSpaceOnUse' > <stop stopColor='#B1F5FF' /> <stop offset='1' stopColor='#34D7E8' /> </linearGradient> <linearGradient id='paint17_linear' x1='374.571' y1='440.941' x2='428.939' y2='404.752' gradientUnits='userSpaceOnUse' > <stop stopColor='#34D7E8' /> <stop offset='0.85' stopColor='#259EB1' /> <stop offset='1' stopColor='#25A0B3' /> </linearGradient> <linearGradient id='paint18_linear' x1='761.463' y1='626.154' x2='933.833' y2='600.419' gradientUnits='userSpaceOnUse' > <stop stopColor='#1C899A' /> <stop offset='1' stopColor='#34D7E8' /> </linearGradient> <linearGradient id='paint19_linear' x1='742.73' y1='347.238' x2='637.147' y2='410.899' gradientUnits='userSpaceOnUse' > <stop stopColor='#042635' /> <stop offset='1' stopColor='#001431' /> </linearGradient> <linearGradient id='paint20_linear' x1='389.931' y1='396.133' x2='387.561' y2='404.718' gradientUnits='userSpaceOnUse' > <stop stopColor='#042635' /> <stop offset='1' stopColor='#06565B' /> </linearGradient> <linearGradient id='paint21_linear' x1='408.214' y1='414.416' x2='405.844' y2='423' gradientUnits='userSpaceOnUse' > <stop stopColor='#042635' /> <stop offset='1' stopColor='#06565B' /> </linearGradient> <linearGradient id='paint22_linear' x1='426.496' y1='428.128' x2='424.126' y2='436.712' gradientUnits='userSpaceOnUse' > <stop stopColor='#042635' /> <stop offset='1' stopColor='#06565B' /> </linearGradient> <linearGradient id='paint23_linear' x1='696.565' y1='532.5' x2='531.942' y2='932.551' gradientUnits='userSpaceOnUse' > <stop stopColor='#128698' /> <stop offset='1' stopColor='#43CBC1' /> </linearGradient> <linearGradient id='paint24_linear' x1='455.098' y1='460.177' x2='257.033' y2='1455.91' gradientUnits='userSpaceOnUse' > <stop stopColor='#042635' /> <stop offset='1' stopColor='#06565B' /> </linearGradient> <linearGradient id='paint25_linear' x1='779.148' y1='1099.01' x2='613.371' y2='669.539' gradientUnits='userSpaceOnUse' > <stop stopColor='#5DF1D7' /> <stop offset='1' stopColor='#128698' /> </linearGradient> <linearGradient id='paint26_linear' x1='413.452' y1='399.207' x2='-411.952' y2='2323.08' gradientUnits='userSpaceOnUse' > <stop stopColor='#042635' /> <stop offset='1' stopColor='#06565B' /> </linearGradient> <linearGradient id='paint27_linear' x1='239.065' y1='982' x2='669.74' y2='706.904' gradientUnits='userSpaceOnUse' > <stop stopColor='#5DF1D7' /> <stop offset='1' stopColor='#128698' /> </linearGradient> <linearGradient id='paint28_linear' x1='492.735' y1='621.783' x2='-165.851' y2='1553.45' gradientUnits='userSpaceOnUse' > <stop stopColor='#042635' /> <stop offset='1' stopColor='#06565B' /> </linearGradient> <linearGradient id='paint29_linear' x1='455.741' y1='468.768' x2='446.95' y2='585.747' gradientUnits='userSpaceOnUse' > <stop stopColor='#042635' /> <stop offset='1' stopColor='#06565B' /> </linearGradient> <linearGradient id='paint30_linear' x1='377.081' y1='393.821' x2='371.782' y2='548.419' gradientUnits='userSpaceOnUse' > <stop stopColor='#5DF1D7' /> <stop offset='1' stopColor='#021F24' /> </linearGradient> <linearGradient id='paint31_linear' x1='440.482' y1='414.566' x2='433.864' y2='567.437' gradientUnits='userSpaceOnUse' > <stop stopColor='#5DF1D7' /> <stop offset='1' stopColor='#021F24' /> </linearGradient> <linearGradient id='paint32_linear' x1='529.259' y1='404.147' x2='503.861' y2='594.032' gradientUnits='userSpaceOnUse' > <stop stopColor='#5DF1D7' /> <stop offset='1' stopColor='#021F24' /> </linearGradient> <linearGradient id='paint33_linear' x1='596.728' y1='389.442' x2='570.402' y2='596.526' gradientUnits='userSpaceOnUse' > <stop stopColor='#5DF1D7' /> <stop offset='1' stopColor='#021F24' /> </linearGradient> <linearGradient id='paint34_linear' x1='661.06' y1='395.758' x2='640.32' y2='579.412' gradientUnits='userSpaceOnUse' > <stop stopColor='#5DF1D7' /> <stop offset='1' stopColor='#021F24' /> </linearGradient> <linearGradient id='paint35_linear' x1='708.166' y1='374.621' x2='700.048' y2='551.218' gradientUnits='userSpaceOnUse' > <stop stopColor='#5DF1D7' /> <stop offset='1' stopColor='#021F24' /> </linearGradient> <linearGradient id='paint36_linear' x1='402.081' y1='318.259' x2='251.51' y2='558.336' gradientUnits='userSpaceOnUse' > <stop stopColor='#042635' /> <stop offset='1' stopColor='#001431' /> </linearGradient> <linearGradient id='paint37_linear' x1='637.85' y1='371.698' x2='312.769' y2='357.98' gradientUnits='userSpaceOnUse' > <stop stopColor='#25A0B3' /> <stop offset='1' stopColor='#34D7E8' /> </linearGradient> <linearGradient id='paint38_linear' x1='384.508' y1='534.341' x2='460.273' y2='582.607' gradientUnits='userSpaceOnUse' > <stop stopColor='#042635' /> <stop offset='1' stopColor='#06565B' /> </linearGradient> </defs> </svg> /* eslint-enable max-len */ );
the_stack
module Worldmap { let worldmap: Worldmap = null let worldmapPlayer: WorldmapPlayer = null let $worldmap: HTMLElement|null = null let $worldmapPlayer: HTMLElement|null = null let $worldmapTarget: HTMLElement|null = null let worldmapTimer: number = -1 let lastEncounterCheck = 0 const WORLDMAP_UNDISCOVERED = 0 const WORLDMAP_DISCOVERED = 1 const WORLDMAP_SEEN = 2 const NUM_SQUARES_X = 4*7 const NUM_SQUARES_Y = 5*6 const SQUARE_SIZE = 51 const WORLDMAP_SPEED = 2 // speed scalar const WORLDMAP_ENCOUNTER_CHECK_RATE = 800 // ms (TODO: find right value) interface Square { terrainType: string, //"mountain" | "ocean" | "desert" | "city" | "ocean" fillType: string, //"no_fill" | "fill_w" // note: there are frequencies for certain times of day (Morning, Afternoon, Night) // but as noted on http://falloutmods.wikia.com/wiki/Worldmap.txt_File_Format // they don't appear to be used frequency: string, //"forced" | "frequent" | "uncommon" | "common" | "rare" | "none" encounterType: string, difficulty: number, state: number // WORLDMAP_UNDISCOVERED etc (TODO: make an enum) } interface WorldmapPlayer { x: number; y: number; target: Point; } interface Worldmap { squares: Square[][]; encounterTables: { [encounterType: string]: EncounterTable }; encounterGroups: { [groupName: string]: EncounterGroup }; encounterRates: { [frequency: string]: number }; terrainSpeed: { [terrainType: string]: number }; } export interface EncounterTable { maps: string[]; encounters: Encounter[]; } export interface Encounter { chance: number; scenery: any; // TODO: scenery type (string?) enc: EncounterRef; //enc.enc ? parseEncounterReference(enc.enc) : enc.enc, cond: any; // TODO: condition type condOrig: string|null; // Original condition string special: string|null; } export interface EncounterRef { type: "ambush" | "fighting"; target?: "player"; party: EncounterParty; firstParty?: EncounterParty; secondParty?: EncounterParty; } interface EncounterParty { start: number; end: number; name: string; } export interface EncounterGroup { critters: EncounterCritter[]; position: EncounterPosition; target?: "player" | number; } interface Range { start: number; end: number; } interface EncounterItem { range?: Range; amount?: number; pid: number; wielded: boolean; } export interface EncounterCritter { position?: Point; cond?: Encounters.Node[]; ratio?: number; items: EncounterItem[]; pid: number; script: number; dead: boolean; } export interface EncounterPosition { type: string; // Formation spacing: number; } function parseWorldmap(data: string): Worldmap { // 20 tiles, 7x6 squares each // each tile is 350x300 // 4 tiles horizontally, 5 vertically function parseSquare(data: string): Square { const props = data.split(",").map(x => x.toLowerCase()) return {terrainType: props[0], fillType: props[1], frequency: props[2], encounterType: props[5], difficulty: null, state: null } } function parseEncounterReference(data: string): any { // "(4-8) ncr_masters_army ambush player" if(data === "special1") return {type: "special"} const party = "(?:\\((\\d+)-(\\d+)\\) ([a-z0-9_]+))" const re = party + " ?(?:(ambush player)|(fighting) " + party + ")?" const m = data.match(new RegExp(re)) if(!m) throw Error("Error parsing encounter reference"); //console.log("%o %o", re, data) const firstParty = {start: parseInt(m[1]), end: parseInt(m[2]), name: m[3] } if(m[4] === "ambush player") { return {type: "ambush", target: "player", party: firstParty} } else { return {type: "fighting", firstParty: firstParty, secondParty: { start: parseInt(m[6]), end: parseInt(m[7]), name: m[8] }} } } function parseEncounter(data: string): Encounter { const s = data.trim().split(",") const enc: any = {} let isSpecial = false let i = 0 for(; i < s.length; i++) { const kv = s[i].split(":") if(kv.length === 2) enc[kv[0].toLowerCase()] = kv[1].toLowerCase() if(s[i].toLowerCase().trim() === "special") isSpecial = true } let cond: string|null = s[i-1].toLowerCase().trim() if(cond.indexOf('if') !== 0) // conditions start with "if" cond = null return {chance: parseInt(enc.chance), // integeral percentage scenery: enc.scenery, enc: enc.enc ? parseEncounterReference(enc.enc) : enc.enc, cond: cond ? Encounters.parseConds(cond) : null, special: isSpecial ? enc.map : null, condOrig: cond } } function parseEncounterItem(data: string) { // an item, e.g. Item:7(wielded), Item:(0-10)41 const m = data.match(/(?:\((\d+)-(\d+)\))?(\d+)(?:\((wielded)\))?/) let range = null if(m[1] !== undefined) range = {start: parseInt(m[1]), end: parseInt(m[2])} const item = {range: range, pid: parseInt(m[3]), wielded: (m[4] !== undefined)} return item } function parseEncounterCritter(data: string) { const s = data.trim().split(",") const enc: any = {} const items: EncounterItem[] = [] let i = 0 for(; i < s.length; i++) { const kv = s[i].split(":").map(x => x.toLowerCase().trim()) if(kv[0] === "item") { items.push(parseEncounterItem(kv[1])) } else if(kv.length === 2) enc[kv[0]] = kv[1] } const isDead = s[0] === "dead" let cond = s[i-1].toLowerCase().trim() if(cond.indexOf('if') !== 0) // conditions start with "if" cond = null return {ratio: enc.ratio ? parseInt(enc.ratio) : null, pid: enc.pid ? parseInt(enc.pid) : null, script: enc.script ? parseInt(enc.script) : null, items: items, dead: isDead, cond: cond ? Encounters.parseConds(cond) : null} } // Parse a "key:value, key:value" format function parseKeyed(data: string) { const items = data.split(",").map(x => x.trim()) const out: { [key: string]: string|number } = {} for(let i = 0; i < items.length; i++) { const s: any = items[i].split(":") if(isNumeric(s[1])) s[1] = parseFloat(s[1]) out[s[0].toLowerCase()] = s[1] } return out } const ini: any = parseIni(data) const encounterTables: { [name: string]: EncounterTable } = {} const encounterGroups: { [groupName: string]: EncounterGroup } = {} const squares: Square[][] = new Array(NUM_SQUARES_X) // (4*7) x (5*6) array (i.e., number of tiles -- 840) for(let i = 0; i < NUM_SQUARES_X; i++) squares[i] = new Array(NUM_SQUARES_Y) // console.log(ini) for(const key in ini) { const m = key.match(/Tile (\d+)/) if(m !== null) { const tileNum = parseInt(m[1]) const tileX = tileNum % 4 const tileY = Math.floor(tileNum / 4) const difficulty = parseInt(ini[key].encounter_difficulty) for(const position in ini[key]) { const pos = position.match(/(\d)_(\d)/) if(pos === null) continue const x = tileX * 7 + parseInt(pos[1]) const y = tileY * 6 + parseInt(pos[2]) //console.log(tileX + "/" + tileY + " | " + pos[1] + ", " + pos[2] + " -> " + x + ", " + y) squares[x][y] = parseSquare(ini[key][position]) squares[x][y].difficulty = difficulty squares[x][y].state = WORLDMAP_UNDISCOVERED } } else if(key.indexOf("Encounter Table") === 0) { const name = ini[key].lookup_name.toLowerCase() const maps = ini[key].maps.split(",").map((x: string) => x.trim()) const encounter: EncounterTable = {maps: maps, encounters: []} for(const prop in ini[key]) { if(prop.indexOf("enc_") === 0) { encounter.encounters.push(parseEncounter(ini[key][prop])) } } encounterTables[name] = encounter } else if(key.indexOf("Encounter:") === 0) { const groupName = key.slice("Encounter: ".length).toLowerCase() let position = null if(ini[key].position !== undefined) { const position_ = ini[key].position.split(",").map((x: string) => x.trim().toLowerCase()) position = {type: position_[0], spacing: 3} // TODO: verify defaults (3 spacing?) } else { // default position = {type: "surrounding", spacing: 5} // TODO: What is distance: "Player(Perception)" ? } const group: EncounterGroup = {critters: [], position: position} for(const prop in ini[key]) { if(prop.indexOf("type_") === 0) { group.critters.push(parseEncounterCritter(ini[key][prop])) } } encounterGroups[groupName] = group } } const encounterRates: { [frequency: string]: number } = {} for(const key in ini.Data) { encounterRates[key.toLowerCase()] = parseInt(ini.Data[key]) } // console.log(squares) // console.log(encounterTables) // console.log(encounterGroups) return { squares, encounterTables, encounterGroups, encounterRates, terrainSpeed: parseKeyed(ini.Data.terrain_types) as { [terrainType: string]: number } } } export function getEncounterGroup(groupName: string): EncounterGroup { return worldmap.encounterGroups[groupName] } function positionToSquare(pos: Point): Point { return {x: Math.floor(pos.x / SQUARE_SIZE), y: Math.floor(pos.y / SQUARE_SIZE)} } function setSquareStateAt(squarePos: Point, newState: number, seeAdjacent: boolean=true): void { if(squarePos.x < 0 || squarePos.x >= NUM_SQUARES_X || squarePos.y < 0 || squarePos.y >= NUM_SQUARES_Y) return const oldState = worldmap.squares[squarePos.x][squarePos.y].state worldmap.squares[squarePos.x][squarePos.y].state = newState if(oldState === WORLDMAP_DISCOVERED && newState === WORLDMAP_SEEN) return // console.log( worldmap.squares[squarePos.x][squarePos.y].fillType ) // the square element at squarePos const stateName: { [state: number]: string } = {} stateName[WORLDMAP_UNDISCOVERED] = "undiscovered" stateName[WORLDMAP_DISCOVERED] = "discovered" stateName[WORLDMAP_SEEN] = "seen" //console.log("square: " + squarePos.x + ", " + squarePos.y + " | " + stateName[oldState] + " | " + stateName[newState]) const $square = document.querySelector(`div.worldmapSquare[square-x='${squarePos.x}'][square-y='${squarePos.y}']`); $square.classList.remove("worldmapSquare-" + stateName[oldState]); $square.classList.add("worldmapSquare-" + stateName[newState]); if(seeAdjacent === true) { setSquareStateAt({x: squarePos.x-1, y: squarePos.y}, WORLDMAP_SEEN, false) if(worldmap.squares[squarePos.x][squarePos.y].fillType === "fill_w") return // only fill the left tile setSquareStateAt({x: squarePos.x+1, y: squarePos.y}, WORLDMAP_SEEN, false) setSquareStateAt({x: squarePos.x, y: squarePos.y-1}, WORLDMAP_SEEN, false) setSquareStateAt({x: squarePos.x, y: squarePos.y+1}, WORLDMAP_SEEN, false) // diagonals setSquareStateAt({x: squarePos.x-1, y: squarePos.y-1}, WORLDMAP_SEEN, false) setSquareStateAt({x: squarePos.x+1, y: squarePos.y-1}, WORLDMAP_SEEN, false) setSquareStateAt({x: squarePos.x-1, y: squarePos.y+1}, WORLDMAP_SEEN, false) setSquareStateAt({x: squarePos.x+1, y: squarePos.y+1}, WORLDMAP_SEEN, false) } } function execEncounter(encTable: EncounterTable): void { const enc = Encounters.evalEncounter(encTable) console.log("final: map %s, groups %o", enc.mapName, enc.groups) // load map gMap.loadMap(enc.mapName, undefined, undefined, function() { // set up critters' positions in their formations Encounters.positionCritters(enc.groups, player.position, lookupMapFromLookup(enc.mapLookupName)) enc.groups.forEach(function(group) { group.critters.forEach(function(critter) { //console.log("critter: %o", critter) const obj = createObjectWithPID(critter.pid, critter.script ? critter.script : undefined) //console.log("obj: %o", obj) // TODO: items & equipping gMap.addObject(obj) obj.move(critter.position) }) }) // player was ambushed, so begin combat if(enc.encounterType === "ambush" && Config.engine.doCombat === true) Combat.start() }) } export function doEncounter(): void { const squarePos = positionToSquare(worldmapPlayer) const square = worldmap.squares[squarePos.x][squarePos.y] const encTable = worldmap.encounterTables[square.encounterType] console.log("enc table: %s -> %o", square.encounterType, encTable) execEncounter(encTable) } export function didEncounter(): boolean { const squarePos = positionToSquare(worldmapPlayer) const square = worldmap.squares[squarePos.x][squarePos.y] const encRate = worldmap.encounterRates[square.frequency] //console.log("square: %o, worldmap: %o, encRate: %d", square, worldmap, encRate) if(encRate === 0) // 0% encounter rate (none) return false else if(encRate === 100) // 100% encounter rate (forced) return true else { // roll for it // TODO: adjust for difficulty: // If easy difficulty, encRate -= encRate / 15 // If hard difficulty, encRate += encRate / 15 const roll = getRandomInt(0, 100) console.log("encounter: rolled %d vs %d", roll, encRate) if(roll < encRate) { // We rolled an encounter! return true } } return false } function centerWorldmapTarget(x: number, y: number): void { $worldmapTarget.style.left = (x - $worldmapTarget.offsetWidth/2|0) + "px"; $worldmapTarget.style.top = (y - $worldmapTarget.offsetHeight/2|0) + "px"; } export function init(): void { /*$("#worldmap").mousemove(function(e) { var offset = $(this).offset() var x = e.pageX - parseInt(offset.left) var y = e.pageY - parseInt(offset.top) var scrollLeft = $(this).scrollLeft() var scrollTop = $(this).scrollTop() console.log(scrollLeft + " | " + $(this).width()) if(x <= 15) $(this).scrollLeft(scrollLeft - 15) if(x >= $(this).width() - 15) { console.log("y"); $(this).scrollLeft(scrollLeft + 15) } console.log(x + ", " + y) })*/ $worldmapPlayer = $id("worldmapPlayer") $worldmapTarget = $id("worldmapTarget") $worldmap = $id("worldmap") worldmap = parseWorldmap(getFileText("data/data/worldmap.txt")) if(!mapAreas) mapAreas = loadAreas() $worldmap.onclick = function(this: HTMLElement, e: MouseEvent) { // Calculate viewport-relative offset const box = this.getBoundingClientRect(); const offsetLeft = box.left|0 + window.pageXOffset; const offsetTop = box.top|0 + window.pageYOffset; const x = e.pageX - offsetLeft const y = e.pageY - offsetTop const ax = x + this.scrollLeft const ay = y + this.scrollTop worldmapPlayer.target = {x: ax, y: ay} showv($worldmapPlayer); Object.assign($worldmapTarget.style, { backgroundImage: "url('art/intrface/wmaptarg.png')", left: ax + "px", top: ay + "px"}); console.log("targeting: " + ax + ", " + ay) }; $worldmapTarget.onclick = function(e: MouseEvent) { const area = withinArea(worldmapPlayer) if(area !== null) { // we're on a hotspot, visit the area map e.stopPropagation() uiWorldMapShowArea(area) } else { // we're in an open area, do nothing } }; for(const key in mapAreas) { const area = mapAreas[key] if(area.state !== true) continue const $area = makeEl("div", { classes: ["area"] }); $worldmap.appendChild($area); //console.log("adding one @ " + area.worldPosition.x + ", " + area.worldPosition.y) const $el = makeEl("div", { classes: ["areaCircle", "areaSize-" + area.size] }); $area.appendChild($el); // transform the circle since (0,0) is the top-left instead of center const x = area.worldPosition.x - $el.offsetWidth / 2 const y = area.worldPosition.y - $el.offsetHeight / 2 //console.log("adding one @ " + x + ", " + y + " | " + $el.width() + ", " + $el.height()) //console.log("size = " + area.size) $area.style.left = x + "px"; $area.style.top = y + "px"; //if(area.name==="Arroyo")console.log("ARROYO IS " + key) const $label = makeEl("div", { classes: ["areaLabel"], style: { left: "0px", top: (2 + $el.offsetHeight) + "px" } }); $area.appendChild($label); $label.textContent = area.name; } for(let x = 0; x < NUM_SQUARES_X; x++) { for(let y = 0; y < NUM_SQUARES_Y; y++) { let state: string|number = worldmap.squares[x][y].state if(state === WORLDMAP_UNDISCOVERED) state = "undiscovered" else if(state === WORLDMAP_DISCOVERED) state = "discovered" else if(state === WORLDMAP_SEEN) state = "seen" const $el = makeEl("div", { classes: ["worldmapSquare", "worldmapSquare-" + state], style: { left: (x*SQUARE_SIZE) + "px", top: (y*SQUARE_SIZE) + "px" }, attrs: { "square-x": x + "", "square-y": y + "" } }); $worldmap.appendChild($el); } } worldmapPlayer = {x: mapAreas[0].worldPosition.x, y: mapAreas[0].worldPosition.y, target: null} $worldmapTarget.style.left = worldmapPlayer.x + "px"; $worldmapTarget.style.top = worldmapPlayer.y + "px"; setSquareStateAt(positionToSquare(worldmapPlayer), WORLDMAP_DISCOVERED) if(withinArea(worldmapPlayer) !== null) { hidev($worldmapPlayer); $worldmapTarget.style.backgroundImage = "url('art/intrface/hotspot1.png')"; } // updateWorldmapPlayer() } export function start() { updateWorldmapPlayer() } export function stop() { clearTimeout(worldmapTimer) } // check if we're inside an area function withinArea(position: Point) { for(const areaNum in mapAreas) { const area = mapAreas[areaNum] const radius = (area.size === "large" ? 32 : 16) // guessing for now if(pointIntersectsCircle(area.worldPosition, radius, position)) { console.log("intersects " + area.name) return area } } return null } function updateWorldmapPlayer() { $worldmapPlayer.style.left = worldmapPlayer.x + "px"; $worldmapPlayer.style.top = worldmapPlayer.y + "px"; if(worldmapPlayer.target) { let dx = worldmapPlayer.target.x - worldmapPlayer.x let dy = worldmapPlayer.target.y - worldmapPlayer.y const len = Math.sqrt(dx*dx + dy*dy) const squarePos = positionToSquare(worldmapPlayer) const currentSquare = worldmap.squares[squarePos.x][squarePos.y] const speed = WORLDMAP_SPEED / worldmap.terrainSpeed[currentSquare.terrainType] if(len < speed) { worldmapPlayer.x = worldmapPlayer.target.x worldmapPlayer.y = worldmapPlayer.target.y worldmapPlayer.target = null hidev($worldmapPlayer); $worldmapTarget.style.backgroundImage = "url('art/intrface/hotspot1.png')"; centerWorldmapTarget(worldmapPlayer.x, worldmapPlayer.y) } else { // normalize direction dx /= len dy /= len // head towards it worldmapPlayer.x += dx * speed worldmapPlayer.y += dy * speed } // center the worldmap to the player const width = $worldmap.offsetWidth const height = $worldmap.offsetHeight const sx = clamp(0, width, Math.floor(worldmapPlayer.x - width/2)) const sy = clamp(0, height, Math.floor(worldmapPlayer.y - height/2)) $worldmap.scrollLeft = sx; $worldmap.scrollTop = sy; if(currentSquare.state !== WORLDMAP_DISCOVERED) setSquareStateAt(squarePos, WORLDMAP_DISCOVERED) // check for encounters const time = heart.timer.getTime() if(Config.engine.doEncounters === true && (time >= lastEncounterCheck + WORLDMAP_ENCOUNTER_CHECK_RATE)) { lastEncounterCheck = time const hadEncounter = didEncounter() if(hadEncounter === true) { $worldmapPlayer.style.backgroundImage = "url('art/intrface/wmapfgt0.png')"; // TODO: Disable Worldmap UI while waiting on this! setTimeout(function() { doEncounter() uiCloseWorldMap() $worldmapPlayer.style.backgroundImage = "url('art/intrface/wmaploc.png')"; }, 1000) clearTimeout(worldmapTimer) return } } } worldmapTimer = setTimeout(updateWorldmapPlayer, 75) } }
the_stack
import { unwindEdges } from '@good-idea/unwind-edges' import createSanityClient, { SanityClient } from '@sanity/client' import PQueue from 'p-queue' import { Collection, Product, ShopifyClient, SyncOperationResult, SaneShopifyConfig, RelatedPair, ShopifySecrets, LinkOperation, SubscriptionCallbacks, RelatedPairPartial, SyncUtils, SyncMachineState, UpdateConfigDocumentArgs, } from '@sane-shopify/types' import { syncStateMachine } from './syncState' import { createLogger, Logger } from './logger' import { createShopifyClient, shopifyUtils } from './shopify' import { sanityUtils } from './sanity' import { definitely } from './utils' import { migrateSanityConfig } from './migrations' /** * This is the main 'entry point' for the sync utils client. * It creates the two sub-clients, for Sanity and Shopify, * which return several functions used in the syncing process. * * This base client is responsible for: * - Initializing the clients * - Providing a public API of functions * - Calls any callbacks provided by the API end user */ const noop = () => undefined // TODO: // might make sense to turn this into a class. The shopify client and/or // sanity client might be updated, for instance, when saving a set of new // shopify secrets. // // Making these clients stateful would allow for updating it when new secrets // are saved. For now, the consumer should just re-create a new syncing client. export const syncUtils = ( shopifyClient: ShopifyClient, sanityClient: SanityClient, onStateChange: (state: SyncMachineState) => void = noop ): SyncUtils => { /** * Client Setup */ const { fetchItemById, fetchAllShopifyProducts, fetchAllShopifyCollections, testSecrets, } = shopifyUtils(shopifyClient) const { fetchAllSanityDocuments, syncSanityDocument, syncRelationships, fetchRelatedDocs, documentByShopifyId, // fetchSecrets, archiveSanityDocument, saveConfig: saveConfigToSanity, clearConfig: clearConfigFromSanity, } = sanityUtils(sanityClient, shopifyClient) /** * State Management */ const { init, initialState, onDocumentsFetched, startSync, onSavedSecrets, onSavedSecretsError, onClearedSecrets, onFetchComplete, onDocumentSynced, onDocumentLinked, onComplete, } = syncStateMachine({ onStateChange }) /** * Private Methods */ /* Syncs a single document and returns related nodes to sync */ const syncCollection = async ( shopifyCollection: Collection ): Promise<SyncOperationResult> => { const [related] = unwindEdges(shopifyCollection.products) const operation = await syncSanityDocument(shopifyCollection) return { operation, related } } const syncProduct = async ( shopifyProduct: Product ): Promise<SyncOperationResult> => { const [related] = unwindEdges(shopifyProduct.collections) const operation = await syncSanityDocument(shopifyProduct) return { operation, related } } const completePair = async ( partialPair: RelatedPairPartial ): Promise<RelatedPair | null> => { const { shopifyNode, sanityDocument } = partialPair if (shopifyNode && sanityDocument) return { shopifyNode, sanityDocument } if (!shopifyNode && !sanityDocument) { throw new Error( 'A partial pair must have either a shopifyNode or a sanityDocument' ) } if (!shopifyNode && sanityDocument) { const fetchedShopifyItem = await fetchItemById( sanityDocument.shopifyId, false ) if (fetchedShopifyItem) { return { shopifyNode: fetchedShopifyItem, sanityDocument } } return null } if (shopifyNode && !sanityDocument) { const existingDoc = await documentByShopifyId(shopifyNode.id) if (existingDoc) { return { shopifyNode, sanityDocument: existingDoc, } } const completeShopifyItem = await fetchItemById(shopifyNode.id, false) if (!completeShopifyItem) return null const op = await syncSanityDocument(completeShopifyItem) return { shopifyNode, sanityDocument: op.sanityDocument, } } // typescript should know better throw new Error('how did we get here?') } const makeRelationships = async ({ operation, related, }: SyncOperationResult): Promise<LinkOperation> => { const { sanityDocument } = operation const initialPairs = await fetchRelatedDocs(related) const pairQueue = new PQueue({ concurrency: 1 }) const completePairs = await pairQueue.addAll( initialPairs.map((pair) => () => completePair(pair)) ) // At this point we have the already-synced document, // and all of the documents that it should be related to const relatedDocs = definitely<RelatedPair>(completePairs).map( ({ sanityDocument }) => sanityDocument ) const linkOperation = await syncRelationships(sanityDocument, relatedDocs) return linkOperation } const archiveProducts = async (products: Product[], logger: Logger) => { const allSanityProducts = await fetchAllSanityDocuments({ types: ['shopifyProduct'], }) // Find all sanity products that do not have corresponding Shopify products const productsToArchive = allSanityProducts.filter( (sanityDocument) => sanityDocument.sourceData.shopName && sanityDocument.sourceData.shopName === shopifyClient.shopName && sanityDocument.archived !== true && !Boolean( products.find( (shopifyProduct) => shopifyProduct.id === sanityDocument.shopifyId ) ) ) const archiveQueue = new PQueue({ concurrency: 1 }) await archiveQueue.addAll( productsToArchive.map((product) => async () => { await archiveSanityDocument(product) logger.logArchived(product) }) ) return productsToArchive } const archiveCollections = async ( collections: Collection[], logger: Logger ) => { const allSanityProducts = await fetchAllSanityDocuments({ types: ['shopifyCollection'], }) const collectionsToArchive = allSanityProducts.filter( (sanityDocument) => sanityDocument.sourceData.shopName && sanityDocument.sourceData.shopName === shopifyClient.shopName && sanityDocument.archived !== true && !Boolean( collections.find( (shopifyCollection) => shopifyCollection.id === sanityDocument.shopifyId ) ) ) const archiveQueue = new PQueue({ concurrency: 1 }) await archiveQueue.addAll( collectionsToArchive.map((collection) => async () => { await archiveSanityDocument(collection) logger.logArchived(collection) }) ) return collectionsToArchive } /** * Public API methods * * These are responsible for: * - coordinating the fetching, syncing, and linking of docs * - logging the events */ /* Initializes the syncState */ const initialize = async (secrets: ShopifySecrets) => { await migrateSanityConfig(sanityClient) const { isError } = await testSecrets(secrets) init(!isError, secrets.shopName) } /* Saves the Storefront name and API key to Sanity */ const saveConfig = async ( storefront: string, secrets: UpdateConfigDocumentArgs ) => { const { isError, message } = await testSecrets(secrets) if (isError) { onSavedSecretsError(new Error(message)) return } await saveConfigToSanity(storefront, secrets) onSavedSecrets(secrets.shopName) } const testConfig = async (secrets: ShopifySecrets) => { return testSecrets(secrets) } const clearConfig = async (storefront: string) => { await clearConfigFromSanity(storefront) onClearedSecrets() } const syncItem = async ( itemId: string, shopifyItem: Product | Collection | null, cbs: SubscriptionCallbacks = {} ) => { const logger = createLogger(cbs) if (!shopifyItem) { onFetchComplete() const sanityDoc = await documentByShopifyId(itemId) if (sanityDoc) { archiveSanityDocument(sanityDoc) } onComplete() return } onDocumentsFetched([shopifyItem]) logger.logFetched(shopifyItem) onFetchComplete() if (shopifyItem.__typename === 'Product') { const syncResult = await syncProduct(shopifyItem) onDocumentSynced(syncResult.operation) logger.logSynced(syncResult.operation) const linkOperation = await makeRelationships(syncResult) onDocumentLinked(linkOperation) logger.logLinked(syncResult.operation.sanityDocument, linkOperation.pairs) onComplete() return } if (shopifyItem.__typename === 'Collection') { const syncResult = await syncCollection(shopifyItem) onDocumentSynced(syncResult.operation) logger.logSynced(syncResult.operation) const linkOperation = await makeRelationships(syncResult) onDocumentLinked(linkOperation) logger.logLinked(syncResult.operation.sanityDocument, linkOperation.pairs) onComplete() return } // @ts-ignore throw new Error(`Item type ${shopifyItem.__typename} is not supported`) } /* Sync an item by ID */ const syncItemByID = async (id: string, cbs: SubscriptionCallbacks = {}) => { startSync() const shopifyItem = await fetchItemById(id, true) return syncItem(id, shopifyItem, cbs) } /* Syncs all products */ const syncProducts = async (cbs: SubscriptionCallbacks = {}) => { startSync() // do an initial fetch of all docs to populate the cache await fetchAllSanityDocuments() const logger = createLogger(cbs) const onProgress = (products: Product[]) => { onDocumentsFetched(products) } const allProducts = await fetchAllShopifyProducts(onProgress) logger.logFetched(allProducts) onFetchComplete() const queue = new PQueue({ concurrency: 1 }) const results = await queue.addAll( allProducts.map((product) => async () => { const result = await syncProduct(product) onDocumentSynced(result.operation) logger.logSynced(result.operation) return result }) ) const relationshipQueue = new PQueue({ concurrency: 1 }) await relationshipQueue.addAll( results.map((result) => async () => { const linkOperation = await makeRelationships(result) logger.logLinked(result.operation.sanityDocument, linkOperation.pairs) onDocumentLinked(linkOperation) return linkOperation.pairs }) ) await archiveProducts(allProducts, logger) onComplete() } /* Syncs all collections */ const syncCollections = async (cbs: SubscriptionCallbacks = {}) => { startSync() // do an initial fetch of all docs to populate the cache await fetchAllSanityDocuments() const logger = createLogger(cbs) const onProgress = (collections: Collection[]) => { onDocumentsFetched(collections) } const allCollections = await fetchAllShopifyCollections(onProgress) logger.logFetched(allCollections) onFetchComplete() const queue = new PQueue({ concurrency: 1 }) const results = await queue.addAll( allCollections.map((collection) => async () => { const result = await syncCollection(collection) onDocumentSynced(result.operation) logger.logSynced(result.operation) return result }) ) const relationshipQueue = new PQueue({ concurrency: 1 }) await relationshipQueue.addAll( results.map((result) => async () => { const linkOperation = await makeRelationships(result) logger.logLinked(result.operation.sanityDocument, linkOperation.pairs) onDocumentLinked(linkOperation) return linkOperation.pairs }) ) await archiveCollections(allCollections, logger) onComplete() } const syncAll = async (cbs: SubscriptionCallbacks = {}) => { startSync() // do an initial fetch of all docs to populate the cache await fetchAllSanityDocuments() const onProgress = (items: Collection[] | Product[]) => { onDocumentsFetched(items) } const logger = createLogger(cbs) const fetchCollections = async () => { const collections = await fetchAllShopifyCollections(onProgress) return collections } const fetchProducts = async () => { const products = await fetchAllShopifyProducts(onProgress) return products } const allProducts = await fetchProducts() const allCollections = await fetchCollections() const allItems = [...allCollections, ...allProducts] onFetchComplete() const queue = new PQueue({ concurrency: 1 }) const results = await queue.addAll( allItems.map((item) => async () => { const result = item.__typename === 'Collection' ? await syncCollection(item) : item.__typename === 'Product' ? await syncProduct(item) : null if (result === null) throw new Error('Could not sync item') onDocumentSynced(result.operation) logger.logSynced(result.operation) return result }) ) const relationshipQueue = new PQueue({ concurrency: 1 }) await relationshipQueue.addAll( results.map((result) => async () => { const linkOperation = await makeRelationships(result) logger.logLinked(result.operation.sanityDocument, linkOperation.pairs) onDocumentLinked(linkOperation) return linkOperation.pairs }) ) await archiveProducts(allProducts, logger) await archiveCollections(allCollections, logger) onComplete() } // TODO: Uncomment and expose this to the API // + add docs // const deleteArchivedDocuments = async () => { // const query = '*[_type == "shopifyProduct" || _type == "shopifyCollection"]' // await sanityClient // .patch({ query }) // .unset(['products', 'collections']) // .commit() // const deletequery = '*[defined(archived) && archived == true]' // // await sanityClient.delete( // { query: deletequery }, // { returnFirst: false, returnDocuments: true } // ) // } return { initialize, initialState, saveConfig, testConfig, clearConfig, syncProducts, syncCollections, syncAll, syncItem, fetchItemById, syncItemByID, } } export const createSyncingClient = ({ secrets, onStateChange, }: SaneShopifyConfig): SyncUtils => { const { sanity, shopify } = secrets const sanityClient = createSanityClient({ apiVersion: sanity?.apiVersion || '2021-03-20', projectId: sanity.projectId, dataset: sanity.dataset, token: sanity.authToken, useCdn: false, }) const shopifyClient = createShopifyClient(shopify) return syncUtils(shopifyClient, sanityClient, onStateChange) }
the_stack
export interface BulmaTagsInputItem { value: string; text: string; } export interface BulmaTagsInputOptions { /** * When true, the same tag can be added multiple times. * * @default false */ allowDuplicates?: boolean | undefined; /** * When true, duplicate tags value check is case sensitive. * * @default true */ caseSensitive?: boolean | undefined; /** * When true, tags will be unselected when new tag is entered. * * @default false */ clearSelectionOnTyping?: boolean | undefined; /** * When true, datalist will close automatically after an item have been selected. * * @default true */ closeDropdownOnItemSelect?: boolean | undefined; /** * Multiple tags can be added at once. Delimiter is used to separate all tags. * * @default ",", */ delimiter?: string | undefined; /** * When true, tags can be entered manually. This option is useful with select Tags inputs. Set * to false automatically when using on select element. * * @default true */ freeInput?: boolean | undefined; /** * When true, if `allowDuplicates` option if false then the already existing tag will be * temporarly and visually identified as duplicate * * @default true */ highlightDuplicate?: boolean | undefined; /** * When true, identified matches strings when searching is highlighted. * * @default true */ highlightMatchesString?: boolean | undefined; /** * When adding objects as tags, you can set itemText to the name of the property of item to use * for a its tag's text. When this options is not set, the value of _itemValue_ will be used. */ itemText?: string | undefined; /** * When adding objects as tags, itemValue must be set to the name of the property containing the * item's value. */ itemValue?: string | undefined; /** * When set, no more than the given number of tags are allowed to add. */ maxTags?: number | undefined; /** * Defines the maximum length of a single tag. */ maxChars?: number | undefined; /** * Defines the minimum length of a single tag. * * @default 1 */ minChars?: number | undefined; /** * Empty dropdown label. * * @default "No results found" */ noResultsLabel?: string | undefined; /** * TagsInput placeholder text if original input doesn't have one. * * @default undefined */ placeholder?: string | undefined; /** * When true, tags are removable either using the associted delete button or _backspace_ and * _delete_ keys. * * @default true */ removable?: boolean | undefined; /** * Defines the minimum length of input value before loading auto-complete. * * @default 1 */ searchMinChars?: number | undefined; /** * Defines on what dropdown item data do we search the entered value. * * @default "text" */ searchOn?: 'value' | 'text' | undefined; /** * When true, tags can be selected either by mouse click or using _left_ or _right_ arrow keys. * * @default true */ selectable?: boolean | undefined; /** * Source of data proposed in dropdown (used for auto-complete). * * @default undefined */ source?: | Array<string | BulmaTagsInputItem> | (() => Array<string | BulmaTagsInputItem>) | Promise<Array<string | BulmaTagsInputItem>> | undefined; /** * Classname applied to each tag. * * @default "is-rounded" */ tagClass?: string | undefined; /** * When true, automatically removes all whitespace around tags. * * @default true */ trim?: boolean | undefined; } export interface BulmaTagsInputEventMap { /** * Trigerred before adding new tag. The concerned item is passed as parameter. You can modify the item * before its treatment by returning the new item data or prevent tag to be added by returning false. */ 'before.add': string | BulmaTagsInputItem; /** * Triggered once a tag has been added. The added item and the related tag are passed in an object as * parameter. */ 'after.add': { item: string | BulmaTagsInputItem; tag: string; }; /** * Triggered before removing a tag. The concerned item is passed as parameter. You can prevent * deletion by returning `false`. */ 'before.remove': string | BulmaTagsInputItem; /** * Triggered once a tag has been removed. The removed item is passed as parameter. */ 'after.remove': string | BulmaTagsInputItem; /** * Triggered before flushing items. Items array is passed as parameter. */ 'before.flush': Array<string | BulmaTagsInputItem>; /** * Triggered after flushing items. */ 'after.flush': Array<string | BulmaTagsInputItem>; /** * Triggered before selecting an item. The concerned item and related tag are passed in an * Object as parameter. */ 'before.select': { item: string | BulmaTagsInputItem; tag: string; }; /** * Triggered once an item has been selected. The concerned item and related tag are passed in * an Object as parameter. */ 'after.select': { item: string | BulmaTagsInputItem; tag: string; }; /** * Triggered before unselect an item. The concerned item and related tag are passed in an Object * as parameter. */ 'before.unselect': { item: string | BulmaTagsInputItem; tag: string; }; /** * Triggered once an item has been unselected. The concerned item and related tag are passed in * an Object as parameter. */ 'after.unselect': { item: string | BulmaTagsInputItem; tag: string; }; } export default class BulmaTagsInput { /** * @param selector query string returning a single Node or directly a Node */ constructor(selector: string | HTMLInputElement, options?: BulmaTagsInputOptions); /** * DOM modifications will be observed to detect any new element responding to the given selector * to automatically instantiate BulmaTagsInput on them with the given option. * * @param selector selector can be a query string returning a single Node or a NodeList, directly * a Node or a NodeList */ static attach(selector: string | HTMLInputElement, options?: BulmaTagsInputOptions): BulmaTagsInput; /** * Add given item to the component. * * @param item Item to add. * * You can provide multiple items at once by passing and Array of item or a string with multiple * value delimited by delimiter option (default: comma). */ add(item: string | BulmaTagsInputItem | Array<string | BulmaTagsInputItem>): this; /** * Unselect the current selected tag. */ clearSelection(): this; /** * Shortcut to removeAll method */ flush(): this; /** * Sets focus on the input */ focus(): this; /** * Check if given item is present * * @param item Item to find. */ has(item: string | BulmaTagsInputItem): boolean; /** * Check if given value is present * * @param value Single value to find. */ hasValue(value: string): boolean; /** * Check if given text is present * * @param text single Text to find in items. */ hasText(value: string): boolean; /** * CGet index of given item * * @param item Item to find. */ indexOf(item: string | BulmaTagsInputItem): number; /** * Get the internal input element */ input: HTMLInputElement; /** * Get all added items */ items: Array<string | BulmaTagsInputItem>; /** * Remove given items * * @param item Item to add * * You can provide multiple items at once by passing and Array of item or a string with multiple * value delimited by delimiter option (default: comma). */ remove(item: string | BulmaTagsInputItem | Array<string | BulmaTagsInputItem>): this; /** * Remove all tags at once */ removeAll(): this; /** * Remove item at given index. * * @param index Index of the item to remove. * @param clearSelection Should current selection be cleared */ removeAtIndex(index: number, clearSelection: boolean): this; /** * Select given item * * @param item Item to add. * * You can provide multiple items at once by passing and Array of item or a string with multiple * value delimited by delimiter option (default: comma). If a list of items is passed then each * item will be selected one by one and at the end only the last existing item from the list will * be selected at the end. */ select(item: string | BulmaTagsInputItem): this; /** * Select tag at given index * * @param index Index of the item to select. */ selectAtIndex(index: number): this; /** * Get the current selected item */ selected: string | BulmaTagsInputItem; /** * Get the current selected item index */ selectedIndex: number; /** * Get component value */ value: string | string[]; // EventEmitter functions /** * Destroys EventEmitter */ destroy(): void; /** * Count listeners registered for the provided eventName */ listenerCount(eventName: string): number; /** * Subscribes on event eventName specified function * * @param eventName * @param listener */ on<T extends keyof BulmaTagsInputEventMap>(eventName: T, listener: (item: BulmaTagsInputEventMap[T]) => any): void; /** * Subscribes on event name specified function to fire only once */ once<T extends keyof BulmaTagsInputEventMap>( eventName: T, listener: (item: BulmaTagsInputEventMap[T]) => any, ): void; /** * Removes event with specified eventName. */ off(eventName: string): void; }
the_stack
import * as imageLoaded from 'image-loaded' import * as raf from 'raf' import Spriteling from '../spriteling' jest.setTimeout(1000) // Mock imageLoaded imageLoaded.default = jest.fn((a, b) => { a.width = 100 a.height = 100 b() }) // Mock dummy RAF raf.default = jest.fn() raf.default.cancel = jest.fn() // Mock RAF to play x amount of frames let workingRafTimeout const workingRaf = (framesToRender: number, delay: number) => { let time = 0 return (a) => { if (framesToRender) { framesToRender-- workingRafTimeout = setTimeout(() => { a(time += delay) }, delay) } } } // Mock element.offsetParent property Object.defineProperties((window as any).HTMLElement.prototype, { offsetParent: { get: () => 0 } }) // Example animation script const myScriptName = 'my-script' const myAnimationScript = [ {sprite: 2}, {sprite: 3, delay: 100}, {sprite: 7, top: 1}, {sprite: 1, right: 2}, {sprite: 5, bottom: 3}, {sprite: 6, left: 4} ] describe('Playback', () => { let instance beforeEach(() => { instance = new Spriteling({url: './some-image.png', cols: 5, rows: 10}) }) describe('showSprite()', () => { it('should wait for loading promise to be fullfilled', async () => { instance.drawFrame = jest.fn() const r = instance.showSprite(2) await r expect(r instanceof Promise).toBe(true) expect(instance.drawFrame.mock.calls.length).toBe(1) }) it('should set playhead to stop', async () => { instance.playhead.play = true await instance.showSprite(2) expect(instance.isPlaying()).toBe(false) }) it('should show the specified sprite', async () => { await instance.showSprite(7) expect(instance.element.style.backgroundPosition).toBe('-20px -10px') await instance.showSprite(13) expect(instance.element.style.backgroundPosition).toBe('-40px -20px') }) it('should warn when the specified sprite is out of bounds', async () => { console.warn = jest.fn() await instance.showSprite(70) expect(console.warn).toHaveBeenCalledWith('Spriteling', 'position 70 out of bound') }) }) describe('currentSprite()', () => { it('should return the current sprite', async () => { await instance.showSprite(7) const r = await instance.currentSprite(7) expect(r).toBe(7) }) }) describe('addScript', () => { it('should store named animation script', () => { instance.addScript(myScriptName, myAnimationScript) expect(instance.spriteSheet.animations[myScriptName]).toEqual(myAnimationScript) }) }) describe('play()', () => { beforeEach(() => { instance.addScript(myScriptName, myAnimationScript) }) it('should play indefinite when called without parameters', async () => { await instance.play() expect(instance.playhead.play).toBe(true) expect(instance.playhead.run).toBe(-1) }) it('should play once when called without parameters after animation has stopped', async () => { instance.playhead.play = false instance.playhead.run = 0 await instance.play() expect(instance.playhead.play).toBe(true) expect(instance.playhead.run).toBe(1) }) it('should play script when called with scriptName', async () => { await instance.play(myScriptName) expect(instance.playhead.script).toBe(myAnimationScript) expect(instance.playhead.play).toBe(true) expect(instance.playhead.run).toBe(-1) }) it('should play script + options when called with scriptName + options', async () => { await instance.play(myScriptName, { run: 2, delay: 3, tempo: 4, reversed: true }) expect(instance.playhead).toMatchSnapshot() }) it('should play "all" animation when scriptName is not found', async () => { await instance.play('unknown script', { run: 2 }) expect(instance.playhead.script.length).toBe(50) }) it('should play current + options when called with options', async () => { await instance.play(myScriptName, {}) await instance.play({ run: 20, delay: 3, tempo: 4 }) expect(instance.playhead).toMatchSnapshot() }) it('should play script + options when called with options and embedded new script', async () => { const embeddedScript = [ {sprite: 4}, {sprite: 3} ] await instance.play({ run: 1, reversed: true, script: embeddedScript }) expect(instance.playhead.script).toEqual(embeddedScript) }) it('should call onPlay when provided', async (done) => { await instance.play(myScriptName, { run: 1, onPlay: done }) }) it('should call onStop when provided and stop() is called', async (done) => { await instance.play(myScriptName, { run: 1, onStop: done }) instance.stop() }) it('should call onFrame when provided', async (done) => { await instance.play(myScriptName, { run: 1, onFrame: (currentFrame) => { expect(currentFrame).toBe(0) done() } }) }) it('should call onOutOfView when provided and element is no longer in view', async (done) => { // Fake out-of-view instance.inViewport = jest.fn(() => false) await instance.play({ run: 1, onOutOfView: done }) }) it('should apply positioning per frame', async (done) => { await instance.play({ run: 1, script: [ {sprite: 4, top: 10, right: 20, bottom: 30, left: 40}, {sprite: 3, top: 10, right: 20, bottom: 30, left: 40}, {sprite: 2, top: 10, right: 20, bottom: 30, left: 40}, {sprite: 1, top: 10, right: 20, bottom: 30, left: 40} ] }) await instance.next() expect(instance.element.style.top).toBe('10px') expect(instance.element.style.right).toBe('20px') expect(instance.element.style.bottom).toBe('30px') expect(instance.element.style.left).toBe('40px') done() }) it('should play script forwards', async (done) => { const delay = 10 const simpleScript = [ {sprite: 1}, {sprite: 2}, {sprite: 3}, {sprite: 4} ] let counter = 0 raf.default.mockImplementation(workingRaf(4, delay)) await instance.play({ run: 1, delay, script: simpleScript, onFrame: (frameNumber) => { expect(frameNumber).toBe(counter) counter++ }, onStop: () => { clearTimeout(workingRafTimeout) done() } }) }) it('should play script reversed', async (done) => { const delay = 10 const simpleScript = [ {sprite: 1}, {sprite: 2}, {sprite: 3}, {sprite: 4} ] let counter = 3 raf.default.mockImplementation(workingRaf(4, delay)) await instance.play({ run: 1, delay, script: simpleScript, reversed: true, onFrame: (frameNumber) => { expect(frameNumber).toBe(counter) counter-- }, onStop: () => { clearTimeout(workingRafTimeout) done() } }) }) it('should stop when run reached 0', async (done) => { const delay = 10 const simpleScript = [ {sprite: 1}, {sprite: 2}, {sprite: 3}, {sprite: 4} ] raf.default.mockImplementation(workingRaf(5, delay)) await instance.play({ run: 1, delay, script: simpleScript, reversed: true, onStop: () => { setTimeout(() => { clearTimeout(workingRafTimeout) expect(raf.default.cancel).toHaveBeenCalled() done() }, 100) } }) }) it('should set nextDelay', async (done) => { const delay = 40 const simpleScript = [ {sprite: 1, delay: 10}, {sprite: 2, delay: 20}, {sprite: 3, delay: 30}, {sprite: 4, delay: 40} ] raf.default.mockImplementation(workingRaf(4, delay)) await instance.play({ run: 1, delay, script: simpleScript, onFrame: (c) => { expect(instance.playhead.nextDelay).toBe(simpleScript[c].delay) }, onStop: () => { clearTimeout(workingRafTimeout) done() } }) }) it('should set nextDelay based on tempo', async (done) => { const delay = 40 const tempo = 2 const simpleScript = [ {sprite: 1, delay: 10}, {sprite: 2, delay: 20}, {sprite: 3, delay: 30}, {sprite: 4, delay: 40} ] raf.default.mockImplementation(workingRaf(4, delay)) await instance.play({ run: 1, delay, script: simpleScript, tempo, onFrame: (c) => { expect(instance.playhead.nextDelay).toBe(simpleScript[c].delay / tempo) }, onStop: () => { clearTimeout(workingRafTimeout) done() } }) }) }) describe('isPlaying()', () => { it('should return the playing state', () => { instance.playhead.play = false expect(instance.isPlaying()).toBe(false) instance.playhead.play = true expect(instance.isPlaying()).toBe(true) }) }) describe('setTempo()', () => { it('should set the tempo', async () => { instance.playhead.tempo = 1 await instance.setTempo(2) expect(instance.playhead.tempo).toBe(2) }) }) describe('getTempo()', () => { it('should get the tempo', () => { instance.playhead.tempo = .5 expect(instance.getTempo()).toBe(.5) }) }) describe('next()', () => { it('should draw next frame', async () => { const simpleScript = [ {sprite: 1, delay: 10}, {sprite: 2, delay: 20}, {sprite: 3, delay: 30}, {sprite: 4, delay: 40} ] instance.drawFrame = jest.fn() await instance.play({ play: false, run: 1, script: simpleScript }) await instance.next() expect(instance.drawFrame).toHaveBeenCalledWith({delay: 10, sprite: 1}) await instance.next() expect(instance.drawFrame).toHaveBeenCalledWith({delay: 20, sprite: 2}) await instance.next() expect(instance.drawFrame).toHaveBeenCalledWith({delay: 30, sprite: 3}) await instance.next() expect(instance.drawFrame).toHaveBeenCalledWith({delay: 40, sprite: 4}) await instance.next() expect(instance.drawFrame).toHaveBeenCalledWith({delay: 10, sprite: 1}) }) }) describe('previous()', () => { it('should draw previous frame', async () => { const simpleScript = [ {sprite: 1, delay: 10}, {sprite: 2, delay: 20}, {sprite: 3, delay: 30}, {sprite: 4, delay: 40} ] instance.drawFrame = jest.fn() await instance.play({ play: false, run: 1, script: simpleScript }) await instance.previous() expect(instance.drawFrame).toHaveBeenCalledWith({delay: 40, sprite: 4}) await instance.previous() expect(instance.drawFrame).toHaveBeenCalledWith({delay: 30, sprite: 3}) await instance.previous() expect(instance.drawFrame).toHaveBeenCalledWith({delay: 20, sprite: 2}) await instance.previous() expect(instance.drawFrame).toHaveBeenCalledWith({delay: 10, sprite: 1}) }) }) // TODO // xdescribe('goTo()', () => { // it('should', () => { // }) // }) // // xdescribe('reverse()', () => { // it('should', () => { // }) // }) // // xdescribe('isReversed()', () => { // it('should', () => { // }) // }) // // xdescribe('stop()', () => { // it('should', () => { // }) // }) // // xdescribe('reset()', () => { // it('should', () => { // }) // }) })
the_stack
/// Imports of 3rd Party /// import url = require("url"); import path = require("path"); /// Import base rest class /// import * as restm from 'typed-rest-client/RestClient'; import ifm = require("./interfaces/common/VsoBaseInterfaces"); interface VssApiResourceLocationLookup { [locationId: string]: ifm.ApiResourceLocation; } export interface ClientVersioningData { /** * The api version string to send in the request (e.g. "1.0" or "2.0-preview.2") */ apiVersion?: string; /** * The request path string to send the request to. Looked up via an options request with the location id. */ requestUrl?: string; } export class InvalidApiResourceVersionError implements Error { public name: string = "Invalid resource version"; public message: string; constructor(message?: string) { this.message = message; } } /** * Base class that should be used (derived from) to make requests to VSS REST apis */ export class VsoClient { private static APIS_RELATIVE_PATH = "_apis"; private static PREVIEW_INDICATOR = "-preview."; private _locationsByAreaPromises: { [areaName: string]: Promise<VssApiResourceLocationLookup>; }; private _initializationPromise: Promise<any>; restClient: restm.RestClient; baseUrl: string; basePath: string; constructor(baseUrl: string, restClient: restm.RestClient) { this.baseUrl = baseUrl; this.basePath = url.parse(baseUrl).pathname; this.restClient = restClient; this._locationsByAreaPromises = {}; this._initializationPromise = Promise.resolve(true); } protected autoNegotiateApiVersion(location: ifm.ApiResourceLocation, requestedVersion: string): string { let negotiatedVersion: string; let apiVersion: number; let apiVersionString: string; if (requestedVersion) { let apiVersionRegEx = new RegExp('(\\d+(\\.\\d+)?)(-preview(\\.(\\d+))?)?'); // Need to handle 3 types of api versions + invalid apiversion // '2.1-preview.1' = ["2.1-preview.1", "2.1", ".1", -preview.1", ".1", "1"] // '2.1-preview' = ["2.1-preview", "2.1", ".1", "-preview", undefined, undefined] // '2.1' = ["2.1", "2.1", ".1", undefined, undefined, undefined] let isPreview = false; let resourceVersion: number; let regExExecArray = apiVersionRegEx.exec(requestedVersion); if (regExExecArray) { if (regExExecArray[1]) { // we have an api version apiVersion = +regExExecArray[1]; apiVersionString = regExExecArray[1]; if (regExExecArray[3]) { // requesting preview isPreview = true; if (regExExecArray[5]) { // we have a resource version resourceVersion = +regExExecArray[5]; } } // compare the location version and requestedversion if (apiVersion <= +location.releasedVersion || (!resourceVersion && apiVersion <= +location.maxVersion && isPreview) || (resourceVersion && apiVersion <= +location.maxVersion && resourceVersion <= +location.resourceVersion)) { negotiatedVersion = requestedVersion; } // else fall back to latest version of the resource from location } } } if (!negotiatedVersion) { // Use the latest version of the resource if the api version was not specified in the request or if the requested version is higher then the location's supported version if (apiVersion < +location.maxVersion) { negotiatedVersion = apiVersionString + "-preview"; } else if (location.maxVersion === location.releasedVersion) { negotiatedVersion = location.maxVersion; } else { negotiatedVersion = location.maxVersion + "-preview." + location.resourceVersion; } } return negotiatedVersion; } /** * Gets the route template for a resource based on its location ID and negotiates the api version */ public getVersioningData(apiVersion: string, area: string, locationId: string, routeValues: any, queryParams?: any): Promise<ClientVersioningData> { let requestUrl; return this.beginGetLocation(area, locationId) .then((location: ifm.ApiResourceLocation): ClientVersioningData => { if (!location) { throw new Error("Failed to find api location for area: " + area + " id: " + locationId); } apiVersion = this.autoNegotiateApiVersion(location, apiVersion); requestUrl = this.getRequestUrl(location.routeTemplate, location.area, location.resourceName, routeValues, queryParams); return { apiVersion: apiVersion, requestUrl: requestUrl }; }); } /** * Sets a promise that is waited on before any requests are issued. Can be used to asynchronously * set the request url and auth token manager. */ public _setInitializationPromise(promise: Promise<any>) { if (promise) { this._initializationPromise = promise; } } /** * Gets information about an API resource location (route template, supported versions, etc.) * * @param area resource area name * @param locationId Guid of the location to get */ public beginGetLocation(area: string, locationId: string): Promise<ifm.ApiResourceLocation> { return this._initializationPromise.then(() => { return this.beginGetAreaLocations(area); }).then((areaLocations: VssApiResourceLocationLookup) => { return areaLocations[(locationId || "").toLowerCase()]; }); } private beginGetAreaLocations(area: string): Promise<VssApiResourceLocationLookup> { let areaLocationsPromise = this._locationsByAreaPromises[area]; if (!areaLocationsPromise) { let requestUrl = this.resolveUrl(VsoClient.APIS_RELATIVE_PATH + "/" + area); areaLocationsPromise = this.restClient.options<any>(requestUrl) .then((res:restm.IRestResponse<any>) => { let locationsLookup: VssApiResourceLocationLookup = {}; let resourceLocations: ifm.ApiResourceLocation[] = res.result.value; let i; for (i = 0; i < resourceLocations.length; i++) { let resourceLocation = resourceLocations[i]; locationsLookup[resourceLocation.id.toLowerCase()] = resourceLocation; } // If we have completed successfully, cache the response. this._locationsByAreaPromises[area] = areaLocationsPromise; return locationsLookup; }); } return areaLocationsPromise; } public resolveUrl(relativeUrl: string): string { return url.resolve(this.baseUrl, path.join(this.basePath, relativeUrl)); } private queryParamsToStringHelper(queryParams: any, prefix: string): string { if (!queryParams) { return ''; } let queryString: string = ''; if (typeof(queryParams) !== 'string') { for (let property in queryParams) { if (queryParams.hasOwnProperty(property)) { const prop = queryParams[property]; const newPrefix = prefix + encodeURIComponent(property.toString()) + '.'; queryString += this.queryParamsToStringHelper(prop, newPrefix); } } } if (queryString === '' && prefix.length > 0){ // Date.prototype.toString() returns a string that is not valid for the REST API. // Need to specially call `toUTCString()` instead for such cases const queryValue = typeof queryParams === 'object' && 'toUTCString' in queryParams ? (queryParams as Date).toUTCString() : queryParams.toString(); // Will always need to chop period off of end of prefix queryString = prefix.slice(0,-1) + '=' + encodeURIComponent(queryValue) + '&'; } return queryString; } private queryParamsToString(queryParams: any): string { const queryString: string = '?' + this.queryParamsToStringHelper(queryParams, ''); // Will always need to slice either a ? or & off of the end return queryString.slice(0,-1); } protected getRequestUrl(routeTemplate: string, area: string, resource: string, routeValues: any, queryParams?: any): string { // Add area/resource route values (based on the location) routeValues = routeValues || {}; if (!routeValues.area) { routeValues.area = area; } if (!routeValues.resource) { routeValues.resource = resource; } // Replace templated route values let relativeUrl = this.replaceRouteValues(routeTemplate, routeValues); // Append query parameters to the end if (queryParams) { relativeUrl += this.queryParamsToString(queryParams); } // Resolve the relative url with the base return url.resolve(this.baseUrl, path.join(this.basePath, relativeUrl)); } // helper method copied directly from VSS\WebAPI\restclient.ts private replaceRouteValues(routeTemplate: string, routeValues: any): string { let result = "", currentPathPart = "", paramName = "", insideParam = false, charIndex: number, routeTemplateLength = routeTemplate.length, c: string; for (charIndex = 0; charIndex < routeTemplateLength; charIndex++) { c = routeTemplate[charIndex]; if (insideParam) { if (c == "}") { insideParam = false; if (routeValues[paramName]) { currentPathPart += encodeURIComponent(routeValues[paramName]); } else { // Normalize param name in order to capture wild-card routes let strippedParamName = paramName.replace(/[^a-z0-9]/ig, ''); if (routeValues[strippedParamName]) { currentPathPart += encodeURIComponent(routeValues[strippedParamName]); } } paramName = ""; } else { paramName += c; } } else { if (c == "/") { if (currentPathPart) { if (result) { result += "/"; } result += currentPathPart; currentPathPart = ""; } } else if (c == "{") { if ((charIndex + 1) < routeTemplateLength && routeTemplate[charIndex + 1] == "{") { // Escaped '{' currentPathPart += c; charIndex++; } else { insideParam = true; } } else if (c == '}') { currentPathPart += c; if ((charIndex + 1) < routeTemplateLength && routeTemplate[charIndex + 1] == "}") { // Escaped '}' charIndex++; } } else { currentPathPart += c; } } } if (currentPathPart) { if (result) { result += "/"; } result += currentPathPart; } return result; } }
the_stack
module Rx { export interface Observable<T> { /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence which performs a exclusive waiting for the first to finish before subscribing to another observable. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time performs a exclusive waiting for the first to finish before subscribing to another observable. */ selectSwitchFirst<TResult>(selector: _ValueOrSelector<T, ObservableOrPromise<TResult>>): Observable<TResult>; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence which performs a exclusive waiting for the first to finish before subscribing to another observable. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time performs a exclusive waiting for the first to finish before subscribing to another observable. */ selectSwitchFirst<TResult>(selector: _ValueOrSelector<T, ArrayOrIterable<TResult>>): Observable<TResult>; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence which performs a exclusive waiting for the first to finish before subscribing to another observable. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time performs a exclusive waiting for the first to finish before subscribing to another observable. */ selectSwitchFirst<TOther, TResult>(selector: _ValueOrSelector<T, ObservableOrPromise<TOther>>, resultSelector: special._FlatMapResultSelector<T, TOther, TResult>, thisArg?: any): Observable<TResult>; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence which performs a exclusive waiting for the first to finish before subscribing to another observable. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time performs a exclusive waiting for the first to finish before subscribing to another observable. */ selectSwitchFirst<TOther, TResult>(selector: _ValueOrSelector<T, ArrayOrIterable<TOther>>, resultSelector: special._FlatMapResultSelector<T, TOther, TResult>, thisArg?: any): Observable<TResult>; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence which performs a exclusive waiting for the first to finish before subscribing to another observable. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time performs a exclusive waiting for the first to finish before subscribing to another observable. */ flatMapFirst<TResult>(selector: _ValueOrSelector<T, ObservableOrPromise<TResult>>): Observable<TResult>; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence which performs a exclusive waiting for the first to finish before subscribing to another observable. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time performs a exclusive waiting for the first to finish before subscribing to another observable. */ flatMapFirst<TResult>(selector: _ValueOrSelector<T, ArrayOrIterable<TResult>>): Observable<TResult>; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence which performs a exclusive waiting for the first to finish before subscribing to another observable. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time performs a exclusive waiting for the first to finish before subscribing to another observable. */ flatMapFirst<TOther, TResult>(selector: _ValueOrSelector<T, ObservableOrPromise<TOther>>, resultSelector: special._FlatMapResultSelector<T, TOther, TResult>, thisArg?: any): Observable<TResult>; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence which performs a exclusive waiting for the first to finish before subscribing to another observable. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time performs a exclusive waiting for the first to finish before subscribing to another observable. */ flatMapFirst<TOther, TResult>(selector: _ValueOrSelector<T, ArrayOrIterable<TOther>>, resultSelector: special._FlatMapResultSelector<T, TOther, TResult>, thisArg?: any): Observable<TResult>; } } (function() { var o: Rx.Observable<string>; var n: Rx.Observable<number>; n = o.flatMapFirst(x => Rx.Observable.from([1, 2, 3])); n = o.flatMapFirst(x => Rx.Observable.from([1, 2, 3]).toPromise()); n = o.flatMapFirst(x => [1, 2, 3]); n = o.flatMapFirst(x => Rx.Observable.from([1, 2, 3]), (x, y) => y); n = o.flatMapFirst(x => Rx.Observable.from([1, 2, 3]).toPromise(), (x, y) => y); n = o.flatMapFirst(x => [1, 2, 3], (x, y) => y); n = o.flatMapFirst(Rx.Observable.from([1, 2, 3])); n = o.flatMapFirst(Rx.Observable.from([1, 2, 3]).toPromise()); n = o.flatMapFirst([1, 2, 3]); n = o.flatMapFirst(Rx.Observable.from([1, 2, 3]), (x, y) => y); n = o.flatMapFirst(Rx.Observable.from([1, 2, 3]).toPromise(), (x, y) => y); n = o.flatMapFirst([1, 2, 3], (x, y) => y); n = o.selectSwitchFirst(x => Rx.Observable.from([1, 2, 3])); n = o.selectSwitchFirst(x => Rx.Observable.from([1, 2, 3]).toPromise()); n = o.selectSwitchFirst(x => [1, 2, 3]); n = o.selectSwitchFirst(x => Rx.Observable.from([1, 2, 3]), (x, y) => y); n = o.selectSwitchFirst(x => Rx.Observable.from([1, 2, 3]).toPromise(), (x, y) => y); n = o.selectSwitchFirst(x => [1, 2, 3], (x, y) => y); n = o.selectSwitchFirst(Rx.Observable.from([1, 2, 3])); n = o.selectSwitchFirst(Rx.Observable.from([1, 2, 3]).toPromise()); n = o.selectSwitchFirst([1, 2, 3]); n = o.selectSwitchFirst(Rx.Observable.from([1, 2, 3]), (x, y) => y); n = o.selectSwitchFirst(Rx.Observable.from([1, 2, 3]).toPromise(), (x, y) => y); n = o.selectSwitchFirst([1, 2, 3], (x, y) => y); });
the_stack
import * as $protobuf from "protobufjs"; /** Namespace google. */ export namespace google { /** Namespace api. */ namespace api { /** Properties of a Http. */ interface IHttp { /** Http rules */ rules?: (google.api.IHttpRule[]|null); /** Http fully_decode_reserved_expansion */ fully_decode_reserved_expansion?: (boolean|null); } /** Represents a Http. */ class Http implements IHttp { /** * Constructs a new Http. * @param [properties] Properties to set */ constructor(properties?: google.api.IHttp); /** Http rules. */ public rules: google.api.IHttpRule[]; /** Http fully_decode_reserved_expansion. */ public fully_decode_reserved_expansion: boolean; /** * Creates a new Http instance using the specified properties. * @param [properties] Properties to set * @returns Http instance */ public static create(properties?: google.api.IHttp): google.api.Http; /** * Encodes the specified Http message. Does not implicitly {@link google.api.Http.verify|verify} messages. * @param message Http message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Http message, length delimited. Does not implicitly {@link google.api.Http.verify|verify} messages. * @param message Http message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Http message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Http * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Http; /** * Decodes a Http message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Http * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Http; /** * Verifies a Http message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Http message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Http */ public static fromObject(object: { [k: string]: any }): google.api.Http; /** * Creates a plain object from a Http message. Also converts values to other types if specified. * @param message Http * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Http to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a HttpRule. */ interface IHttpRule { /** HttpRule selector */ selector?: (string|null); /** HttpRule get */ get?: (string|null); /** HttpRule put */ put?: (string|null); /** HttpRule post */ post?: (string|null); /** HttpRule delete */ "delete"?: (string|null); /** HttpRule patch */ patch?: (string|null); /** HttpRule custom */ custom?: (google.api.ICustomHttpPattern|null); /** HttpRule body */ body?: (string|null); /** HttpRule response_body */ response_body?: (string|null); /** HttpRule additional_bindings */ additional_bindings?: (google.api.IHttpRule[]|null); } /** Represents a HttpRule. */ class HttpRule implements IHttpRule { /** * Constructs a new HttpRule. * @param [properties] Properties to set */ constructor(properties?: google.api.IHttpRule); /** HttpRule selector. */ public selector: string; /** HttpRule get. */ public get: string; /** HttpRule put. */ public put: string; /** HttpRule post. */ public post: string; /** HttpRule delete. */ public delete: string; /** HttpRule patch. */ public patch: string; /** HttpRule custom. */ public custom?: (google.api.ICustomHttpPattern|null); /** HttpRule body. */ public body: string; /** HttpRule response_body. */ public response_body: string; /** HttpRule additional_bindings. */ public additional_bindings: google.api.IHttpRule[]; /** HttpRule pattern. */ public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); /** * Creates a new HttpRule instance using the specified properties. * @param [properties] Properties to set * @returns HttpRule instance */ public static create(properties?: google.api.IHttpRule): google.api.HttpRule; /** * Encodes the specified HttpRule message. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. * @param message HttpRule message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified HttpRule message, length delimited. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. * @param message HttpRule message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a HttpRule message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns HttpRule * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.HttpRule; /** * Decodes a HttpRule message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns HttpRule * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.HttpRule; /** * Verifies a HttpRule message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns HttpRule */ public static fromObject(object: { [k: string]: any }): google.api.HttpRule; /** * Creates a plain object from a HttpRule message. Also converts values to other types if specified. * @param message HttpRule * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this HttpRule to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a CustomHttpPattern. */ interface ICustomHttpPattern { /** CustomHttpPattern kind */ kind?: (string|null); /** CustomHttpPattern path */ path?: (string|null); } /** Represents a CustomHttpPattern. */ class CustomHttpPattern implements ICustomHttpPattern { /** * Constructs a new CustomHttpPattern. * @param [properties] Properties to set */ constructor(properties?: google.api.ICustomHttpPattern); /** CustomHttpPattern kind. */ public kind: string; /** CustomHttpPattern path. */ public path: string; /** * Creates a new CustomHttpPattern instance using the specified properties. * @param [properties] Properties to set * @returns CustomHttpPattern instance */ public static create(properties?: google.api.ICustomHttpPattern): google.api.CustomHttpPattern; /** * Encodes the specified CustomHttpPattern message. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. * @param message CustomHttpPattern message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified CustomHttpPattern message, length delimited. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. * @param message CustomHttpPattern message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a CustomHttpPattern message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns CustomHttpPattern * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.CustomHttpPattern; /** * Decodes a CustomHttpPattern message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns CustomHttpPattern * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.CustomHttpPattern; /** * Verifies a CustomHttpPattern message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns CustomHttpPattern */ public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; /** * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. * @param message CustomHttpPattern * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this CustomHttpPattern to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } }
the_stack
import * as assert from "assert"; import { LeafTask, LeafWithDoneFileTask } from "./leafTask"; import { logVerbose } from "../../../common/logging"; import { readFileAsync, existsSync, isSameFileOrDir } from "../../../common/utils"; import path from "path"; import * as ts from "typescript"; import * as TscUtils from "../../tscUtils"; import * as fs from "fs"; const isEqual = require("lodash.isequal"); interface ITsBuildInfo { program: { fileInfos: { [key: string]: { version: string, signature: string } }, semanticDiagnosticsPerFile?: any[], options: any } } interface TscTaskMatchOptions { tsConfig?: string; }; export class TscTask extends LeafTask { private _tsBuildInfoFullPath: string | undefined; private _tsBuildInfo: ITsBuildInfo | undefined; private _tsConfig: ts.ParsedCommandLine | undefined; private _tsConfigFullPath: string | undefined; private _projectReference: TscTask | undefined; private _sourceStats: fs.Stats[] | undefined; public matchTask(command: string, options?: TscTaskMatchOptions): LeafTask | undefined { if (!options?.tsConfig) { return super.matchTask(command); } if (command !== "tsc") { return undefined; } const configFile = this.configFileFullPath; if (!configFile) { return undefined; } return isSameFileOrDir(configFile, options.tsConfig) ? this : undefined; } protected addDependentTasks(dependentTasks: LeafTask[]) { if (this.addChildTask(dependentTasks, this.node, "npm run build:genver")) { this.logVerboseDependency(this.node, "build:genver"); } const testConfig = path.join("src", "test", "tsconfig.json"); const isTestTsc = this.configFileFullPath && isSameFileOrDir(this.configFileFullPath, this.getPackageFileFullPath(testConfig)); for (const child of this.node.dependentPackages) { // TODO: Need to look at the output from tsconfig if (this.addChildTask(dependentTasks, child, "tsc")) { this.logVerboseDependency(child, "tsc"); } if (isTestTsc) { // TODO: Not all test package depends on test from dependents. // Can check if the dependent's tsconfig has declaration generated or not if (this.addChildTask(dependentTasks, child, "npm run build:test")) { this.logVerboseDependency(child, "build:test"); } } } const config = this.readTsConfig(); if (config?.projectReferences) { // TODO: make less assumptions if (config.projectReferences.length !== 1) { throw new Error(`${this.node.pkg.nameColored}: Only one project references is supported`); } if (!isSameFileOrDir(config.projectReferences[0].path, this.node.pkg.directory)) { throw new Error(`${this.node.pkg.nameColored}: Only package root project is supported for project references`); } this._projectReference = this.addChildTask(dependentTasks, this.node, "tsc") as TscTask | undefined; if (!this._projectReference) { throw new Error(`${this.node.pkg.nameColored}: tsc not found for project reference`); } this.logVerboseDependency(this.node, "tsc"); } } protected async checkLeafIsUpToDate() { const tsBuildInfoFileFullPath = this.tsBuildInfoFileFullPath; if (tsBuildInfoFileFullPath === undefined) { return false; } const tsBuildInfoFileDirectory = path.dirname(tsBuildInfoFileFullPath); // Using tsc incremental information const tsBuildInfo = await this.readTsBuildInfo(); if (tsBuildInfo === undefined) { this.logVerboseTrigger("tsBuildInfo not found"); return false; } // Check previous build errors const diag = tsBuildInfo.program.semanticDiagnosticsPerFile; if (diag?.some(item => Array.isArray(item))) { this.logVerboseTrigger("previous build error"); return false; } // Check dependencies file hashes const fileInfos = tsBuildInfo.program.fileInfos; for (const key of Object.keys(fileInfos)) { try { // Resolve relative path based on the directory of the tsBuildInfo file let fullPath = path.resolve(tsBuildInfoFileDirectory, key); // If we have project reference, see if this is in reference to one of the file, and map it to the d.ts file instead if (this._projectReference) { fullPath = this._projectReference.remapSrcDeclFile(fullPath); } const hash = await this.node.buildContext.fileHashCache.getFileHash(fullPath); if (hash !== fileInfos[key].version) { this.logVerboseTrigger(`version mismatch for ${key}, ${hash}, ${fileInfos[key].version}`); return false; } } catch (e) { this.logVerboseTrigger(`exception generating hash for ${key}`); logVerbose(e.stack); return false; } } // Check tsconfig.json return this.checkTsConfig(tsBuildInfoFileDirectory, tsBuildInfo); } private remapSrcDeclFile(fullPath: string) { if (!this._sourceStats) { const config = this.readTsConfig(); this._sourceStats = config ? config.fileNames.map(fs.lstatSync) : []; } const parsed = path.parse(fullPath); const directory = parsed.dir; const stat = fs.lstatSync(fullPath); if (this._sourceStats.some(value => isEqual(value, stat))) { return this.remapOutFile(this.readTsConfig()!, directory, `${parsed.name}.d.ts`); } return fullPath; } private checkTsConfig(tsBuildInfoFileDirectory: string, tsBuildInfo: ITsBuildInfo) { const options = this.readTsConfig(); if (!options) { return false; } const configFileFullPath = this.configFileFullPath; if (!configFileFullPath) { assert.fail(); }; // Patch relative path based on the file directory where the config comes from const configOptions = TscUtils.convertToOptionsWithAbsolutePath(options.options, path.dirname(configFileFullPath)); const tsBuildInfoOptions = TscUtils.convertToOptionsWithAbsolutePath(tsBuildInfo.program.options, tsBuildInfoFileDirectory); if (!isEqual(configOptions, tsBuildInfoOptions)) { logVerbose(`${this.node.pkg.nameColored}: ts option changed ${configFileFullPath}`); logVerbose("Config:") logVerbose(JSON.stringify(configOptions, undefined, 2)); logVerbose("BuildInfo:"); logVerbose(JSON.stringify(tsBuildInfoOptions, undefined, 2)); return false; } return true; } private readTsConfig() { if (this._tsConfig == undefined) { const parsedCommand = this.parsedCommandLine; if (!parsedCommand) { return undefined; } const configFileFullPath = this.configFileFullPath; if (!configFileFullPath) { return undefined; } const config = TscUtils.readConfigFile(configFileFullPath); if (!config) { logVerbose(`${this.node.pkg.nameColored}: ts fail to parse ${configFileFullPath}`); return undefined; } // Fix up relative path from the command line based on the package directory const commandOptions = TscUtils.convertToOptionsWithAbsolutePath(parsedCommand.options, this.node.pkg.directory); // Parse the config file relative to the config file directory const configDir = path.parse(configFileFullPath).dir; const options = ts.parseJsonConfigFileContent(config, ts.sys, configDir, commandOptions, configFileFullPath); if (options.errors.length) { logVerbose(`${this.node.pkg.nameColored}: ts fail to parse file content ${configFileFullPath}`); return undefined; } this._tsConfig = options; if (!options.options.incremental) { console.warn(`${this.node.pkg.nameColored}: warning: incremental not enabled`); } } return this._tsConfig; } protected get recheckLeafIsUpToDate() { return true; } private get configFileFullPath() { if (this._tsConfigFullPath === undefined) { const parsedCommand = this.parsedCommandLine; if (!parsedCommand) { return undefined; } this._tsConfigFullPath = TscUtils.findConfigFile(this.node.pkg.directory, parsedCommand); } return this._tsConfigFullPath; } private get parsedCommandLine() { const parsedCommand = TscUtils.parseCommandLine(this.command); if (!parsedCommand) { logVerbose(`${this.node.pkg.nameColored}: ts fail to parse command line ${this.command}`); } return parsedCommand; } private get tsBuildInfoFileName() { const configFileFullPath = this.configFileFullPath; if (!configFileFullPath) { return undefined; } const configFileParsed = path.parse(configFileFullPath); if (configFileParsed.ext === ".json") { return `${configFileParsed.name}.tsbuildinfo`; } return `${configFileParsed.name}${configFileParsed.ext}.tsbuildinfo`; } private getTsBuildInfoFileFromConfig() { const options = this.readTsConfig(); if (!options || !options.options.incremental) { return undefined; } const outFile = options.options.out ? options.options.out : options.options.outFile; if (outFile) { return `${outFile}.tsbuildinfo`; } const configFileFullPath = this.configFileFullPath; if (!configFileFullPath) { return undefined; } const tsBuildInfoFileName = this.tsBuildInfoFileName; if (!tsBuildInfoFileName) { return undefined; } return this.remapOutFile(options, path.parse(configFileFullPath).dir, tsBuildInfoFileName); } private remapOutFile(options: ts.ParsedCommandLine, directory: string, fileName: string) { if (options.options.outDir) { if (options.options.rootDir) { const relative = path.relative(options.options.rootDir, directory); return path.join(options.options.outDir, relative, fileName); } return path.join(options.options.outDir, fileName); } return path.join(directory, fileName); } private get tsBuildInfoFileFullPath() { if (this._tsBuildInfoFullPath === undefined) { const infoFile = this.getTsBuildInfoFileFromConfig(); if (infoFile) { if (path.isAbsolute(infoFile)) { this._tsBuildInfoFullPath = infoFile; } else { this._tsBuildInfoFullPath = this.getPackageFileFullPath(infoFile); } } } return this._tsBuildInfoFullPath; } protected getVsCodeErrorMessages(errorMessages: string) { const lines = errorMessages.split("\n"); for (let i = 0; i < lines.length; i++) { const line = lines[i]; if (line.length && line[0] !== ' ') { lines[i] = `${this.node.pkg.directory}/${line}`; } } return lines.join("\n"); } public async readTsBuildInfo(): Promise<ITsBuildInfo | undefined> { if (this._tsBuildInfo === undefined) { const tsBuildInfoFileFullPath = this.tsBuildInfoFileFullPath; if (tsBuildInfoFileFullPath && existsSync(tsBuildInfoFileFullPath)) { try { const tsBuildInfo = JSON.parse(await readFileAsync(tsBuildInfoFileFullPath, "utf8")); if (tsBuildInfo.program) { this._tsBuildInfo = tsBuildInfo; } else { logVerbose(`${this.node.pkg.nameColored}: Missing program property ${tsBuildInfoFileFullPath}`); } } catch { logVerbose(`${this.node.pkg.nameColored}: Unable to load ${tsBuildInfoFileFullPath}`); } } else { logVerbose(`${this.node.pkg.nameColored}: ${this.tsBuildInfoFileName} file not found`); } } return this._tsBuildInfo; } protected async markExecDone() { this._tsBuildInfo = undefined; } protected get useWorker() { // TODO: Worker doesn't implement all mode. This is not comprehensive filtering yet. const parsed = this.parsedCommandLine; return parsed !== undefined && (parsed.fileNames.length === 0 || parsed.options.project === undefined) && !parsed.watchOptions; } }; // Base class for tasks that are dependent on a tsc compile export abstract class TscDependentTask extends LeafWithDoneFileTask { protected tscTasks: TscTask[] = []; protected get recheckLeafIsUpToDate() { return true; } protected async getDoneFileContent() { try { const tsBuildInfoFiles: ITsBuildInfo[] = []; for (const tscTask of this.tscTasks) { const tsBuildInfo = await tscTask.readTsBuildInfo(); if (tsBuildInfo === undefined) { // If any of the tsc task don't have build info, we can't track return undefined; } tsBuildInfoFiles.push(tsBuildInfo); } const configFile = this.configFileFullPath; let config = ""; if (existsSync(configFile)) { // Include the config file if it exists so that we can detect changes config = await readFileAsync(this.configFileFullPath, "utf8"); } return JSON.stringify({ tsBuildInfoFiles, config }); } catch (e) { this.logVerboseTask(`error generating done file content ${e}`); return undefined; } } protected addDependentTasks(dependentTasks: LeafTask[]) { if (this.tscTasks.length === 0) { // derived class didn't populate it. this.addTscTask(dependentTasks); } } protected addTscTask(dependentTasks: LeafTask[], options?: any) { const tscTask = this.addChildTask(dependentTasks, this.node, "tsc", options); if (!tscTask) { if (options) { throw new Error(`${this.node.pkg.nameColored}: Unable to find tsc task matching ${options.tsConfig} for dependent task ${this.command}`); } else { throw new Error(`${this.node.pkg.nameColored}: Unable to find tsc task for dependent task ${this.command}`); } } this.tscTasks.push(tscTask as TscTask); this.logVerboseDependency(this.node, tscTask.command); } protected abstract get configFileFullPath(): string; };
the_stack
import { App } from "./app"; import { SendMessageFn, Log } from "mx-puppet-bridge"; import * as Discord from "better-discord.js"; import { BridgeableGuildChannel } from "./discord/DiscordUtil"; const log = new Log("DiscordPuppet:Commands"); const MAX_MSG_SIZE = 4000; export class Commands { constructor(private readonly app: App) {} public async commandSyncProfile(puppetId: number, param: string, sendMessage: SendMessageFn) { const p = this.app.puppets[puppetId]; if (!p) { await sendMessage("Puppet not found!"); return; } // only bots are allowed to profile sync, for security reasons const syncProfile = p.client.user!.bot ? param === "1" || param.toLowerCase() === "true" : false; p.data.syncProfile = syncProfile; await this.app.puppet.setPuppetData(puppetId, p.data); if (syncProfile) { await sendMessage("Syncing discord profile with matrix profile now"); await this.app.updateUserInfo(puppetId); } else { await sendMessage("Stopped syncing discord profile with matrix profile"); } } public async commandJoinEntireGuild(puppetId: number, param: string, sendMessage: SendMessageFn) { const p = this.app.puppets[puppetId]; if (!p) { await sendMessage("Puppet not found!"); return; } const guild = p.client.guilds.cache.get(param); if (!guild) { await sendMessage("Guild not found!"); return; } if (!(await this.app.store.isGuildBridged(puppetId, guild.id))) { await sendMessage("Guild not bridged!"); return; } for (const chan of guild.channels.cache.array()) { if (!this.app.discord.isBridgeableGuildChannel(chan)) { continue; } const gchan = chan as BridgeableGuildChannel; if (gchan.members.has(p.client.user!.id)) { const remoteChan = this.app.matrix.getRemoteRoom(puppetId, gchan); await this.app.puppet.bridgeRoom(remoteChan); } } await sendMessage(`Invited to all channels in guild ${guild.name}!`); } public async commandListGuilds(puppetId: number, param: string, sendMessage: SendMessageFn) { const p = this.app.puppets[puppetId]; if (!p) { await sendMessage("Puppet not found!"); return; } const guilds = await this.app.store.getBridgedGuilds(puppetId); let sendStr = "Guilds:\n"; for (const guild of p.client.guilds.cache.array()) { let sendStrPart = ` - ${guild.name} (\`${guild.id}\`)`; if (guilds.includes(guild.id)) { sendStrPart += " **bridged!**"; } sendStrPart += "\n"; if (sendStr.length + sendStrPart.length > MAX_MSG_SIZE) { await sendMessage(sendStr); sendStr = ""; } sendStr += sendStrPart; } await sendMessage(sendStr); } public async commandAcceptInvite(puppetId: number, param: string, sendMessage: SendMessageFn) { const p = this.app.puppets[puppetId]; if (!p) { await sendMessage("Puppet not found!"); return; } const matches = param.match(/^(?:https?:\/\/)?(?:discord\.gg\/|discordapp\.com\/invite\/)?([^?\/\s]+)/i); if (!matches) { await sendMessage("No invite code found!"); return; } const inviteCode = matches[1]; try { const guild = await p.client.acceptInvite(inviteCode); if (!guild) { await sendMessage("Something went wrong"); } else { await sendMessage(`Accepted invite to guild ${guild.name}!`); } } catch (err) { if (err.message) { await sendMessage(`Invalid invite code \`${inviteCode}\`: ${err.message}`); } else { await sendMessage(`Invalid invite code \`${inviteCode}\``); } log.warn(`Invalid invite code ${inviteCode}:`, err); } } public async commandBridgeGuild(puppetId: number, param: string, sendMessage: SendMessageFn) { const p = this.app.puppets[puppetId]; if (!p) { await sendMessage("Puppet not found!"); return; } const guild = p.client.guilds.cache.get(param); if (!guild) { await sendMessage("Guild not found!"); return; } await this.app.store.setBridgedGuild(puppetId, guild.id); let msg = `Guild ${guild.name} (\`${guild.id}\`) is now being bridged! Either type \`joinentireguild ${puppetId} ${guild.id}\` to get invited to all the channels of that guild `; msg += `or type \`listrooms\` and join that way. Additionally you will be invited to guild channels as messages are sent in them.`; await sendMessage(msg); } public async commandUnbridgeGuild(puppetId: number, param: string, sendMessage: SendMessageFn) { const p = this.app.puppets[puppetId]; if (!p) { await sendMessage("Puppet not found!"); return; } const bridged = await this.app.store.isGuildBridged(puppetId, param); if (!bridged) { await sendMessage("Guild wasn't bridged!"); return; } await this.app.store.removeBridgedGuild(puppetId, param); await sendMessage("Unbridged guild!"); } public async commandBridgeChannel(puppetId: number, param: string, sendMessage: SendMessageFn) { const p = this.app.puppets[puppetId]; if (!p) { await sendMessage("Puppet not found!"); return; } let channel: BridgeableGuildChannel | undefined; let guild: Discord.Guild | undefined; for (const g of p.client.guilds.cache.array()) { channel = g.channels.resolve(param) as BridgeableGuildChannel; if (this.app.discord.isBridgeableGuildChannel(channel)) { guild = g; break; } channel = undefined; } if (!channel || !guild) { await sendMessage("Channel not found!"); return; } await this.app.store.setBridgedChannel(puppetId, channel.id); await sendMessage(`Channel ${channel.name} (\`${channel.id}\`) of guild ${guild.name} is now been bridged!`); } public async commandUnbridgeChannel(puppetId: number, param: string, sendMessage: SendMessageFn) { const p = this.app.puppets[puppetId]; if (!p) { await sendMessage("Puppet not found!"); return; } const bridged = await this.app.store.isChannelBridged(puppetId, param); if (!bridged) { await sendMessage("Channel wasn't bridged!"); return; } await this.app.store.removeBridgedChannel(puppetId, param); await sendMessage("Unbridged channel!"); } public async commandBridgeAll(puppetId: number, param: string, sendMessage: SendMessageFn) { const p = this.app.puppets[puppetId]; if (!p) { await sendMessage("Puppet not found!"); return; } const bridgeAll = param === "1" || param.toLowerCase() === "true"; p.data.bridgeAll = bridgeAll; await this.app.puppet.setPuppetData(puppetId, p.data); if (bridgeAll) { await sendMessage("Bridging everything now"); } else { await sendMessage("Not bridging everything anymore"); } } public async commandEnableFriendsManagement(puppetId: number, param: string, sendMessage: SendMessageFn) { const p = this.app.puppets[puppetId]; if (!p) { await sendMessage("Puppet not found!"); return; } if (p.data.friendsManagement) { await sendMessage("Friends management is already enabled."); return; } if (param === "YES I KNOW THE RISKS") { p.data.friendsManagement = true; await this.app.puppet.setPuppetData(puppetId, p.data); await sendMessage("Friends management enabled!"); return; } await sendMessage(`Using user accounts is against discords TOS. As this is required for friends management, you ` + `will be breaking discords TOS if you enable this feature. Development of it has already softlocked accounts. ` + `USE AT YOUR OWN RISK!\n\nIf you want to enable friends management type \`enablefriendsmanagement ${puppetId} ` + `YES I KNOW THE RISKS\``); } public async commandListFriends(puppetId: number, param: string, sendMessage: SendMessageFn) { const p = this.app.puppets[puppetId]; if (!p) { await sendMessage("Puppet not found!"); return; } if (!p.data.friendsManagement) { await sendMessage(`Friends management is disabled. Please type ` + `\`enablefriendsmanagement ${puppetId}\` to enable it`); return; } let sendStr = ""; const friends = p.client.user!.relationships.friends; if (friends.size > 0) { sendStr += "Friends:\n"; for (const user of p.client.user!.relationships.friends.array()) { const mxid = await this.app.puppet.getMxidForUser({ puppetId, userId: user.id, }); const sendStrPart = ` - ${user.username} (\`${user.id}\`): [${user.username}](https://matrix.to/#/${mxid})\n`; if (sendStr.length + sendStrPart.length > MAX_MSG_SIZE) { await sendMessage(sendStr); sendStr = ""; } sendStr += sendStrPart; } } const incoming = p.client.user!.relationships.incoming; if (incoming.size > 0) { sendStr += "\nIncoming friend requests:\n"; for (const user of incoming.array()) { const sendStrPart = ` - ${user.username} (\`${user.id}\`)\n`; if (sendStr.length + sendStrPart.length > MAX_MSG_SIZE) { await sendMessage(sendStr); sendStr = ""; } sendStr += sendStrPart; } } const outgoing = p.client.user!.relationships.outgoing; if (outgoing.size > 0) { sendStr += "\nOutgoing friend requests:\n"; for (const user of outgoing.array()) { const sendStrPart = ` - ${user.username} (\`${user.id}\`)\n`; if (sendStr.length + sendStrPart.length > MAX_MSG_SIZE) { await sendMessage(sendStr); sendStr = ""; } sendStr += sendStrPart; } } await sendMessage(sendStr); } public async commandAddFriend(puppetId: number, param: string, sendMessage: SendMessageFn) { const p = this.app.puppets[puppetId]; if (!p) { await sendMessage("Puppet not found!"); return; } if (!p.data.friendsManagement) { await sendMessage(`Friends management is disabled. Please type ` + `\`enablefriendsmanagement ${puppetId}\` to enable it`); return; } try { const user = await p.client.user!.relationships.request("friend", param); if (user) { await sendMessage(`Added/sent friend request to ${typeof user === "string" ? user : user.username}!`); } else { await sendMessage("User not found"); } } catch (err) { await sendMessage("User not found"); log.warn(`Couldn't find user ${param}:`, err); } } public async commandRemoveFriend(puppetId: number, param: string, sendMessage: SendMessageFn) { const p = this.app.puppets[puppetId]; if (!p) { await sendMessage("Puppet not found!"); return; } if (!p.data.friendsManagement) { await sendMessage(`Friends management is disabled. Please type ` + `\`enablefriendsmanagement ${puppetId}\` to enable it`); return; } try { const user = await p.client.user!.relationships.remove(param); if (user) { await sendMessage(`Removed ${user.username} as friend!`); } else { await sendMessage("User not found"); } } catch (err) { await sendMessage("User not found"); log.warn(`Couldn't find user ${param}:`, err); } } }
the_stack
import { inspect } from 'util' import { toFileKey } from './utils/id-utils' import { enumerablizeWithPrototypeGetters } from './utils/object-utils' import { createLayerEntitySelector } from './utils/selector-utils' import { LayerCollectionFacade } from './layer-collection-facade' import { LayerAttributes, LayerFacade, LayerOctopusAttributesConfig, } from './layer-facade' import type { CancelToken } from '@avocode/cancel-token' import type { ArtboardId, ArtboardManifestData, ArtboardSelector, ComponentId, OctopusDocument as OctopusDocumentType, IArtboard, LayerId, LayerSelector, PageId, RgbaColor, } from '@opendesign/octopus-reader' import type { BlendingMode, Bounds, LayerBounds } from '@opendesign/rendering' import type { DesignFacade } from './design-facade' import type { FontDescriptor } from './layer-facade' import type { BitmapAssetDescriptor } from './local/local-design' import type { PageFacade } from './page-facade' // HACK: This makes TypeDoc not inline the whole type in the documentation. interface OctopusDocument extends OctopusDocumentType {} export type LayerAttributesConfig = { /** Whether to apply layer effects of the layer. Rendering of effects of nested layers is not affected. By defaults, effects of the layer are applied. */ includeEffects?: boolean /** Whether to apply clipping by a mask layer if any such mask is set for the layer (see {@link LayerFacade.isMasked}). Clipping is disabled by default. Setting this flag for layers which do not have a mask layer set has no effect on the results. */ clip?: boolean /** Whether to render the component background from the main/master component. By default, the configuration from the main/master component is used. */ includeComponentBackground?: boolean /** The blending mode to use for rendering the layer instead of its default blending mode. */ blendingMode?: BlendingMode /** The opacity to use for the layer instead of its default opacity. */ opacity?: number } export class ArtboardFacade { private _artboardEntity: IArtboard private _designFacade: DesignFacade private _layerFacades: Map<LayerId, LayerFacade> = new Map() /** @internal */ constructor( artboardEntity: IArtboard, params: { designFacade: DesignFacade } ) { this._artboardEntity = artboardEntity this._designFacade = params.designFacade enumerablizeWithPrototypeGetters(this) } /** * The ID of the artboard. * * Beware that this value may not be safely usable for naming files in the file system and the {@link fileKey} value should be instead. * * @category Identification * @returns The ID of the artboard. */ get id(): ArtboardId { return this._artboardEntity.id } /** * The key which can be used to name files in the file system. It SHOULD be unique within a design. * * IDs can include characters invalid for use in file names (such as `:`). * * @category Identification * * @example * ```typescript * // Safe: * artboard.renderToFile(`./artboards/${artboard.fileKey}.png`) * * // Unsafe: * artboard.renderToFile(`./artboards/${artboard.id}.png`) * ``` */ get fileKey(): string { return toFileKey(this.id) } /** * Returns the content of the artboard in the form of an "artboard octopus" document. * * This data includes the list of layers, the artboard position and size as well as styles used in the artboard. * * See the [Octopus Format](https://opendesign.dev/docs/octopus-format) documentation page for more info. * * This method internally triggers loading of the artboard content. In case the artboard is uncached, it is downloaded (and cached when the local cache is configured). The API has to be configured when working with an uncached artboard. * * @category Data * @param options Options * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the artboards is not uncached when newly cached). A cancellation token can be created via {@link createCancelToken}. * @returns The artboard content. * * @example * ```typescript * const artboardContent = await artboards.getContent() * ``` */ async getContent( options: { cancelToken?: CancelToken | null } = {} ): Promise<OctopusDocument> { const artboardEntity = this._artboardEntity if (!artboardEntity.isLoaded()) { await this._designFacade.loadArtboard(this.id, options) } const octopus = artboardEntity.getOctopus() if (!octopus) { throw new Error('The artboard octopus is not available') } return octopus } /** * The ID of the page in which the artboard is placed. * @category Reference */ get pageId(): PageId | null { return this._artboardEntity.pageId } /** * The ID of the component this artboard represents. * @category Reference */ get componentId(): ComponentId | null { return this._artboardEntity.componentId } /** * The name of the artboard. * @category Identification */ get name(): string | null { return this._artboardEntity.name } /** @internal */ toString(): string { const artboardInfo = this.toJSON() return `Artboard ${inspect(artboardInfo)}` } /** @internal */ [inspect.custom](): string { return this.toString() } /** @internal */ toJSON(): unknown { return { ...this, } } /** @internal */ setArtboardEntity(artboardEntity: IArtboard): void { this._artboardEntity = artboardEntity } /** @internal */ getArtboardEntity(): IArtboard { return this._artboardEntity } /** * Returns the design object associated with the artboard object. * @category Reference * @returns A design object. * * @example * ```typescript * const design = artboard.getDesign() * ``` */ getDesign(): DesignFacade { return this._designFacade } /** * Returns whether the artboard matches the provided selector. * * @category Artboard Lookup * @param selector The selector against which to test the artboard. * @returns Whether the artboard matches. * * @example * ```typescript * console.log(artboard.name) // A * artboard.matches({ name: 'A' }) // true * ``` */ matches(selector: ArtboardSelector): boolean { return this._artboardEntity.matches(selector) } /** @internal */ getManifest(): ArtboardManifestData { return this._artboardEntity.getManifest() } /** @internal */ setManifest(nextManifestData: ArtboardManifestData): void { this._artboardEntity.setManifest(nextManifestData) } /** * Returns whether the artboard content is loaded in memory from the API or a local cache. * * @category Status * @returns Whether the artboard content is loaded. * * @example * ```typescript * const design = await sdk.fetchDesignById('<DESIGN_ID>') * const artboard = design.getArtboardById('<ARTBOARD_ID>') * console.log(artboard.isLoaded()) // false * * const layerA = await artboard.findLayerById('a') * console.log(artboard.isLoaded()) // true * ``` */ isLoaded(): boolean { return this._artboardEntity.isLoaded() } /** @internal */ async load(options: { cancelToken?: CancelToken | null }): Promise<void> { if (this.isLoaded()) { return } await this._designFacade.loadArtboard(this.id, options) } /** * Releases data related to the artboard from memory. * @category Status */ async unload(): Promise<void> { await this._designFacade.unloadArtboard(this.id) } /** * Returns the page object associated with the artboard object. * * @category Reference * @returns A page object. * * @example * ```typescript * const page = artboard.getPage() * ``` */ getPage(): PageFacade | null { const pageId = this.pageId return pageId ? this._designFacade.getPageById(pageId) : null } /** @internal */ setPage(nextPageId: PageId): void { this._artboardEntity.setPage(nextPageId) } /** @internal */ unassignFromPage(): void { this._artboardEntity.unassignFromPage() } /** * Returns the dimensions of the artboard and its position within the coordinate system of the design/page. * * @category Data * @param options Options * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the artboards is not uncached when newly cached). A cancellation token can be created via {@link createCancelToken}. * @returns The artboard bounds. * * @example * ```typescript * const artboardBounds = await artboard.getBounds() * ``` */ async getBounds( options: { cancelToken?: CancelToken | null } = {} ): Promise<Bounds> { await this.load(options) const bounds = this._artboardEntity.getBounds() if (!bounds) { throw new Error('Artboard bounds are not available') } return bounds } /** * Returns a list of bitmap assets used by layers in the artboard (optionally down to a specific nesting level). * * This method internally triggers loading of the artboard content. In case the artboard is uncached, it is downloaded (and cached when the local cache is configured). The API has to be configured when working with an uncached artboard. * * @category Asset * @param options Options * @param options.depth The maximum nesting level within page and artboard layers to search for bitmap asset usage. By default, all levels are searched. `0` also means "no limit"; `1` means only root layers in the artboard should be searched. * @param options.includePrerendered Whether to also include "pre-rendered" bitmap assets. These assets can be produced by the rendering engine (if configured; future functionality) but are available as assets for either performance reasons or due to the some required data (such as font files) potentially not being available. By default, pre-rendered assets are included. * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the artboards is not uncached when newly cached). A cancellation token can be created via {@link createCancelToken}. * @returns A list of bitmap assets. * * @example * ```typescript * // All bitmap assets from the artboard * const bitmapAssetDescs = await artboard.getBitmapAssets() * * // Bitmap assets excluding pre-renredered bitmaps from the artboard * const bitmapAssetDescs = await artboard.getBitmapAssets({ * includePrerendered: false, * }) * ``` */ async getBitmapAssets( options: { depth?: number includePrerendered?: boolean cancelToken?: CancelToken | null } = {} ): Promise< Array< BitmapAssetDescriptor & { artboardLayerIds: Record<ArtboardId, Array<LayerId>> } > > { const { cancelToken = null, ...bitmapOptions } = options await this.load({ cancelToken }) return this._artboardEntity.getBitmapAssets(bitmapOptions) } /** * Returns a list of fonts used by layers the artboard (optionally down to a specific nesting level). * * This method internally triggers loading of the artboard content. In case the artboard is uncached, it is downloaded (and cached when the local cache is configured). The API has to be configured when working with an uncached artboard. * * @category Asset * @param options Options * @param options.depth The maximum nesting level within page and artboard layers to search for font usage. By default, all levels are searched. `0` also means "no limit"; `1` means only root layers in the artboard should be searched. * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the artboards is not uncached when newly cached). A cancellation token can be created via {@link createCancelToken}. * @returns A list of fonts. * * @example * ```typescript * // All fonts from the artboard * const fontDescs = await artboard.getFonts() * ``` */ async getFonts( options: { depth?: number cancelToken?: CancelToken | null } = {} ): Promise< Array< FontDescriptor & { artboardLayerIds: Record<ArtboardId, Array<LayerId>> } > > { const { cancelToken = null, ...fontOptions } = options await this.load({ cancelToken }) return this._artboardEntity.getFonts(fontOptions) } /** * Returns the background color of the artboard. * * This method internally triggers loading of the artboard content. In case the artboard is uncached, it is downloaded (and cached when the local cache is configured). The API has to be configured when working with an uncached artboard. * * @category Data * @param options Options * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the artboards is not uncached when newly cached). A cancellation token can be created via {@link createCancelToken}. * @returns The background color. * * @example * ```typescript * const color = await artboard.getBackgroundColor() * if (color) { * console.log(color) // { r: number, g: number, b: number, a: number } * } * ``` */ async getBackgroundColor( options: { cancelToken?: CancelToken | null } = {} ): Promise<RgbaColor | null> { await this.load(options) return this._artboardEntity.getBackgroundColor() } /** * Returns a collection of the first-level (root) layers objects within the artboard. * * This method internally triggers loading of the artboard content. In case the artboard is uncached, it is downloaded (and cached when the local cache is configured). The API has to be configured when working with an uncached artboard. * * @category Layer Lookup * @param options Options * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the artboards is not uncached when newly cached). A cancellation token can be created via {@link createCancelToken}. * @returns A collection of root layers. * * @example * ```typescript * const rootLayers = await artboard.getRootLayers() * ``` */ async getRootLayers( options: { cancelToken?: CancelToken | null } = {} ): Promise<LayerCollectionFacade> { await this.load(options) const layerCollection = this._artboardEntity.getRootLayers() return new LayerCollectionFacade(layerCollection, { designFacade: this._designFacade, }) } /** * Returns a collection of all layers from the artboard (optionally down to a specific nesting level). * * The produced collection can be queried further for narrowing down the search. * * This method internally triggers loading of the artboard content. In case the artboard is uncached, it is downloaded (and cached when the local cache is configured). The API has to be configured when working with an uncached artboard. * * @category Layer Lookup * @param options Options * @param options.depth The maximum nesting level of layers within the artboard to include in the collection. By default, all levels are included. `0` also means "no limit"; `1` means only root layers in the artboard should be included. * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the artboards is not uncached when newly cached). A cancellation token can be created via {@link createCancelToken}. * @returns A collection of flattened layers. * * @example All layers (from all nesting levels) * ```typescript * const allLayers = await artboard.getFlattenedLayers() * ``` * * @example Layers from the first three nesting levels (root layers + 2 levels) * ```typescript * const layers = await artboard.getFlattenedLayers({ depth: 3 }) * ``` */ async getFlattenedLayers( options: { depth?: number cancelToken?: CancelToken | null } = {} ): Promise<LayerCollectionFacade> { const { cancelToken = null, ...layerOptions } = options await this.load({ cancelToken }) const layerCollection = this._artboardEntity.getFlattenedLayers( layerOptions ) return new LayerCollectionFacade(layerCollection, { designFacade: this._designFacade, }) } /** * Returns the layer object from within the artboard which has the specified ID. * * Layer IDs are unique within individual artboards. * * This method internally triggers loading of the artboard content. In case the artboard is uncached, it is downloaded (and cached when the local cache is configured). The API has to be configured when working with an uncached artboard. * * @category Layer Lookup * @param options Options * @param layerId A layer ID. * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the artboards is not uncached when newly cached). A cancellation token can be created via {@link createCancelToken}. * @returns A layer object. * * @example Single layer * ```typescript * const layerA = await artboard.getLayerById('a') * ``` * * @example Multiple layers * ```typescript * const [ layerA, layerB, layerC ] = await Promise.all([ * artboard.getLayerById('a'), * artboard.getLayerById('b'), * artboard.getLayerById('c'), * ]) * ``` */ async getLayerById( layerId: LayerId, options: { cancelToken?: CancelToken | null } = {} ): Promise<LayerFacade | null> { await this.load(options) return this.getLayerFacadeById(layerId) } /** @internal */ getLayerFacadeById(layerId: LayerId): LayerFacade | null { const prevLayerFacade = this._layerFacades.get(layerId) if (prevLayerFacade) { return prevLayerFacade } const nextLayerFacade = this._createLayerFacade(layerId) if (nextLayerFacade) { this._layerFacades.set(layerId, nextLayerFacade) } return nextLayerFacade } /** * Returns the first layer object from the artboard (optionally down to a specific nesting level) matching the specified criteria. * * This method internally triggers loading of the artboard content. In case the artboard is uncached, it is downloaded (and cached when the local cache is configured). The API has to be configured when working with an uncached artboard. * * @category Layer Lookup * @param selector A layer selector. All specified fields must be matched by the result. * @param options Options * @param options.depth The maximum nesting level within page and artboard layers to search. By default, all levels are searched. `0` also means "no limit"; `1` means only root layers in the artboard should be searched. * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the artboards is not uncached when newly cached). A cancellation token can be created via {@link createCancelToken}. * @returns A layer object. * * @example Layer by name * ```typescript * const layer = await artboard.findLayer({ name: 'Share icon' }) * ``` * * @example Layer by function selector * ```typescript * const shareIconLayer = await design.findLayer((layer) => { * return layer.name === 'Share icon' * }) * ``` * * @example Text layer by content * ```typescript * const layer = await artboard.findLayer({ * type: 'textLayer', * text: /click to dismiss/i, * }) * ``` * * @example With timeout * ```typescript * const { cancel, token } = createCancelToken() * setTimeout(cancel, 5000) // Throw an OperationCancelled error in 5 seconds. * const layer = await artboard.findLayer( * { name: 'Share icon' }, * { cancelToken: token } * ) * ``` */ async findLayer( selector: LayerSelector | ((layer: LayerFacade) => boolean), options: { depth?: number cancelToken?: CancelToken | null } = {} ): Promise<LayerFacade | null> { const { cancelToken = null, ...layerOptions } = options await this.load({ cancelToken }) const entitySelector = createLayerEntitySelector( this._designFacade, selector ) const layerEntity = this._artboardEntity.findLayer( entitySelector, layerOptions ) return layerEntity ? this.getLayerById(layerEntity.id) : null } /** * Returns a collection of all layer objects from the artboards (optionally down to a specific nesting level) matching the specified criteria. * * This method internally triggers loading of the artboard content. In case the artboard is uncached, it is downloaded (and cached when the local cache is configured). The API has to be configured when working with an uncached artboard. * * @category Layer Lookup * @param selector A layer selector. All specified fields must be matched by the result. * @param options Options * @param options.depth The maximum nesting level within page and artboard layers to search. By default, all levels are searched. `0` also means "no limit"; `1` means only root layers in the artboard should be searched. * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the artboards is not uncached when newly cached). A cancellation token can be created via {@link createCancelToken}. * @returns A layer collection with layer matches. * * @example Layer by name * ```typescript * const layer = await artboard.findLayers({ name: 'Share icon' }) * ``` * * @example Layers by function selector * ```typescript * const shareIconLayers = await design.findLayers((layer) => { * return layer.name === 'Share icon' * }) * ``` * * @example Invisible text layers * ```typescript * const layer = await artboard.findLayers({ * type: 'textLayer', * visible: false, * }) * ``` * * @example With timeout * ```typescript * const { cancel, token } = createCancelToken() * setTimeout(cancel, 5000) // Throw an OperationCancelled error in 5 seconds. * const layer = await artboard.findLayers( * { name: 'Share icon' }, * { cancelToken: token } * ) * ``` */ async findLayers( selector: LayerSelector | ((layer: LayerFacade) => boolean), options: { depth?: number cancelToken?: CancelToken | null } = {} ): Promise<LayerCollectionFacade> { const { cancelToken = null, ...layerOptions } = options await this.load({ cancelToken }) const entitySelector = createLayerEntitySelector( this._designFacade, selector ) const layerCollection = this._artboardEntity.findLayers( entitySelector, layerOptions ) return new LayerCollectionFacade(layerCollection, { designFacade: this._designFacade, }) } /** * Returns the nesting level at which the layer of the specified ID is contained within the layer tree of the artboard. * * This method internally triggers loading of the artboard content. In case the artboard is uncached, it is downloaded (and cached when the local cache is configured). The API has to be configured when working with an uncached artboard. * * @category Layer Lookup * @param layerId A layer ID. * @param options Options * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the artboards is not uncached when newly cached). A cancellation token can be created via {@link createCancelToken}. * @returns The depth where the layer is located within the layer tree of the artboard. Root layers have the depth of 1. * * @example * ```typescript * const depth = await artboard.getLayerDepth('<ARTBOARD_ID>', '<LAYER_ID>') * ``` */ async getLayerDepth( layerId: LayerId, options: { cancelToken?: CancelToken | null } = {} ): Promise<number | null> { await this.load(options) return this._artboardEntity.getLayerDepth(layerId) } /** * Returns whether the artboard represends a (main/master) component. * @category Data * @returns Whether the artboard is a component. * * @example * ```typescript * const isComponentArtboard = artboard.isComponent() * ``` */ isComponent(): boolean { return this._artboardEntity.isComponent() } /** * Renders the artboard as an PNG image file. * * All visible layers from the artboard are included. * * Uncached items (artboard content and bitmap assets of rendered layers) are downloaded and cached. * * The rendering engine and the local cache have to be configured when using this method. * * @category Rendering * @param filePath The target location of the produced PNG image file. * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the created image file is not deleted when cancelled during actual rendering). A cancellation token can be created via {@link createCancelToken}. * @param options Options * @param options.scale The scale (zoom) factor to use for rendering instead of the default 1x factor. * * @example With default options (1x, whole artboard area) * ```typescript * await artboard.renderToFile('./rendered/artboard.png') * ``` * * @example With custom scale and crop * ```typescript * await artboard.renderToFile('./rendered/artboard.png', { * scale: 4, * // The result is going to have the dimensions of 400x200 due to the 4x scale. * bounds: { left: 100, top: 0, width: 100, height: 50 }, * }) * ``` */ async renderToFile( filePath: string, options: { scale?: number cancelToken?: CancelToken | null } = {} ): Promise<void> { await this._designFacade.renderArtboardToFile(this.id, filePath, options) } /** * Renders the specified layer from the artboard as an PNG image file. * * In case of group layers, all visible nested layers are also included. * * Uncached items (artboard content and bitmap assets of rendered layers) are downloaded and cached. * * The rendering engine and the local cache have to be configured when using this method. * * @category Rendering * @param layerId The ID of the artboard layer to render. * @param filePath The target location of the produced PNG image file. * @param options Options * @param options.blendingMode The blending mode to use for rendering the layer instead of its default blending mode. * @param options.clip Whether to apply clipping by a mask layer if any such mask is set for the layer (see {@link LayerFacade.isMasked}). Clipping is disabled by default. Setting this flag for layers which do not have a mask layer set has no effect on the results. * @param options.includeComponentBackground Whether to render the component background from the main/master component. By default, the configuration from the main/master component is used. Note that this configuration has no effect when the artboard background is not included via explicit `includeComponentBackground=true` nor the main/master component configuration as there is nothing with which to blend the layer. * @param options.includeEffects Whether to apply layer effects of the layer. Rendering of effects of nested layers is not affected. By defaults, effects of the layer are applied. * @param options.opacity The opacity to use for the layer instead of its default opacity. * @param options.bounds The area to include. This can be used to either crop or expand (add empty space to) the default layer area. * @param options.scale The scale (zoom) factor to use for rendering instead of the default 1x factor. * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the created image file is not deleted when cancelled during actual rendering). A cancellation token can be created via {@link createCancelToken}. * * @example With default options (1x, whole layer area) * ```typescript * await artboard.renderLayerToFile( * '<LAYER_ID>', * './rendered/layer.png' * ) * ``` * * @example With custom scale and crop and using the component background color * ```typescript * await artboard.renderLayerToFile( * '<LAYER_ID>', * './rendered/layer.png', * { * scale: 2, * // The result is going to have the dimensions of 400x200 due to the 2x scale. * bounds: { left: 100, top: 0, width: 100, height: 50 }, * includeComponentBackground: true, * } * ) * ``` */ async renderLayerToFile( layerId: LayerId, filePath: string, options: { includeEffects?: boolean clip?: boolean includeComponentBackground?: boolean blendingMode?: BlendingMode opacity?: number bounds?: Bounds scale?: number cancelToken?: CancelToken | null } = {} ): Promise<void> { await this._designFacade.renderArtboardLayerToFile( this.id, layerId, filePath, options ) } /** * Renders the specified layers from the artboard as a single PNG image file. * * In case of group layers, all visible nested layers are also included. * * Uncached items (artboard content and bitmap assets of rendered layers) are downloaded and cached. * * The rendering engine and the local cache have to be configured when using this method. * * @category Rendering * @param layerIds The IDs of the artboard layers to render. * @param filePath The target location of the produced PNG image file. * @param options Options * @param options.bounds The area to include. This can be used to either crop or expand (add empty space to) the default layer area. * @param options.scale The scale (zoom) factor to use for rendering instead of the default 1x factor. * @param options.layerAttributes Layer-specific options to use for the rendering instead of the default values. * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the created image file is not deleted when cancelled during actual rendering). A cancellation token can be created via {@link createCancelToken}. * * @example With default options (1x, whole combined layer area) * ```typescript * await artboard.renderLayersToFile( * ['<LAYER1>', '<LAYER2>'], * './rendered/layers.png' * ) * ``` * * @example With custom scale and crop and using the custom layer configuration * ```typescript * await artboard.renderLayersToFile( * ['<LAYER1>', '<LAYER2>'], * './rendered/layers.png', * { * scale: 2, * // The result is going to have the dimensions of 400x200 due to the 2x scale. * bounds: { left: 100, top: 0, width: 100, height: 50 }, * layerAttributes: { * '<LAYER1>': { blendingMode: 'SOFT_LIGHT', includeComponentBackground: true }, * '<LAYER2>': { opacity: 0.6 }, * } * } * ) * ``` */ async renderLayersToFile( layerIds: Array<LayerId>, filePath: string, options: { layerAttributes?: Record<string, LayerAttributesConfig> scale?: number bounds?: Bounds cancelToken?: CancelToken | null } = {} ): Promise<void> { await this._designFacade.renderArtboardLayersToFile( this.id, layerIds, filePath, options ) } /** * Returns an SVG document string of the specified layer from the artboard. * * In case of group layers, all visible nested layers are also included. * * Bitmap assets are serialized as base64 data URIs. * * Uncached items (artboard content and bitmap assets of exported layers) are downloaded and cached. * * The rendering engine and the local cache have to be configured when using this method. * * @category SVG Export * @param layerId The ID of the artboard layer to export. * @param options Export options * @param options.blendingMode The blending mode to use for the layer instead of its default blending mode. * @param options.clip Whether to apply clipping by a mask layer if any such mask is set for the layer (see {@link LayerFacade.isMasked}). Clipping is disabled by default. Setting this flag for layers which do not have a mask layer set has no effect on the results. * @param options.includeEffects Whether to apply layer effects of the layer. Effects of nested layers are not affected. By defaults, effects of the layer are applied. * @param options.opacity The opacity to use for the layer instead of its default opacity. * @param options.scale The scale (zoom) factor to use instead of the default 1x factor. * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the created image file is not deleted when cancelled during actual rendering). A cancellation token can be created via {@link createCancelToken}. * @returns An SVG document string. * * @example With default options (1x) * ```typescript * const svg = await artboard.exportLayerToSvgCode('<LAYER_ID>') * ``` * * @example With custom scale and opacity * ```typescript * const svg = await artboard.exportLayerToSvgCode('<LAYER_ID>', { scale: 2 }) * ``` */ exportLayerToSvgCode( layerId: LayerId, options: { includeEffects?: boolean clip?: boolean blendingMode?: BlendingMode opacity?: number scale?: number cancelToken?: CancelToken | null } = {} ): Promise<string> { return this._designFacade.exportArtboardLayerToSvgCode( this.id, layerId, options ) } /** * Returns an SVG document string of the specified layer from the artboard. * * In case of group layers, all visible nested layers are also included. * * Bitmap assets are serialized as base64 data URIs. * * Uncached items (artboard content and bitmap assets of exported layers) are downloaded and cached. * * The rendering engine and the local cache have to be configured when using this method. * * @category SVG Export * @param layerId The ID of the artboard layer to export. * @param filePath The target location of the produced SVG file. * @param options Export options * @param options.blendingMode The blending mode to use for the layer instead of its default blending mode. * @param options.clip Whether to apply clipping by a mask layer if any such mask is set for the layer (see {@link LayerFacade.isMasked}). Clipping is disabled by default. Setting this flag for layers which do not have a mask layer set has no effect on the results. * @param options.includeEffects Whether to apply layer effects of the layer. Effects of nested layers are not affected. By defaults, effects of the layer are applied. * @param options.opacity The opacity to use for the layer instead of its default opacity. * @param options.scale The scale (zoom) factor to use instead of the default 1x factor. * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the created image file is not deleted when cancelled during actual rendering). A cancellation token can be created via {@link createCancelToken}. * * @example With default options (1x) * ```typescript * await artboard.exportLayerToSvgFile('<LAYER_ID>', './layer.svg') * ``` * * @example With custom scale and opacity * ```typescript * await artboard.exportLayerToSvgFile( * '<LAYER_ID>', * './layer.svg', * { scale: 2 } * ) * ``` */ async exportLayerToSvgFile( layerId: LayerId, filePath: string, options: { includeEffects?: boolean clip?: boolean blendingMode?: BlendingMode opacity?: number scale?: number cancelToken?: CancelToken | null } = {} ): Promise<void> { await this._designFacade.exportArtboardLayerToSvgFile( this.id, layerId, filePath, options ) } /** * Returns an SVG document string of the specified layers from the artboard. * * In case of group layers, all visible nested layers are also included. * * Bitmap assets are serialized as base64 data URIs. * * Uncached items (artboard content and bitmap assets of exported layers) are downloaded and cached. * * The rendering engine and the local cache have to be configured when using this method. * * @category SVG Export * @param layerIds The IDs of the artboard layers to render. * @param options Export options * @param options.layerAttributes Layer-specific options to use for instead of the default values. * @param options.scale The scale (zoom) factor to use instead of the default 1x factor. * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the created image file is not deleted when cancelled during actual rendering). A cancellation token can be created via {@link createCancelToken}. * @returns An SVG document string. * * @example With default options (1x) * ```typescript * const svg = await artboard.exportLayersToSvgCode( * ['<LAYER1>', '<LAYER2>'] * ) * ``` * * @example With a custom scale * ```typescript * const svg = await artboard.exportLayersToSvgCode( * ['<LAYER1>', '<LAYER2>'], * { * scale: 2, * layerAttributes: { * '<LAYER1>': { blendingMode: 'SOFT_LIGHT' }, * '<LAYER2>': { opacity: 0.6 }, * } * } * ) * ``` */ exportLayersToSvgCode( layerIds: Array<LayerId>, options: { layerAttributes?: Record<LayerId, LayerOctopusAttributesConfig> scale?: number cancelToken?: CancelToken | null } = {} ): Promise<string> { return this._designFacade.exportArtboardLayersToSvgCode( this.id, layerIds, options ) } /** * Returns an SVG document string of the specified layers from the artboard. * * In case of group layers, all visible nested layers are also included. * * Bitmap assets are serialized as base64 data URIs. * * Uncached items (artboard content and bitmap assets of exported layers) are downloaded and cached. * * The rendering engine and the local cache have to be configured when using this method. * * @category SVG Export * @param layerIds The IDs of the artboard layers to render. * @param filePath The target location of the produced SVG file. * @param options Export options * @param options.layerAttributes Layer-specific options to use for instead of the default values. * @param options.scale The scale (zoom) factor to use instead of the default 1x factor. * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the created image file is not deleted when cancelled during actual rendering). A cancellation token can be created via {@link createCancelToken}. * * @example With default options (1x) * ```typescript * await artboard.exportLayersToSvgFile( * ['<LAYER1>', '<LAYER2>'], * './layers.svg' * ) * ``` * * @example With a custom scale * ```typescript * await artboard.exportLayersToSvgFile( * ['<LAYER1>', '<LAYER2>'], * './layers.svg', * { * scale: 2, * layerAttributes: { * '<LAYER1>': { blendingMode: 'SOFT_LIGHT' }, * '<LAYER2>': { opacity: 0.6 }, * } * } * ) * ``` */ async exportLayersToSvgFile( layerIds: Array<LayerId>, filePath: string, options: { layerAttributes?: Record<LayerId, LayerOctopusAttributesConfig> scale?: number cancelToken?: CancelToken | null } = {} ): Promise<void> { await this._designFacade.exportArtboardLayersToSvgFile( this.id, layerIds, filePath, options ) } /** * Returns various bounds of the specified layer. * * The rendering engine and the local cache have to be configured when using this method. * * @category Data * @param layerId The ID of the artboard layer to inspect. * @param options Options * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the artboards is not uncached when newly cached). A cancellation token can be created via {@link createCancelToken}. * @returns Various layer bounds. * * @example * ```typescript * const layerBounds = await artboard.getLayerBounds('<LAYER_ID>') * const boundsWithEffects = layerBounds.fullBounds * ``` */ getLayerBounds( layerId: LayerId, options: { cancelToken?: CancelToken | null } = {} ): Promise<LayerBounds> { return this._designFacade.getArtboardLayerBounds(this.id, layerId, options) } /** * Returns the attributes of the specified layer. * * @category Data * @param layerId The ID of the layer to inspect. * @param options Options * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the artboards is not uncached when newly cached). A cancellation token can be created via {@link createCancelToken}. * @returns An SVG document string. * * @example * ```typescript * const { blendingMode, opacity, visible } = await layer.getLayerAttributes('<LAYER_ID>') * ``` */ async getLayerAttributes( layerId: LayerId, options: { cancelToken?: CancelToken | null } = {} ): Promise<LayerAttributes> { return this._designFacade.getArtboardLayerAttributes( this.id, layerId, options ) } /** * Returns the top-most layer located at the specified coordinates within the specified artboard. * * The rendering engine and the local cache have to be configured when using this method. * * @category Layer Lookup * @param x The X coordinate in the coordinate system of the artboard where to look for a layer. * @param y The Y coordinate in the coordinate system of the artboard where to look for a layer. * @param options Options * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the artboards is not uncached when newly cached). A cancellation token can be created via {@link createCancelToken}. * @returns A layer object. * * @example * ```typescript * const layerId = await artboard.getLayerAtPosition(100, 200) * ``` */ getLayerAtPosition( x: number, y: number, options: { cancelToken?: CancelToken | null } = {} ): Promise<LayerFacade | null> { return this._designFacade.getArtboardLayerAtPosition(this.id, x, y, options) } /** * Returns all layers located within the specified area of the the specified artboard. * * The rendering engine and the local cache have to be configured when using this method. * * @category Layer Lookup * @param bounds The area in the corrdinate system of the artboard where to look for layers. * @param options.partialOverlap Whether to also return layers which are only partially contained within the specified area. * @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the artboards is not uncached when newly cached). A cancellation token can be created via {@link createCancelToken}. * @param options Options * @returns Array of layer objects. * * @example * ```typescript Layers fully contained in the area * const layerIds = await artboard.getLayersInArea( * { left: 80, top: 150, width: 40, height: 30 } * ) * ``` * * @example * ```typescript Layers fully or partially contained in the area * const layerIds = await artboard.getLayersInArea( * { left: 80, top: 150, width: 40, height: 30 }, * { partialOverlap: true } * ) * ``` */ getLayersInArea( bounds: Bounds, options: { partialOverlap?: boolean cancelToken?: CancelToken | null } = {} ): Promise<Array<LayerFacade>> { return this._designFacade.getArtboardLayersInArea(this.id, bounds, options) } /** @internal */ async resolveVisibleLayerSubtree( layerId: LayerId, options: { cancelToken?: CancelToken | null } ): Promise<Array<LayerId>> { const layer = await this.getLayerById(layerId, options) if (!layer) { throw new Error('No such layer') } const visibleNestedLayerIds = layer .findNestedLayers({ visible: true }) .map((nestedLayer) => nestedLayer.id) return [layer.id].concat(visibleNestedLayerIds) } private _createLayerFacade(layerId: LayerId): LayerFacade | null { const artboardEntity = this._artboardEntity const layerEntity = artboardEntity ? artboardEntity.getLayerById(layerId) : null return layerEntity ? new LayerFacade(layerEntity, { designFacade: this._designFacade }) : null } }
the_stack
import { DateEntityTableColumn, EntityActionTableColumn, EntityTableColumn, EntityTableConfig } from '@home/models/entity/entities-table-config.models'; import { DebugEventType, Event, EventType, FilterEventBody } from '@shared/models/event.models'; import { TimePageLink } from '@shared/models/page/page-link'; import { TranslateService } from '@ngx-translate/core'; import { DatePipe } from '@angular/common'; import { MatDialog } from '@angular/material/dialog'; import { EntityId } from '@shared/models/id/entity-id'; import { EventService } from '@app/core/http/event.service'; import { EventTableHeaderComponent } from '@home/components/event/event-table-header.component'; import { EntityTypeResource } from '@shared/models/entity-type.models'; import { Observable } from 'rxjs'; import { PageData } from '@shared/models/page/page-data'; import { Direction } from '@shared/models/page/sort-order'; import { DialogService } from '@core/services/dialog.service'; import { ContentType } from '@shared/models/constants'; import { EventContentDialogComponent, EventContentDialogData } from '@home/components/event/event-content-dialog.component'; import { isEqual, sortObjectKeys } from '@core/utils'; import { ConnectedPosition, Overlay, OverlayConfig, OverlayRef } from '@angular/cdk/overlay'; import { ChangeDetectorRef, Injector, StaticProvider, ViewContainerRef } from '@angular/core'; import { ComponentPortal } from '@angular/cdk/portal'; import { EVENT_FILTER_PANEL_DATA, EventFilterPanelComponent, EventFilterPanelData, FilterEntityColumn } from '@home/components/event/event-filter-panel.component'; export class EventTableConfig extends EntityTableConfig<Event, TimePageLink> { eventTypeValue: EventType | DebugEventType; private filterParams: FilterEventBody = {}; private filterColumns: FilterEntityColumn[] = []; set eventType(eventType: EventType | DebugEventType) { if (this.eventTypeValue !== eventType) { this.eventTypeValue = eventType; this.updateColumns(true); this.updateFilterColumns(); } } get eventType(): EventType | DebugEventType { return this.eventTypeValue; } eventTypes: Array<EventType | DebugEventType>; constructor(private eventService: EventService, private dialogService: DialogService, private translate: TranslateService, private datePipe: DatePipe, private dialog: MatDialog, public entityId: EntityId, public tenantId: string, private defaultEventType: EventType | DebugEventType, private disabledEventTypes: Array<EventType | DebugEventType> = null, private debugEventTypes: Array<DebugEventType> = null, private overlay: Overlay, private viewContainerRef: ViewContainerRef, private cd: ChangeDetectorRef) { super(); this.loadDataOnInit = false; this.tableTitle = ''; this.useTimePageLink = true; this.detailsPanelEnabled = false; this.selectionEnabled = false; this.searchEnabled = false; this.addEnabled = false; this.entitiesDeleteEnabled = false; this.headerComponent = EventTableHeaderComponent; this.eventTypes = Object.keys(EventType).map(type => EventType[type]); if (disabledEventTypes && disabledEventTypes.length) { this.eventTypes = this.eventTypes.filter(type => disabledEventTypes.indexOf(type) === -1); } if (debugEventTypes && debugEventTypes.length) { this.eventTypes = [...this.eventTypes, ...debugEventTypes]; } this.eventTypeValue = defaultEventType; this.entityTranslations = { noEntities: 'event.no-events-prompt' }; this.entityResources = { } as EntityTypeResource<Event>; this.entitiesFetchFunction = pageLink => this.fetchEvents(pageLink); this.defaultSortOrder = {property: 'createdTime', direction: Direction.DESC}; this.updateColumns(); this.updateFilterColumns(); this.headerActionDescriptors.push({ name: this.translate.instant('event.clear-filter'), icon: 'mdi:filter-variant-remove', isMdiIcon: true, isEnabled: () => !isEqual(this.filterParams, {}), onAction: ($event) => { this.clearFiter($event); } }, { name: this.translate.instant('event.events-filter'), icon: 'filter_list', isEnabled: () => true, onAction: ($event) => { this.editEventFilter($event); } }); } fetchEvents(pageLink: TimePageLink): Observable<PageData<Event>> { return this.eventService.getFilterEvents(this.entityId, this.eventType, this.tenantId, this.filterParams, pageLink); } updateColumns(updateTableColumns: boolean = false): void { this.columns = []; this.columns.push( new DateEntityTableColumn<Event>('createdTime', 'event.event-time', this.datePipe, '120px'), new EntityTableColumn<Event>('server', 'event.server', '100px', (entity) => entity.body.server, entity => ({}), false)); switch (this.eventType) { case EventType.ERROR: this.columns.push( new EntityTableColumn<Event>('method', 'event.method', '100%', (entity) => entity.body.method, entity => ({}), false), new EntityActionTableColumn<Event>('error', 'event.error', { name: this.translate.instant('action.view'), icon: 'more_horiz', isEnabled: (entity) => entity.body.error && entity.body.error.length > 0, onAction: ($event, entity) => this.showContent($event, entity.body.error, 'event.error') }, '100px') ); break; case EventType.LC_EVENT: this.columns.push( new EntityTableColumn<Event>('method', 'event.event', '100%', (entity) => entity.body.event, entity => ({}), false), new EntityTableColumn<Event>('status', 'event.status', '100%', (entity) => this.translate.instant(entity.body.success ? 'event.success' : 'event.failed'), entity => ({}), false), new EntityActionTableColumn<Event>('error', 'event.error', { name: this.translate.instant('action.view'), icon: 'more_horiz', isEnabled: (entity) => entity.body.error && entity.body.error.length > 0, onAction: ($event, entity) => this.showContent($event, entity.body.error, 'event.error') }, '100px') ); break; case EventType.STATS: this.columns.push( new EntityTableColumn<Event>('messagesProcessed', 'event.messages-processed', '50%', (entity) => entity.body.messagesProcessed + '', () => ({}), false, () => ({}), () => undefined, true), new EntityTableColumn<Event>('errorsOccurred', 'event.errors-occurred', '50%', (entity) => entity.body.errorsOccurred + '', () => ({}), false, () => ({}), () => undefined, true) ); break; case DebugEventType.DEBUG_RULE_NODE: case DebugEventType.DEBUG_RULE_CHAIN: this.columns[0].width = '100px'; this.columns.push( new EntityTableColumn<Event>('type', 'event.type', '40px', (entity) => entity.body.type, entity => ({ padding: '0 12px 0 0', }), false, key => ({ padding: '0 12px 0 0' })), new EntityTableColumn<Event>('entityName', 'event.entity-type', '100px', (entity) => entity.body.entityName, entity => ({ padding: '0 12px 0 0', }), false, key => ({ padding: '0 12px 0 0' })), new EntityTableColumn<Event>('msgId', 'event.message-id', '100px', (entity) => entity.body.msgId, entity => ({ whiteSpace: 'nowrap', padding: '0 12px 0 0' }), false, key => ({ padding: '0 12px 0 0' }), entity => entity.body.msgId), new EntityTableColumn<Event>('msgType', 'event.message-type', '100px', (entity) => entity.body.msgType, entity => ({ whiteSpace: 'nowrap', padding: '0 12px 0 0' }), false, key => ({ padding: '0 12px 0 0' }), entity => entity.body.msgType), new EntityTableColumn<Event>('relationType', 'event.relation-type', '100px', (entity) => entity.body.relationType, entity => ({padding: '0 12px 0 0', }), false, key => ({ padding: '0 12px 0 0' })), new EntityActionTableColumn<Event>('data', 'event.data', { name: this.translate.instant('action.view'), icon: 'more_horiz', isEnabled: (entity) => entity.body.data ? entity.body.data.length > 0 : false, onAction: ($event, entity) => this.showContent($event, entity.body.data, 'event.data', entity.body.dataType) }, '40px'), new EntityActionTableColumn<Event>('metadata', 'event.metadata', { name: this.translate.instant('action.view'), icon: 'more_horiz', isEnabled: (entity) => entity.body.metadata ? entity.body.metadata.length > 0 : false, onAction: ($event, entity) => this.showContent($event, entity.body.metadata, 'event.metadata', ContentType.JSON, true) }, '40px'), new EntityActionTableColumn<Event>('error', 'event.error', { name: this.translate.instant('action.view'), icon: 'more_horiz', isEnabled: (entity) => entity.body.error && entity.body.error.length > 0, onAction: ($event, entity) => this.showContent($event, entity.body.error, 'event.error') }, '40px') ); break; } if (updateTableColumns) { this.table.columnsUpdated(true); } } showContent($event: MouseEvent, content: string, title: string, contentType: ContentType = null, sortKeys = false): void { if ($event) { $event.stopPropagation(); } if (contentType === ContentType.JSON && sortKeys) { try { content = JSON.stringify(sortObjectKeys(JSON.parse(content))); } catch (e) {} } this.dialog.open<EventContentDialogComponent, EventContentDialogData>(EventContentDialogComponent, { disableClose: true, panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], data: { content, title, contentType } }); } private updateFilterColumns() { this.filterParams = {}; this.filterColumns = [{key: 'server', title: 'event.server'}]; switch (this.eventType) { case EventType.ERROR: this.filterColumns.push( {key: 'method', title: 'event.method'}, {key: 'errorStr', title: 'event.error'} ); break; case EventType.LC_EVENT: this.filterColumns.push( {key: 'event', title: 'event.event'}, {key: 'status', title: 'event.status'}, {key: 'errorStr', title: 'event.error'} ); break; case EventType.STATS: this.filterColumns.push( {key: 'messagesProcessed', title: 'event.min-messages-processed'}, {key: 'errorsOccurred', title: 'event.min-errors-occurred'} ); break; case DebugEventType.DEBUG_RULE_NODE: case DebugEventType.DEBUG_RULE_CHAIN: this.filterColumns.push( {key: 'msgDirectionType', title: 'event.type'}, {key: 'entityId', title: 'event.entity-id'}, {key: 'entityName', title: 'event.entity-type'}, {key: 'msgType', title: 'event.message-type'}, {key: 'relationType', title: 'event.relation-type'}, {key: 'dataSearch', title: 'event.data'}, {key: 'metadataSearch', title: 'event.metadata'}, {key: 'isError', title: 'event.error'}, {key: 'errorStr', title: 'event.error'} ); break; } } private clearFiter($event) { if ($event) { $event.stopPropagation(); } this.filterParams = {}; this.table.paginator.pageIndex = 0; this.table.updateData(); } private editEventFilter($event: MouseEvent) { if ($event) { $event.stopPropagation(); } const target = $event.target || $event.srcElement || $event.currentTarget; const config = new OverlayConfig(); config.backdropClass = 'cdk-overlay-transparent-backdrop'; config.hasBackdrop = true; const connectedPosition: ConnectedPosition = { originX: 'end', originY: 'bottom', overlayX: 'end', overlayY: 'top' }; config.positionStrategy = this.overlay.position().flexibleConnectedTo(target as HTMLElement) .withPositions([connectedPosition]); const overlayRef = this.overlay.create(config); overlayRef.backdropClick().subscribe(() => { overlayRef.dispose(); }); const providers: StaticProvider[] = [ { provide: EVENT_FILTER_PANEL_DATA, useValue: { columns: this.filterColumns, filterParams: this.filterParams } as EventFilterPanelData }, { provide: OverlayRef, useValue: overlayRef } ]; const injector = Injector.create({parent: this.viewContainerRef.injector, providers}); const componentRef = overlayRef.attach(new ComponentPortal(EventFilterPanelComponent, this.viewContainerRef, injector)); componentRef.onDestroy(() => { if (componentRef.instance.result && !isEqual(this.filterParams, componentRef.instance.result.filterParams)) { this.filterParams = componentRef.instance.result.filterParams; this.table.paginator.pageIndex = 0; this.table.updateData(); } }); this.cd.detectChanges(); } }
the_stack
import React, { useState, useEffect } from 'react' import styled from 'styled-components' import { Spring, config as springConfig } from 'react-spring/renderprops.cjs' import Link from 'next/link' import CodeHighlight from '../shared/CodeHighlight' import Lead from '../shared/Lead' import BoxCenteredOnMobile from '../shared/BoxCenteredOnMobile' import SEO from '../shared/SEO' import { theme } from '../shared/config' import { CircularInput, CircularTrack, CircularProgress, CircularThumb, useCircularInputContext, } from '../' export const Example = styled(BoxCenteredOnMobile)` padding: ${theme.space[3]}px 0; margin-top: ${theme.space[4]}px; @media screen and (min-width: ${theme.breakpoints[2]}) { padding: ${theme.space[4]}px 0; } ` const Examples = () => ( <> <SEO /> <Lead> A declarative and composable approach means we have a lot of flexibility, here are a few examples that showcase it. </Lead> <ul style={{ margin: '32px 0' }}> <li> <a href="#default">Default</a> </li> <li> <a href="#animated">Animated</a> </li> <li> <a href="#styled">Styled</a> </li> <li> <a href="#custom-component">Custom Component</a> </li> <li> <a href="#progress">Progress</a> </li> <li> <a href="#min-max-scale">Min, Max & Scale</a> </li> <li> <a href="#steps">Steps</a> </li> <li> <a href="#readonly">Readonly</a> </li> <li> <a href="#render-prop">Render Prop</a> </li> </ul> <p> Or play around with the{' '} <a href="https://codesandbox.io/s/ypwq61rnxz?hidenavigation=1&view=preview" target="_blank" rel="noopener noreferrer" > <strong>examples at CodeSandbox</strong> </a> </p> <a href="https://codesandbox.io/s/ypwq61rnxz?hidenavigation=1&view=preview" target="_blank" rel="noopener noreferrer" > <img alt="Edit react-circular-input" src="https://codesandbox.io/static/img/play-codesandbox.svg" /> </a> <h2 id="default">Default</h2> <p> An example of using the 3 components included with their default styling. </p> <Example> <DefaultExample /> </Example> <CodeHighlight code={` const [value, setValue] = useState(0.25) return ( <CircularInput value={value} onChange={setValue}> <CircularTrack /> <CircularProgress /> <CircularThumb /> </CircularInput> ) `} /> <h2 id="animated">Animated</h2> <p> You can use libraries like{' '} <a href="https://www.react-spring.io/">react-spring</a> to add animation. </p> <Example> <AnimatedExample /> </Example> <CodeHighlight code={` const [value, setValue] = useState(0.25) return ( <Spring to={{ value }}> {props => ( <CircularInput value={props.value} onChange={setValue}> <CircularTrack /> <CircularProgress /> <CircularThumb /> </CircularInput> )} </Spring> ) `} /> <h2 id="styled">Styled</h2> <p> The recommended way to style the components is to use CSS classes or CSS-in-JS as you normally do for other components 🙂 </p> <p> <code>CircularTrack</code>, <code>CircularProgress</code> and{' '} <code>CircularThumb</code> are just SVG <code>{`<circle />`}</code>{' '} so you can also just tweak most (see Component docs) attributes 💅 </p> <Example> <StyledExample /> </Example> <CodeHighlight code={` const [value, setValue] = useState(0.25) return ( <StyledCircularInput value={value} onChange={setValue}> {/* CSS-in-JS */} <StyledCircularTrack /> {/* CSS class */} <CircularProgress className="custom-progress" /> {/* SVG style prop */} <CircularThumb r={10} fill="rgba(255,255,255,0.5)" /> </StyledCircularInput> ) `} /> <h2 id="custom-component">Custom Component</h2> <p> Using the provided{' '} <strong> <Link href="/hooks"> <a>Hooks</a> </Link> </strong>{' '} you can create your own components! 🤩 </p> <Example> <CustomExample /> </Example> <CodeHighlight code={` const CustomComponent = () => { const { getPointFromValue, value } = useCircularInputContext() const { x, y } = getPointFromValue() return ( <text x={x} y={y} style={{ pointerEvents: 'none' }}> {Math.round(value * 100)} </text> ) } const CustomComponentExample = () => { const [value, setValue] = useState(0.25) return ( <CircularInput value={value} onChange={setValue}> <CircularProgress /> <CircularThumb /> {/* Add any component and use the provided hooks! */} <CustomComponent /> </CircularInput> ) } `} /> <h2 id="progress">Progress</h2> <p>Can be used to simply display progress/gauge.</p> <Example> <ProgressExample /> </Example> <CodeHighlight code={` <CircularInput value={Math.random()}> <CircularTrack strokeWidth={5} stroke="#eee" /> <CircularProgress stroke={\`hsl(\${props.value * 100}, 100%, 50%)\`} /> </CircularInput> `} /> <h2 id="min-max-scale">Min, Max & Scale</h2> <p> There are no props for min/max/etc as you can easily achieve these and much more with simple code. </p> <Example> <MinMaxScaleExample /> </Example> <CodeHighlight code={` const [value, setValue] = useState(0.25) // custom limits const min = 0.25 const max = 0.75 // get value within limits const valueWithinLimits = v => Math.min(Math.max(v, min), max) // custom range const range = [0, 100] // scaled range value const rangeValue = value * (range[1] - range[0]) + range[0] return ( <CircularInput value={valueWithinLimits(value)} onChange={v => setValue(valueWithinLimits(v))} > <CircularTrack /> <CircularProgress /> {/* limit lines */} <line x1={-10} x2={10} y1={100} y2={100} stroke="black" /> <line x1={190} x2={210} y1={100} y2={100} stroke="black" /> <CircularThumb /> {/* range value in center */} <text x={100} y={100} textAnchor="middle" dy="0.3em" fontWeight="bold"> {Math.round(rangeValue)}% </text> </CircularInput> ) `} /> <h2 id="steps">Steps</h2> <p> You&apos;re in full control of the value so it&apos;s easy to introduce the stepped interaction. </p> <Example> <SteppedExample /> </Example> <CodeHighlight code={` const [value, setValue] = useState(0.25) const stepValue = v => Math.round(v * 10) / 10 return ( <CircularInput value={stepValue(value)} onChange={v => setValue(stepValue(v))} > <CircularTrack /> <CircularProgress /> <CircularThumb /> <text x={100} y={100} textAnchor="middle" dy="0.3em" fontWeight="bold"> {Math.round(stepValue(value) * 100)}% </text> </CircularInput> ) `} /> <h2 id="readonly">Readonly</h2> <p> Omitting the <code>onChange</code> prop makes it readonly. </p> <Example> <CircularInput value={0.25}> <CircularTrack /> <CircularProgress /> </CircularInput> </Example> <CodeHighlight code={` <CircularInput value={0.25}> <CircularTrack /> <CircularProgress /> </CircularInput> `} /> <h2 id="render-prop">Render Prop</h2> <p> Use <code>children</code> prop as a function to receive the current context. </p> <Example> <RenderPropExample /> </Example> <CodeHighlight code={` const [value, setValue] = useState(0.25) return ( <CircularInput value={value} onChange={setValue}> {({ getPointFromValue }) => ( <> <CircularTrack /> <CircularProgress /> <text {...getPointFromValue()} dx="30" dy="0.3em"> wee! </text> <CircularThumb /> </> )} </CircularInput> ) `} /> <p> It might be a good time to dive deep into customisation with components and hooks: </p> <ul> <li> <Link href="/components"> <a>Components</a> </Link> </li> <li> <Link href="/hooks"> <a>Hooks</a> </Link> </li> </ul> </> ) export function DefaultExample() { const [value, setValue] = useState(0.25) return ( <CircularInput value={value} onChange={setValue}> <CircularTrack /> <CircularProgress /> <CircularThumb /> </CircularInput> ) } function ProgressExample() { const [value, setValue] = useState(0.25) useEffect(() => { const i = setInterval(() => { setValue(Math.random()) }, 1000) return () => clearInterval(i) }, []) return ( <Spring to={{ value }} config={springConfig.slow}> {(props) => ( <CircularInput value={props.value}> <CircularTrack strokeWidth={5} stroke="#eee" /> <CircularProgress stroke={`hsl(${props.value * 100}, 100%, 50%)`} /> </CircularInput> )} </Spring> ) } const StyledCircularInput = styled(CircularInput)` .custom-progress { stroke: #b1108e; stroke-width: 40px; } ` const StyledCircularTrack = styled(CircularTrack)` stroke: #f6f6f6; stroke-width: 10px; ` function StyledExample() { const [value, setValue] = useState(0.25) return ( <StyledCircularInput value={value} onChange={setValue}> <StyledCircularTrack /> <CircularProgress className="custom-progress" /> <CircularThumb r={10} fill="rgba(255,255,255,0.5)" /> </StyledCircularInput> ) } function AnimatedExample() { const [value, setValue] = useState(0.25) return ( <Spring to={{ value }} config={springConfig.stiff}> {(props) => ( <CircularInput value={props.value} onChange={setValue}> <CircularTrack /> <CircularProgress /> <CircularThumb /> </CircularInput> )} </Spring> ) } function CustomComponent() { const { getPointFromValue, value } = useCircularInputContext() const { x, y } = getPointFromValue() return ( <text x={x} y={y} textAnchor="middle" dy="0.35em" fill="rgb(61, 153, 255)" style={{ pointerEvents: 'none', fontWeight: 'bold' }} > {Math.round(value * 100)} </text> ) } function CustomExample() { const [value, setValue] = useState(0.25) return ( <Spring to={{ value }} config={springConfig.stiff}> {(props) => ( <CircularInput value={props.value} onChange={setValue}> <CircularProgress strokeWidth={45} stroke={`rgba(61, 153, 255, ${props.value})`} /> <CircularThumb fill="white" stroke="rgb(61, 153, 255)" strokeWidth="5" /> <CustomComponent /> </CircularInput> )} </Spring> ) } function RenderPropExample() { const [value, setValue] = useState(0.25) return ( <CircularInput value={value} onChange={setValue}> {({ getPointFromValue }) => ( <> <CircularTrack /> <CircularProgress /> <text {...getPointFromValue()} dx="30" dy="0.3em"> wee! </text> <CircularThumb /> </> )} </CircularInput> ) } function MinMaxScaleExample() { const [value, setValue] = useState(0.25) // custom limits const min = 0.25 const max = 0.75 // get value within limits const valueWithinLimits = (v) => Math.min(Math.max(v, min), max) // custom range const range = [0, 100] // scaled range value const rangeValue = value * (range[1] - range[0]) + range[0] return ( <CircularInput // make sure value is always within limits value={valueWithinLimits(value)} // make sure we set value within limits onChange={(v) => setValue(valueWithinLimits(v))} > <CircularTrack /> <CircularProgress /> {/* limit lines */} <line x1={-10} x2={10} y1={100} y2={100} stroke="black" /> <line x1={190} x2={210} y1={100} y2={100} stroke="black" /> <CircularThumb /> {/* range value in center */} <text x={100} y={100} textAnchor="middle" dy="0.3em" fontWeight="bold" > {Math.round(rangeValue)}% </text> </CircularInput> ) } function SteppedExample() { const [value, setValue] = useState(0.25) const stepValue = (v) => Math.round(v * 10) / 10 return ( <CircularInput value={stepValue(value)} onChange={(v) => setValue(stepValue(v))} > <CircularTrack /> <CircularProgress /> <CircularThumb /> <text x={100} y={100} textAnchor="middle" dy="0.3em" fontWeight="bold" > {Math.round(stepValue(value) * 100)}% </text> </CircularInput> ) } export default Examples
the_stack
import { Get, Post, Put, Delete, Param, Body, CurrentUser, Authorized, JsonController, UploadedFile, UseBefore, BadRequestError, ForbiddenError, NotFoundError} from 'routing-controllers'; import passportJwtMiddleware from '../security/passportJwtMiddleware'; import {errorCodes} from '../config/errorCodes'; import config from '../config/main'; import {ICourse} from '../../../shared/models/ICourse'; import {ICourseDashboard} from '../../../shared/models/ICourseDashboard'; import {ICourseView} from '../../../shared/models/ICourseView'; import {IUser} from '../../../shared/models/IUser'; import {Course, ICourseModel} from '../models/Course'; import {WhitelistUser} from '../models/WhitelistUser'; import emailService from '../services/EmailService'; const multer = require('multer'); import {API_NOTIFICATION_TYPE_ALL_CHANGES, NotificationSettings} from '../models/NotificationSettings'; import {IWhitelistUser} from '../../../shared/models/IWhitelistUser'; import {DocumentToObjectOptions} from 'mongoose'; import * as fs from 'fs'; import * as path from 'path'; import ResponsiveImageService from '../services/ResponsiveImageService'; import {IResponsiveImageData} from '../../../shared/models/IResponsiveImageData'; import {Picture} from '../models/mediaManager/File'; const coursePictureUploadOptions = { storage: multer.diskStorage({ destination: (req: any, file: any, cb: any) => { cb(null, path.join(config.uploadFolder, 'courses')); }, filename: (req: any, file: any, cb: any) => { const id = req.params.id; const extPos = file.originalname.lastIndexOf('.'); const ext = (extPos !== -1) ? `.${file.originalname.substr(extPos + 1).toLowerCase()}` : ''; cb(null, id + '_' + new Date().getTime().toString() + ext); } }), }; @JsonController('/courses') @UseBefore(passportJwtMiddleware) export class CourseController { /** * @api {get} /api/courses/ Request courses of current user * @apiName GetCourses * @apiGroup Course * * @apiParam {IUser} currentUser Currently logged in user. * * @apiSuccess {ICourseDashboard[]} courses List of ICourseDashboard objects. * * @apiSuccessExample {json} Success-Response: * [ * { * "_id": "5ad0f9b56ff514268c5adc8c", * "name": "Inactive Test", * "active": false, * "description": "An inactive course.", * "enrollType": "free", * "userCanEditCourse": true, * "userCanViewCourse": true, * "userIsCourseAdmin": true, * "userIsCourseTeacher": false, * "userIsCourseMember": true * }, * { * "_id": "5ad0f9b56ff514268c5adc8d", * "name": "Access key test", * "active": true, * "description": "This course is used to test the access key course enroll type.", * "enrollType": "accesskey", * "userCanEditCourse": true, * "userCanViewCourse": true, * "userIsCourseAdmin": false, * "userIsCourseTeacher": true, * "userIsCourseMember": true * }, * { * "_id": "5ad0f9b56ff514268c5adc8e", * "name": "Advanced web development", * "active": true, * "description": "Learn all the things! Angular, Node, Express, MongoDB, TypeScript ...", * "enrollType": "free", * "userCanEditCourse": false, * "userCanViewCourse": false, * "userIsCourseAdmin": false, * "userIsCourseTeacher": false, * "userIsCourseMember": false * } * ] */ @Get('/') async getCourses(@CurrentUser() currentUser: IUser): Promise<ICourseDashboard[]> { const whitelistUsers = await WhitelistUser.find({uid: currentUser.uid}); const conditions = this.userReadConditions(currentUser); if (conditions.$or) { // Everyone is allowed to see free courses in overview conditions.$or.push({enrollType: 'free'}); conditions.$or.push({enrollType: 'accesskey'}); conditions.$or.push({enrollType: 'whitelist', whitelist: {$elemMatch: {$in: whitelistUsers}}}); } const courses = await Course.find(conditions); return await Promise.all(courses.map(async (course) => { return course.forDashboard(currentUser); })); } /** * @api {get} /api/courses/:id Request view information for a specific course * @apiName GetCourseView * @apiGroup Course * * @apiParam {String} id Course ID. * @apiParam {IUser} currentUser Currently logged in user. * * @apiSuccess {ICourseView} course ICourseView object. * * @apiSuccessExample {json} Success-Response: * { * "_id": "5ad0f9b56ff514268c5adc8d", * "name": "Access key test", * "description": "This course is used to test the access key course enroll type.", * "lectures": [ * { * "units": [ * { * "__t": "free-text", * "_id": "5ad0f9b56ff514268c5adc99", * "updatedAt": "2018-04-13T18:40:53.305Z", * "createdAt": "2018-04-13T18:40:53.305Z", * "name": "What is the purpose of this course fixture?", * "description": "", * "markdown": "To test the 'accesskey' enrollType.", * "_course": "5ad0f9b56ff514268c5adc8d", * "__v": 0 * } * ], * "_id": "5ad0f9b56ff514268c5adc92", * "updatedAt": "2018-04-13T18:40:53.316Z", * "createdAt": "2018-04-13T18:40:53.284Z", * "name": "Documentation", * "description": "Documents the course fixture.", * "__v": 1 * } * ] * } * * @apiError NotFoundError Includes implicit authorization check. (In getCourse helper method.) * @apiError ForbiddenError (Redundant) Authorization check. */ @Get('/:id([a-fA-F0-9]{24})') async getCourseView(@Param('id') id: string, @CurrentUser() currentUser: IUser): Promise<ICourseView> { const course = await this.getCourse(id, currentUser); // This is currently a redundant check, because userReadConditions in getCourse above already restricts access! // (I.e. just in case future changes break something.) if (!course.checkPrivileges(currentUser).userCanViewCourse) { throw new ForbiddenError(); } await course.populateLecturesFor(currentUser) .populate('courseAdmin') .populate('teachers') .execPopulate(); await course.processLecturesFor(currentUser); return course.forView(currentUser); } /** * @api {get} /api/courses/:id/edit Request edit information for a specific course * @apiName GetCourseEdit * @apiGroup Course * @apiPermission teacher * @apiPermission admin * * @apiParam {String} id Course ID. * @apiParam {IUser} currentUser Currently logged in user. * * @apiSuccess {ICourse} course ICourse object. * * @apiSuccessExample {json} Success-Response: * { * "teachers": [ * { * "profile": { * "lastName": "Teachman", * "firstName": "Daniel" * }, * "role": "teacher", * "lastVisitedCourses": [ * "5ad0f9b56ff514268c5adc8d", * "5ad0f9b56ff514268c5adc8b", * "5ad0f9b56ff514268c5adc8c", * "5ad2c3ba94e45c0c8493da06", * "5ad7a43f943190432c5af597", * "5ad0f9b56ff514268c5adc90" * ], * "isActive": true, * "_id": "5ad0f9b56ff514268c5adc7e", * "updatedAt": "2018-04-21T23:52:03.424Z", * "createdAt": "2018-04-13T18:40:53.189Z", * "email": "teacher1@test.local", * "__v": 0, * "id": "5ad0f9b56ff514268c5adc7e" * } * ], * "students": [ * { * "profile": { * "firstName": "Fabienne", * "lastName": "Wiedenroth" * }, * "role": "student", * "lastVisitedCourses": [], * "isActive": true, * "_id": "5ad0f9b56ff514268c5adc64", * "updatedAt": "2018-04-13T18:40:53.108Z", * "createdAt": "2018-04-13T18:40:53.108Z", * "uid": "469952", * "email": "student5@test.local", * "__v": 0, * "id": "5ad0f9b56ff514268c5adc64" * }, * { * "profile": { * "firstName": "Clemens", * "lastName": "TillmannsEdit", * "theme": "night" * }, * "role": "student", * "lastVisitedCourses": [ * "5ad0f9b56ff514268c5adc8b", * "5ad0f9b56ff514268c5adc8d", * "5ad0f9b56ff514268c5adc8e" * ], * "isActive": true, * "_id": "5ad0f9b56ff514268c5adc76", * "updatedAt": "2018-04-13T22:22:17.046Z", * "createdAt": "2018-04-13T18:40:53.163Z", * "uid": "970531", * "email": "edit@test.local", * "__v": 0, * "id": "5ad0f9b56ff514268c5adc76" * } * ], * "lectures": [ * { * "units": [ * { * "__t": "free-text", * "_id": "5ad0f9b56ff514268c5adc99", * "updatedAt": "2018-04-13T18:40:53.305Z", * "createdAt": "2018-04-13T18:40:53.305Z", * "name": "What is course fixture for?", * "description": "", * "markdown": "To test the 'accesskey' enrollType.", * "_course": "5ad0f9b56ff514268c5adc8d", * "__v": 0 * } * ], * "_id": "5ad0f9b56ff514268c5adc92", * "updatedAt": "2018-04-13T18:40:53.316Z", * "createdAt": "2018-04-13T18:40:53.284Z", * "name": "Documentation", * "description": "Documents the course fixture.", * "__v": 1 * } * ], * "enrollType": "accesskey", * "whitelist": [], * "_id": "5ad0f9b56ff514268c5adc8d", * "updatedAt": "2018-04-21T02:45:15.877Z", * "createdAt": "2018-04-13T18:40:53.279Z", * "name": "Access key test", * "description": "This course is used to test the access key course enroll type.", * "active": true, * "accessKey": "accessKey1234", * "courseAdmin": { * "profile": { * "firstName": "Ober", * "lastName": "Lehrer" * }, * "role": "teacher", * "lastVisitedCourses": [], * "isActive": true, * "_id": "5ad0f9b56ff514268c5adc7f", * "updatedAt": "2018-04-13T18:40:53.192Z", * "createdAt": "2018-04-13T18:40:53.192Z", * "email": "teacher2@test.local", * "__v": 0, * "id": "5ad0f9b56ff514268c5adc7f" * }, * "__v": 6, * "media": { * "subDirectories": [], * "files": [], * "_id": "5ad2569171d8982ad0761451", * "updatedAt": "2018-04-14T19:29:21.296Z", * "createdAt": "2018-04-14T19:29:21.296Z", * "name": "Access key test", * "__v": 0 * }, * "hasAccessKey": true * } * * @apiError NotFoundError Includes implicit authorization check. (In getCourse helper method.) * @apiError ForbiddenError (Redundant) Authorization check. */ @Authorized(['teacher', 'admin']) @Get('/:id([a-fA-F0-9]{24})/edit') async getCourseEdit(@Param('id') id: string, @CurrentUser() currentUser: IUser): Promise<ICourse> { const course = await this.getCourse(id, currentUser); // This is currently a redundant check, because userReadConditions in getCourse and @Authorized already restrict access! // (I.e. just in case future changes break something.) if (!course.checkPrivileges(currentUser).userCanEditCourse) { throw new ForbiddenError(); } await course.populateLecturesFor(currentUser) .populate('media') .populate('courseAdmin') .populate('teachers') .populate('students') .populate('whitelist') .populate('image') .execPopulate(); await course.processLecturesFor(currentUser); return course.toObject(<DocumentToObjectOptions>{currentUser}); } private userReadConditions(currentUser: IUser) { const conditions: any = {}; if (currentUser.role === 'admin') { return conditions; } conditions.$or = []; if (currentUser.role === 'student') { conditions.active = true; conditions.$or.push({students: currentUser._id}); } else { conditions.$or.push({teachers: currentUser._id}); conditions.$or.push({courseAdmin: currentUser._id}); } return conditions; } private async getCourse(id: string, currentUser: IUser) { const course = await Course.findOne({ ...this.userReadConditions(currentUser), _id: id }); if (!course) { throw new NotFoundError(); } return course; } /** * @api {post} /api/courses/ Add course * @apiName PostCourse * @apiGroup Course * @apiPermission teacher * @apiPermission admin * * @apiParam {ICourse} course New course data. * @apiParam {IUser} currentUser Currently logged in user. * * @apiSuccess {Course} course Added course. * * @apiSuccessExample {json} Success-Response: * { * "_id": "5a037e6b60f72236d8e7c83d", * "updatedAt": "2017-11-08T22:00:11.869Z", * "createdAt": "2017-11-08T22:00:11.263Z", * "name": "Introduction to web development", * "description": "Whether you're just getting started with Web development or are just expanding your horizons...", * "courseAdmin": { * "_id": "5a037e6a60f72236d8e7c815", * "updatedAt": "2017-11-08T22:00:10.898Z", * "createdAt": "2017-11-08T22:00:10.898Z", * "email": "teacher2@test.local", * "isActive": true, * "role": "teacher", * "profile": { * "firstName": "Ober", * "lastName": "Lehrer" * }, * "id": "5a037e6a60f72236d8e7c815" * }, * "active": true, * "__v": 1, * "whitelist": [], * "enrollType": "free", * "lectures": [], * "students": [], * "teachers": [], * "id": "5a037e6b60f72236d8e7c83d", * "hasAccessKey": false * } * * @apiError BadRequestError Course name already in use. */ @Authorized(['teacher', 'admin']) @Post('/') async addCourse(@Body() course: ICourse, @CurrentUser() currentUser: IUser) { // Note that this might technically have a race condition, but it should never matter because the new course ids remain unique. // If a strict version is deemed important, see mongoose Model.findOneAndUpdate for a potential approach. const existingCourse = await Course.findOne({name: course.name}); if (existingCourse) { throw new BadRequestError(errorCodes.course.duplicateName.code); } course.courseAdmin = currentUser; const newCourse = new Course(course); await newCourse.save(); return newCourse.toObject(); } /** * @api {post} /api/courses/mail Send mail to selected users * @apiName PostCourseMail * @apiGroup Course * @apiPermission teacher * @apiPermission admin * * @apiParam {Object} mailData Mail data. * @apiParam {IUser} currentUser Currently logged in user. * * @apiSuccess {Object} freeFormMail Information about sent email. * * @apiSuccessExample {json} Success-Response: * { * "accepted": ["geli.hda@gmail.com"], * "rejected": [], * "envelopeTime": 5, * "messageTime": 4, * "messageSize": 874, * "response": "250 ok: Message 11936348 accepted", * "envelope": { * "from": "staging.geli.fbi@h-da.de", * "to": ["geli.hda@gmail.com"] * }, * "messageId": "<f70858d7-d9f4-3f5b-a833-d94d2a440b33@h-da.de>" * } */ @Authorized(['teacher', 'admin']) @Post('/mail') sendMailToSelectedUsers(@Body() mailData: any, @CurrentUser() currentUser: IUser) { return emailService.sendFreeFormMail({ ...mailData, replyTo: `${currentUser.profile.firstName} ${currentUser.profile.lastName}<${currentUser.email}>`, }); } /** * @api {post} /api/courses/:id/enroll Enroll current student in course * @apiName PostCourseEnroll * @apiGroup Course * @apiPermission student * * @apiParam {String} id Course ID. * @apiParam {Object} data Data (with access key). * @apiParam {IUser} currentUser Currently logged in user. * * @apiSuccess {Object} result Empty object. * * @apiSuccessExample {json} Success-Response: * {} * * @apiError NotFoundError * @apiError ForbiddenError Not allowed to join, you are not on whitelist. * @apiError ForbiddenError Incorrect or missing access key. */ @Authorized(['student']) @Post('/:id/enroll') async enrollStudent(@Param('id') id: string, @Body() data: any, @CurrentUser() currentUser: IUser) { const course = await Course.findById(id); if (!course) { throw new NotFoundError(); } if (course.enrollType === 'whitelist') { const wUsers: IWhitelistUser[] = await WhitelistUser.find().where({courseId: course._id}); if (wUsers.filter(e => e.uid === currentUser.uid).length < 1) { throw new ForbiddenError(errorCodes.course.notOnWhitelist.code); } } else if (course.accessKey && course.accessKey !== data.accessKey) { throw new ForbiddenError(errorCodes.course.accessKey.code); } if (course.students.indexOf(currentUser._id) < 0) { course.students.push(currentUser); await new NotificationSettings({ 'user': currentUser, 'course': course, 'notificationType': API_NOTIFICATION_TYPE_ALL_CHANGES, 'emailNotification': false }).save(); await course.save(); } return {}; } /** * @api {post} /api/courses/:id/leave Sign out current student from course * @apiName PostCourseLeave * @apiGroup Course * @apiPermission student * * @apiParam {String} id Course ID. * @apiParam {IUser} currentUser Currently logged in user. * * @apiSuccess {Object} result Empty object. * * @apiSuccessExample {json} Success-Response: * {} * * @apiError NotFoundError * @apiError ForbiddenError */ @Authorized(['student']) @Post('/:id/leave') async leaveStudent(@Param('id') id: string, @CurrentUser() currentUser: IUser) { const course = await Course.findById(id); if (!course) { throw new NotFoundError(); } const index: number = course.students.indexOf(currentUser._id); if (index >= 0) { course.students.splice(index, 1); await NotificationSettings.findOne({'user': currentUser, 'course': course}).remove(); await course.save(); return {}; } else { // This equals an implicit !course.checkPrivileges(currentUser).userIsCourseStudent check. throw new ForbiddenError(); } } /** * @api {post} /api/courses/:id/whitelist Whitelist students for course * @apiName PostCourseWhitelist * @apiGroup Course * @apiPermission teacher * @apiPermission admin * * @apiParam {String} id Course ID. * @apiParam {Object} file Uploaded file. * * @apiSuccess {Object} result Returns the new whitelist length. * * @apiSuccessExample {json} Success-Response: * { * newlength: 10 * } * * @apiError HttpError UID is not a number 1. * @apiError ForbiddenError Unauthorized user. */ @Authorized(['teacher', 'admin']) @Post('/:id/whitelist') async whitelistStudents( @Param('id') id: string, @Body() whitelist: any[], @CurrentUser() currentUser: IUser) { const course = await Course.findById(id); if (!course.checkPrivileges(currentUser).userCanEditCourse) { throw new ForbiddenError(); } if (!whitelist || whitelist.length === 0) { throw new BadRequestError(); } if (course.whitelist.length > 0) { for (const wuser of course.whitelist) { const whitelistUser = await WhitelistUser.findById(wuser); if (whitelistUser) { await whitelistUser.remove(); } } } course.whitelist = []; for (const whiteListUser of whitelist) { const wUser = new WhitelistUser(); wUser.firstName = whiteListUser.firstName; wUser.lastName = whiteListUser.lastName; wUser.uid = whiteListUser.uid; wUser.courseId = course._id; await wUser.save(); course.whitelist.push(wUser._id); } await course.save(); return whitelist; } /** * @api {put} /api/courses/:id Update course * @apiName PutCourse * @apiGroup Course * @apiPermission teacher * @apiPermission admin * * @apiParam {String} id Course ID. * @apiParam {ICourse} course New course data. * @apiParam {IUser} currentUser Currently logged in user. * * @apiSuccess {Object} result ID and name of the course. * * @apiSuccessExample {json} Success-Response: * { * _id: "5a037e6b60f72236d8e7c83d", * name: "Introduction to web development" * } * * @apiError NotFoundError Can't find the course. (Includes implicit authorization check.) */ @Authorized(['teacher', 'admin']) @Put('/:id') async updateCourse(@Param('id') id: string, @Body() course: ICourse, @CurrentUser() currentUser: IUser) { const conditions: any = {_id: id}; if (currentUser.role !== 'admin') { conditions.$or = [ {teachers: currentUser._id}, {courseAdmin: currentUser._id} ]; } const updatedCourse = await Course.findOneAndUpdate(conditions, course, {'new': true}); if (updatedCourse) { return {_id: updatedCourse.id, name: updatedCourse.name}; } else { throw new NotFoundError(); } } /** * @api {delete} /api/courses/:id Delete course * @apiName DeleteCourse * @apiGroup Course * * @apiParam {String} id Course ID. * @apiParam {IUser} currentUser Currently logged in user. * * @apiSuccess {Object} result Empty object. * * @apiSuccessExample {json} Success-Response: * {} * * @apiError NotFoundError * @apiError ForbiddenError */ @Authorized(['teacher', 'admin']) @Delete('/:id') async deleteCourse(@Param('id') id: string, @CurrentUser() currentUser: IUser) { const course = await Course.findById(id); if (!course) { throw new NotFoundError(); } if (!course.checkPrivileges(currentUser).userCanEditCourse) { throw new ForbiddenError(); } await course.remove(); return {}; } /** * @api {delete} /api/courses/picture/:id Delete course picture * @apiName DeleteCoursePicture * @apiGroup Course * * @apiParam {String} id Course ID. * @apiParam {IUser} currentUser Currently logged in user. * * @apiSuccess {Object} Empty object. * * @apiSuccessExample {json} Success-Response: * {} * * @apiError NotFoundError * @apiError ForbiddenError */ @Authorized(['teacher', 'admin']) @Delete('/picture/:id') async deleteCoursePicture( @Param('id') id: string, @CurrentUser() currentUser: IUser) { const course = await Course.findById(id).orFail(new NotFoundError()); if (!course.checkPrivileges(currentUser).userCanEditCourse) { throw new ForbiddenError(); } if (!course.image) { throw new NotFoundError(); } const picture = await Picture.findById(course.image); if (picture) { picture.remove(); } await Course.updateOne({_id: id}, {$unset: {image: 1}}); return {}; } /** * @api {post} /api/courses/picture/:id Add course picture * @apiName AddCoursePicture * @apiGroup Course * * @apiParam {String} id Course ID. * @apiParam responsiveImageDataRaw Image as data object. * @apiParam {IUser} currentUser Currently logged in user. * * @apiSuccess {Object} Empty object. * * @apiSuccessExample {json} Success-Response: * { * "breakpoints":[ * { * "screenSize":0, * "imageSize":{ * "width":284, * "height":190 * }, * "pathToImage":"uploads/courses/5c0fa2770315e73d6c7babfe_1544542544919_0.jpg", * "pathToRetinaImage":"uploads/courses/5c0fa2770315e73d6c7babfe_1544542544919_0@2x.jpg" * } * ], * "_id":"5c0fd95871707a3a888ae70a", * "__t":"Picture", * "name":"5c0fa2770315e73d6c7babfe_1544542544919.jpg", * "link":"-", * "size":0, * "mimeType":"image/jpeg", * "createdAt":"2018-12-11T15:35:52.423Z", * "updatedAt":"2018-12-11T15:35:52.423Z", * "__v":0 * } * * @apiError NotFoundError * @apiError ForbiddenError */ @Authorized(['teacher', 'admin']) @Post('/picture/:id') async addCoursePicture( @UploadedFile('file', {options: coursePictureUploadOptions}) file: any, @Param('id') id: string, @Body() responsiveImageDataRaw: any, @CurrentUser() currentUser: IUser) { // Remove the old picture if the course already has one. const course = await Course.findById(id).orFail(new NotFoundError()); if (!course.checkPrivileges(currentUser).userCanEditCourse) { throw new ForbiddenError(); } const mimeFamily = file.mimetype.split('/', 1)[0]; if (mimeFamily !== 'image') { // Remove the file if the type was not correct. await fs.unlinkSync(file.path); throw new BadRequestError('Forbidden format of uploaded picture: ' + mimeFamily); } const picture = await Picture.findById(course.image); if (picture) { picture.remove(); } const responsiveImageData = <IResponsiveImageData>JSON.parse(responsiveImageDataRaw.imageData); await ResponsiveImageService.generateResponsiveImages(file, responsiveImageData); const image: any = new Picture({ name: file.filename, physicalPath: responsiveImageData.pathToImage, link: responsiveImageData.pathToImage, size: 0, mimeType: file.mimetype, breakpoints: responsiveImageData.breakpoints }); await image.save(); course.image = image; await course.save(); return image.toObject(); } }
the_stack
import { timestamp, log, warn } from "../utils.js"; import { Timestamp, PageClose } from "../../messages/index.js"; import Message from "../../messages/message.js"; import Nodes from "./nodes.js"; import Observer from "./observer.js"; import Ticker from "./ticker.js"; import { deviceMemory, jsHeapSizeLimit } from "../modules/performance.js"; import type { Options as ObserverOptions } from "./observer.js"; import type { Options as WebworkerOptions, WorkerMessageData } from "../../messages/webworker.js"; export interface OnStartInfo { sessionID: string, sessionToken: string, userUUID: string, } export type Options = { revID: string; node_id: string; session_token_key: string; session_pageno_key: string; local_uuid_key: string; ingestPoint: string; resourceBaseHref: string | null, // resourceHref? //resourceURLRewriter: (url: string) => string | boolean, __is_snippet: boolean; __debug_report_edp: string | null; __debug_log: boolean; onStart?: (info: OnStartInfo) => void; } & ObserverOptions & WebworkerOptions; type Callback = () => void; type CommitCallback = (messages: Array<Message>) => void; // TODO: use backendHost only export const DEFAULT_INGEST_POINT = 'https://api.openreplay.com/ingest'; export default class App { readonly nodes: Nodes; readonly ticker: Ticker; readonly projectKey: string; private readonly messages: Array<Message> = []; /*private*/ readonly observer: Observer; // temp, for fast security fix. TODO: separate security/obscure module with nodeCallback that incapsulates `textMasked` functionality from Observer private readonly startCallbacks: Array<Callback> = []; private readonly stopCallbacks: Array<Callback> = []; private readonly commitCallbacks: Array<CommitCallback> = []; private readonly options: Options; private readonly revID: string; private _sessionID: string | null = null; private isActive = false; private version = 'TRACKER_VERSION'; private readonly worker?: Worker; constructor( projectKey: string, sessionToken: string | null | undefined, opts: Partial<Options>, ) { this.projectKey = projectKey; this.options = Object.assign( { revID: '', node_id: '__openreplay_id', session_token_key: '__openreplay_token', session_pageno_key: '__openreplay_pageno', local_uuid_key: '__openreplay_uuid', ingestPoint: DEFAULT_INGEST_POINT, resourceBaseHref: null, __is_snippet: false, __debug_report_edp: null, __debug_log: false, obscureTextEmails: true, obscureTextNumbers: false, captureIFrames: false, }, opts, ); if (sessionToken != null) { sessionStorage.setItem(this.options.session_token_key, sessionToken); } this.revID = this.options.revID; this.nodes = new Nodes(this.options.node_id); this.observer = new Observer(this, this.options); this.ticker = new Ticker(this); this.ticker.attach(() => this.commit()); try { this.worker = new Worker( URL.createObjectURL( new Blob([`WEBWORKER_BODY`], { type: 'text/javascript' }), ), ); this.worker.onerror = e => { this._debug("webworker_error", e) } let lastTs = timestamp(); let fileno = 0; this.worker.onmessage = ({ data }: MessageEvent) => { if (data === null) { this.stop(); } else if (data === "restart") { this.stop(); this.start(true); } }; const alertWorker = () => { if (this.worker) { this.worker.postMessage(null); } } // TODO: keep better tactics, discard others (look https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon) this.attachEventListener(window, 'beforeunload', alertWorker, false); this.attachEventListener(document, 'mouseleave', alertWorker, false, false); this.attachEventListener(document, 'visibilitychange', alertWorker, false); } catch (e) { this._debug("worker_start", e); } } private _debug(context: string, e: any) { if(this.options.__debug_report_edp !== null) { fetch(this.options.__debug_report_edp, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ context, error: `${e}` }) }); } if(this.options.__debug_log) { warn("OpenReplay error: ", context, e) } } send(message: Message, urgent = false): void { if (!this.isActive) { return; } this.messages.push(message); if (urgent) { this.commit(); } } private commit(): void { if (this.worker && this.messages.length) { this.messages.unshift(new Timestamp(timestamp())); this.worker.postMessage(this.messages); this.commitCallbacks.forEach(cb => cb(this.messages)); this.messages.length = 0; } } attachCommitCallback(cb: CommitCallback): void { this.commitCallbacks.push(cb) } // @Depricated (TODO: remove in 3.5.*) addCommitCallback(cb: CommitCallback): void { this.attachCommitCallback(cb) } safe<T extends (...args: any[]) => void>(fn: T): T { const app = this; return function (this: any, ...args: any) { try { fn.apply(this, args); } catch (e) { app._debug("safe_fn_call", e) // time: timestamp(), // name: e.name, // message: e.message, // stack: e.stack } } as any // TODO: correct typing } attachStartCallback(cb: Callback): void { this.startCallbacks.push(cb); } attachStopCallback(cb: Callback): void { this.stopCallbacks.push(cb); } attachEventListener( target: EventTarget, type: string, listener: EventListener, useSafe = true, useCapture = true, ): void { if (useSafe) { listener = this.safe(listener); } this.attachStartCallback(() => target.addEventListener(type, listener, useCapture), ); this.attachStopCallback(() => target.removeEventListener(type, listener, useCapture), ); } getSessionToken(): string | undefined { const token = sessionStorage.getItem(this.options.session_token_key); if (token !== null) { return token; } } getSessionID(): string | undefined { return this._sessionID || undefined; } getHost(): string { return new URL(this.options.ingestPoint).hostname } getProjectKey(): string { return this.projectKey } getBaseHref(): string { if (typeof this.options.resourceBaseHref === 'string') { return this.options.resourceBaseHref } else if (typeof this.options.resourceBaseHref === 'object') { //switch between types } if (document.baseURI) { return document.baseURI } // IE only return document.head ?.getElementsByTagName("base")[0] ?.getAttribute("href") || location.origin + location.pathname } resolveResourceURL(resourceURL: string): string { const base = new URL(this.getBaseHref()) base.pathname += "/" + new URL(resourceURL).pathname base.pathname.replace(/\/+/g, "/") return base.toString() } isServiceURL(url: string): boolean { return url.startsWith(this.options.ingestPoint) } active(): boolean { return this.isActive; } private _start(reset: boolean): Promise<OnStartInfo> { if (!this.isActive) { if (!this.worker) { return Promise.reject("No worker found: perhaps, CSP is not set."); } this.isActive = true; let pageNo: number = 0; const pageNoStr = sessionStorage.getItem(this.options.session_pageno_key); if (pageNoStr != null) { pageNo = parseInt(pageNoStr); pageNo++; } sessionStorage.setItem(this.options.session_pageno_key, pageNo.toString()); const startTimestamp = timestamp(); const messageData: WorkerMessageData = { ingestPoint: this.options.ingestPoint, pageNo, startTimestamp, connAttemptCount: this.options.connAttemptCount, connAttemptGap: this.options.connAttemptGap, } this.worker.postMessage(messageData); // brings delay of 10th ms? return window.fetch(this.options.ingestPoint + '/v1/web/start', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ token: sessionStorage.getItem(this.options.session_token_key), userUUID: localStorage.getItem(this.options.local_uuid_key), projectKey: this.projectKey, revID: this.revID, timestamp: startTimestamp, trackerVersion: this.version, isSnippet: this.options.__is_snippet, deviceMemory, jsHeapSizeLimit, reset, }), }) .then(r => { if (r.status === 200) { return r.json() } else { // TODO: handle canceling && 403 return r.text().then(text => { throw new Error(`Server error: ${r.status}. ${text}`); }); } }) .then(r => { const { token, userUUID, sessionID, beaconSizeLimit } = r; if (typeof token !== 'string' || typeof userUUID !== 'string' || (typeof beaconSizeLimit !== 'number' && typeof beaconSizeLimit !== 'undefined')) { throw new Error(`Incorrect server response: ${ JSON.stringify(r) }`); } sessionStorage.setItem(this.options.session_token_key, token); localStorage.setItem(this.options.local_uuid_key, userUUID); if (typeof sessionID === 'string') { this._sessionID = sessionID; } if (!this.worker) { throw new Error("no worker found after start request (this might not happen)"); } this.worker.postMessage({ token, beaconSizeLimit }); this.startCallbacks.forEach((cb) => cb()); this.observer.observe(); this.ticker.start(); log("OpenReplay tracking started."); const onStartInfo = { sessionToken: token, userUUID, sessionID }; if (typeof this.options.onStart === 'function') { this.options.onStart(onStartInfo); } return onStartInfo; }) .catch(e => { sessionStorage.removeItem(this.options.session_token_key) this.stop() warn("OpenReplay was unable to start. ", e) this._debug("session_start", e); throw e }) } return Promise.reject("Player is already active"); } start(reset: boolean = false): Promise<OnStartInfo> { if (!document.hidden) { return this._start(reset); } else { return new Promise((resolve) => { const onVisibilityChange = () => { if (!document.hidden) { document.removeEventListener("visibilitychange", onVisibilityChange); resolve(this._start(reset)); } } document.addEventListener("visibilitychange", onVisibilityChange); }); } } stop(): void { if (this.isActive) { try { if (this.worker) { this.worker.postMessage("stop"); } this.observer.disconnect(); this.nodes.clear(); this.ticker.stop(); this.stopCallbacks.forEach((cb) => cb()); log("OpenReplay tracking stopped.") } finally { this.isActive = false; } } } }
the_stack
import * as Common from '../../core/common/common.js'; import * as Host from '../../core/host/host.js'; import * as i18n from '../../core/i18n/i18n.js'; import * as Platform from '../../core/platform/platform.js'; import * as Root from '../../core/root/root.js'; import * as SDK from '../../core/sdk/sdk.js'; import * as Bindings from '../../models/bindings/bindings.js'; import * as TextUtils from '../../models/text_utils/text_utils.js'; import * as Workspace from '../../models/workspace/workspace.js'; import * as ObjectUI from '../../ui/legacy/components/object_ui/object_ui.js'; import * as SourceFrame from '../../ui/legacy/components/source_frame/source_frame.js'; import type * as TextEditor from '../../ui/legacy/components/text_editor/text_editor.js'; import * as UI from '../../ui/legacy/legacy.js'; import * as Protocol from '../../generated/protocol.js'; import {AddSourceMapURLDialog} from './AddSourceMapURLDialog.js'; import {BreakpointEditDialog, LogpointPrefix} from './BreakpointEditDialog.js'; import {Plugin} from './Plugin.js'; import {ScriptFormatterEditorAction} from './ScriptFormatterEditorAction.js'; import {resolveExpression, resolveScopeInObject} from './SourceMapNamesResolver.js'; import {SourcesPanel} from './SourcesPanel.js'; import {getRegisteredEditorActions} from './SourcesView.js'; const UIStrings = { /** *@description Text in Debugger Plugin of the Sources panel */ thisScriptIsOnTheDebuggersIgnore: 'This script is on the debugger\'s ignore list', /** *@description Text to stop preventing the debugger from stepping into library code */ removeFromIgnoreList: 'Remove from ignore list', /** *@description Text of a button in the Sources panel Debugger Plugin to configure ignore listing in Settings */ configure: 'Configure', /** *@description Text in Debugger Plugin of the Sources panel */ sourceMapFoundButIgnoredForFile: 'Source map found, but ignored for file on ignore list.', /** *@description Text to add a breakpoint */ addBreakpoint: 'Add breakpoint', /** *@description A context menu item in the Debugger Plugin of the Sources panel */ addConditionalBreakpoint: 'Add conditional breakpoint…', /** *@description A context menu item in the Debugger Plugin of the Sources panel */ addLogpoint: 'Add logpoint…', /** *@description A context menu item in the Debugger Plugin of the Sources panel */ neverPauseHere: 'Never pause here', /** *@description Context menu command to delete/remove a breakpoint that the user *has set. One line of code can have multiple breakpoints. Always >= 1 breakpoint. */ removeBreakpoint: '{n, plural, =1 {Remove breakpoint} other {Remove all breakpoints in line}}', /** *@description A context menu item in the Debugger Plugin of the Sources panel */ editBreakpoint: 'Edit breakpoint…', /** *@description Context menu command to disable (but not delete) a breakpoint *that the user has set. One line of code can have multiple breakpoints. Always *>= 1 breakpoint. */ disableBreakpoint: '{n, plural, =1 {Disable breakpoint} other {Disable all breakpoints in line}}', /** *@description Context menu command to enable a breakpoint that the user has *set. One line of code can have multiple breakpoints. Always >= 1 breakpoint. */ enableBreakpoint: '{n, plural, =1 {Enable breakpoint} other {Enable all breakpoints in line}}', /** *@description Text in Debugger Plugin of the Sources panel */ addSourceMap: 'Add source map…', /** *@description Text in Debugger Plugin of the Sources panel */ sourceMapDetected: 'Source map detected.', /** *@description Text in Debugger Plugin of the Sources panel */ prettyprintThisMinifiedFile: 'Pretty-print this minified file?', /** *@description Label of a button in the Sources panel to pretty-print the current file */ prettyprint: 'Pretty-print', /** *@description Text in Debugger Plugin pretty-print details message of the Sources panel *@example {Debug} PH1 */ prettyprintingWillFormatThisFile: 'Pretty-printing will format this file in a new tab where you can continue debugging. You can also pretty-print this file by clicking the {PH1} button on the bottom status bar.', /** *@description Title of the Filtered List WidgetProvider of Quick Open *@example {Ctrl+P Ctrl+O} PH1 */ associatedFilesAreAvailable: 'Associated files are available via file tree or {PH1}.', /** *@description Text in Debugger Plugin of the Sources panel */ associatedFilesShouldBeAdded: 'Associated files should be added to the file tree. You can debug these resolved source files as regular JavaScript files.', /** *@description Text in Debugger Plugin of the Sources panel */ theDebuggerWillSkipStepping: 'The debugger will skip stepping through this script, and will not stop on exceptions.', }; const str_ = i18n.i18n.registerUIStrings('panels/sources/DebuggerPlugin.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); // eslint-disable-next-line no-unused-vars class DecoratorWidget extends HTMLDivElement { // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/naming-convention nameToToken!: Map<string, HTMLElement>; constructor() { super(); } } export class DebuggerPlugin extends Plugin { private textEditor: SourceFrame.SourcesTextEditor.SourcesTextEditor; private uiSourceCode: Workspace.UISourceCode.UISourceCode; private readonly transformer: SourceFrame.SourceFrame.Transformer; private executionLocation: Workspace.UISourceCode.UILocation|null; private controlDown: boolean; private asyncStepInHoveredLine: number|null; private asyncStepInHovered: boolean; private clearValueWidgetsTimer: number|null; private sourceMapInfobar: UI.Infobar.Infobar|null; private controlTimeout: number|null; private readonly scriptsPanel: SourcesPanel; private readonly breakpointManager: Bindings.BreakpointManager.BreakpointManager; private readonly popoverHelper: UI.PopoverHelper.PopoverHelper; private readonly boundPopoverHelperHide: () => void; private readonly boundKeyDown: (arg0: Event) => void; private readonly boundKeyUp: (arg0: Event) => void; private readonly boundMouseMove: (arg0: Event) => void; private readonly boundMouseDown: (arg0: Event) => void; private readonly boundBlur: (arg0: Event) => void; private readonly boundWheel: (arg0: Event) => void; private readonly boundGutterClick: (arg0: Common.EventTarget.EventTargetEvent<SourceFrame.SourcesTextEditor.GutterClickEventData>) => void; private readonly breakpointDecorations: Set<BreakpointDecoration>; private readonly decorationByBreakpoint: Map<Bindings.BreakpointManager.Breakpoint, Map<string, BreakpointDecoration>>; private readonly possibleBreakpointsRequested: Set<number>; private scriptFileForDebuggerModel: Map<SDK.DebuggerModel.DebuggerModel, Bindings.ResourceScriptMapping.ResourceScriptFile>; private readonly valueWidgets: Map<number, DecoratorWidget>; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/no-explicit-any private continueToLocationDecorations: Map<any, Function>|null; private readonly liveLocationPool: Bindings.LiveLocation.LiveLocationPool; private muted: boolean; private mutedFromStart: boolean; private ignoreListInfobar: UI.Infobar.Infobar|null; private hasLineWithoutMapping: boolean; private prettyPrintInfobar!: UI.Infobar.Infobar|null; private scheduledBreakpointDecorationUpdates?: Set<BreakpointDecoration>|null; constructor( textEditor: SourceFrame.SourcesTextEditor.SourcesTextEditor, uiSourceCode: Workspace.UISourceCode.UISourceCode, transformer: SourceFrame.SourceFrame.Transformer) { super(); this.textEditor = textEditor; this.uiSourceCode = uiSourceCode; this.transformer = transformer; this.executionLocation = null; this.controlDown = false; this.asyncStepInHoveredLine = 0; this.asyncStepInHovered = false; this.clearValueWidgetsTimer = null; this.sourceMapInfobar = null; this.controlTimeout = null; this.scriptsPanel = SourcesPanel.instance(); this.breakpointManager = Bindings.BreakpointManager.BreakpointManager.instance(); if (uiSourceCode.project().type() === Workspace.Workspace.projectTypes.Debugger) { this.textEditor.element.classList.add('source-frame-debugger-script'); } this.popoverHelper = new UI.PopoverHelper.PopoverHelper(this.scriptsPanel.element, this.getPopoverRequest.bind(this)); this.popoverHelper.setDisableOnClick(true); this.popoverHelper.setTimeout(250, 250); this.popoverHelper.setHasPadding(true); this.boundPopoverHelperHide = this.popoverHelper.hidePopover.bind(this.popoverHelper); this.scriptsPanel.element.addEventListener('scroll', this.boundPopoverHelperHide, true); const shortcutHandlers = { 'debugger.toggle-breakpoint': async(): Promise<boolean> => { const selection = this.textEditor.selection(); if (!selection) { return false; } await this.toggleBreakpoint(selection.startLine, false); return true; }, 'debugger.toggle-breakpoint-enabled': async(): Promise<boolean> => { const selection = this.textEditor.selection(); if (!selection) { return false; } await this.toggleBreakpoint(selection.startLine, true); return true; }, 'debugger.breakpoint-input-window': async(): Promise<boolean> => { const selection = this.textEditor.selection(); if (!selection) { return false; } const breakpoints = this.lineBreakpointDecorations(selection.startLine) .map(decoration => decoration.breakpoint) .filter(breakpoint => Boolean(breakpoint)); let breakpoint: (Bindings.BreakpointManager.Breakpoint|null)|null = null; if (breakpoints.length) { breakpoint = breakpoints[0]; } const isLogpoint = breakpoint ? breakpoint.condition().includes(LogpointPrefix) : false; this.editBreakpointCondition(selection.startLine, breakpoint, null, isLogpoint); return true; }, }; UI.ShortcutRegistry.ShortcutRegistry.instance().addShortcutListener(this.textEditor.element, shortcutHandlers); this.boundKeyDown = (this.onKeyDown.bind(this) as (arg0: Event) => void); this.textEditor.element.addEventListener('keydown', this.boundKeyDown, true); this.boundKeyUp = (this.onKeyUp.bind(this) as (arg0: Event) => void); this.textEditor.element.addEventListener('keyup', this.boundKeyUp, true); this.boundMouseMove = (this.onMouseMove.bind(this) as (arg0: Event) => void); this.textEditor.element.addEventListener('mousemove', this.boundMouseMove, false); this.boundMouseDown = (this.onMouseDown.bind(this) as (arg0: Event) => void); this.textEditor.element.addEventListener('mousedown', this.boundMouseDown, true); this.boundBlur = (this.onBlur.bind(this) as (arg0: Event) => void); this.textEditor.element.addEventListener('focusout', this.boundBlur, false); this.boundWheel = (this.onWheel.bind(this) as (arg0: Event) => void); this.textEditor.element.addEventListener('wheel', this.boundWheel, true); this.boundGutterClick = (e: Common.EventTarget.EventTargetEvent<SourceFrame.SourcesTextEditor.GutterClickEventData>): void => { this.handleGutterClick(e); }; this.textEditor.addEventListener(SourceFrame.SourcesTextEditor.Events.GutterClick, this.boundGutterClick, this); this.breakpointManager.addEventListener( Bindings.BreakpointManager.Events.BreakpointAdded, this.breakpointAdded, this); this.breakpointManager.addEventListener( Bindings.BreakpointManager.Events.BreakpointRemoved, this.breakpointRemoved, this); this.uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged, this.workingCopyChanged, this); this.uiSourceCode.addEventListener( Workspace.UISourceCode.Events.WorkingCopyCommitted, this.workingCopyCommitted, this); this.breakpointDecorations = new Set(); this.decorationByBreakpoint = new Map(); this.possibleBreakpointsRequested = new Set(); this.scriptFileForDebuggerModel = new Map(); Common.Settings.Settings.instance() .moduleSetting('skipStackFramesPattern') .addChangeListener(this.showIgnoreListInfobarIfNeeded, this); Common.Settings.Settings.instance() .moduleSetting('skipContentScripts') .addChangeListener(this.showIgnoreListInfobarIfNeeded, this); this.valueWidgets = new Map(); this.continueToLocationDecorations = null; UI.Context.Context.instance().addFlavorChangeListener(SDK.DebuggerModel.CallFrame, this.callFrameChanged, this); this.liveLocationPool = new Bindings.LiveLocation.LiveLocationPool(); this.callFrameChanged(); this.updateScriptFiles(); if (this.uiSourceCode.isDirty()) { this.muted = true; this.mutedFromStart = true; } else { this.muted = false; this.mutedFromStart = false; this.initializeBreakpoints(); } this.ignoreListInfobar = null; this.showIgnoreListInfobarIfNeeded(); for (const scriptFile of this.scriptFileForDebuggerModel.values()) { scriptFile.checkMapping(); } this.hasLineWithoutMapping = false; this.updateLinesWithoutMappingHighlight(); if (!Root.Runtime.experiments.isEnabled('sourcesPrettyPrint')) { this.prettyPrintInfobar = null; this.detectMinified(); } } static accepts(uiSourceCode: Workspace.UISourceCode.UISourceCode): boolean { return uiSourceCode.contentType().hasScripts(); } private showIgnoreListInfobarIfNeeded(): void { const uiSourceCode = this.uiSourceCode; if (!uiSourceCode.contentType().hasScripts()) { return; } const projectType = uiSourceCode.project().type(); if (!Bindings.IgnoreListManager.IgnoreListManager.instance().isIgnoreListedUISourceCode(uiSourceCode)) { this.hideIgnoreListInfobar(); return; } if (this.ignoreListInfobar) { this.ignoreListInfobar.dispose(); } function unIgnoreList(): void { Bindings.IgnoreListManager.IgnoreListManager.instance().unIgnoreListUISourceCode(uiSourceCode); if (projectType === Workspace.Workspace.projectTypes.ContentScripts) { Bindings.IgnoreListManager.IgnoreListManager.instance().unIgnoreListContentScripts(); } } const infobar = new UI.Infobar.Infobar(UI.Infobar.Type.Warning, i18nString(UIStrings.thisScriptIsOnTheDebuggersIgnore), [ {text: i18nString(UIStrings.removeFromIgnoreList), highlight: false, delegate: unIgnoreList, dismiss: true}, { text: i18nString(UIStrings.configure), highlight: false, delegate: UI.ViewManager.ViewManager.instance().showView.bind(UI.ViewManager.ViewManager.instance(), 'blackbox'), dismiss: false, }, ]); this.ignoreListInfobar = infobar; infobar.createDetailsRowMessage(i18nString(UIStrings.theDebuggerWillSkipStepping)); const scriptFile = this.scriptFileForDebuggerModel.size ? this.scriptFileForDebuggerModel.values().next().value : null; if (scriptFile && scriptFile.hasSourceMapURL()) { infobar.createDetailsRowMessage(i18nString(UIStrings.sourceMapFoundButIgnoredForFile)); } this.textEditor.attachInfobar(this.ignoreListInfobar); } private hideIgnoreListInfobar(): void { if (!this.ignoreListInfobar) { return; } this.ignoreListInfobar.dispose(); this.ignoreListInfobar = null; } wasShown(): void { if (this.executionLocation) { // We need SourcesTextEditor to be initialized prior to this call. @see crbug.com/499889 queueMicrotask(() => { this.generateValuesInSource(); }); } } willHide(): void { this.popoverHelper.hidePopover(); } async populateLineGutterContextMenu(contextMenu: UI.ContextMenu.ContextMenu, editorLineNumber: number): Promise<void> { const uiLocation = new Workspace.UISourceCode.UILocation(this.uiSourceCode, editorLineNumber, 0); this.scriptsPanel.appendUILocationItems(contextMenu, uiLocation); const breakpoints = (this.lineBreakpointDecorations(editorLineNumber) .map(decoration => decoration.breakpoint) .filter(breakpoint => Boolean(breakpoint)) as Bindings.BreakpointManager.Breakpoint[]); const supportsConditionalBreakpoints = Bindings.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().supportsConditionalBreakpoints( this.uiSourceCode); if (!breakpoints.length) { if (!this.textEditor.hasLineClass(editorLineNumber, 'cm-non-breakable-line')) { contextMenu.debugSection().appendItem( i18nString(UIStrings.addBreakpoint), this.createNewBreakpoint.bind(this, editorLineNumber, '', true)); if (supportsConditionalBreakpoints) { contextMenu.debugSection().appendItem( i18nString(UIStrings.addConditionalBreakpoint), this.editBreakpointCondition.bind(this, editorLineNumber, null, null, false /* preferLogpoint */)); contextMenu.debugSection().appendItem( i18nString(UIStrings.addLogpoint), this.editBreakpointCondition.bind(this, editorLineNumber, null, null, true /* preferLogpoint */)); contextMenu.debugSection().appendItem( i18nString(UIStrings.neverPauseHere), this.createNewBreakpoint.bind(this, editorLineNumber, 'false', true)); } } } else { const removeTitle = i18nString(UIStrings.removeBreakpoint, {n: breakpoints.length}); contextMenu.debugSection().appendItem(removeTitle, () => breakpoints.map(breakpoint => breakpoint.remove(false))); if (breakpoints.length === 1 && supportsConditionalBreakpoints) { // Editing breakpoints only make sense for conditional breakpoints // and logpoints and both are currently only available for JavaScript // debugging. contextMenu.debugSection().appendItem( i18nString(UIStrings.editBreakpoint), this.editBreakpointCondition.bind( this, editorLineNumber, breakpoints[0], null, false /* preferLogpoint */)); } const hasEnabled = breakpoints.some(breakpoint => breakpoint.enabled()); if (hasEnabled) { const title = i18nString(UIStrings.disableBreakpoint, {n: breakpoints.length}); contextMenu.debugSection().appendItem(title, () => breakpoints.map(breakpoint => breakpoint.setEnabled(false))); } const hasDisabled = breakpoints.some(breakpoint => !breakpoint.enabled()); if (hasDisabled) { const title = i18nString(UIStrings.enableBreakpoint, {n: breakpoints.length}); contextMenu.debugSection().appendItem(title, () => breakpoints.map(breakpoint => breakpoint.setEnabled(true))); } } } populateTextAreaContextMenu( contextMenu: UI.ContextMenu.ContextMenu, editorLineNumber: number, editorColumnNumber: number): Promise<void> { function addSourceMapURL(scriptFile: Bindings.ResourceScriptMapping.ResourceScriptFile): void { const dialog = new AddSourceMapURLDialog(addSourceMapURLDialogCallback.bind(null, scriptFile)); dialog.show(); } function addSourceMapURLDialogCallback( scriptFile: Bindings.ResourceScriptMapping.ResourceScriptFile, url: string): void { if (!url) { return; } scriptFile.addSourceMapURL(url); } function populateSourceMapMembers(this: DebuggerPlugin): void { if (this.uiSourceCode.project().type() === Workspace.Workspace.projectTypes.Network && Common.Settings.Settings.instance().moduleSetting('jsSourceMapsEnabled').get() && !Bindings.IgnoreListManager.IgnoreListManager.instance().isIgnoreListedUISourceCode(this.uiSourceCode)) { if (this.scriptFileForDebuggerModel.size) { const scriptFile = this.scriptFileForDebuggerModel.values().next().value; const addSourceMapURLLabel = i18nString(UIStrings.addSourceMap); contextMenu.debugSection().appendItem(addSourceMapURLLabel, addSourceMapURL.bind(null, scriptFile)); } } } return super.populateTextAreaContextMenu(contextMenu, editorLineNumber, editorColumnNumber) .then(populateSourceMapMembers.bind(this)); } private workingCopyChanged(): void { if (this.scriptFileForDebuggerModel.size) { return; } if (this.uiSourceCode.isDirty()) { this.muteBreakpointsWhileEditing(); } else { this.restoreBreakpointsAfterEditing(); } } private workingCopyCommitted(): void { this.scriptsPanel.updateLastModificationTime(); if (!this.scriptFileForDebuggerModel.size) { this.restoreBreakpointsAfterEditing(); } } private didMergeToVM(): void { this.restoreBreakpointsIfConsistentScripts(); } private didDivergeFromVM(): void { this.muteBreakpointsWhileEditing(); } private muteBreakpointsWhileEditing(): void { if (this.muted) { return; } for (const decoration of this.breakpointDecorations) { this.updateBreakpointDecoration(decoration); } this.muted = true; } private async restoreBreakpointsIfConsistentScripts(): Promise<void> { for (const scriptFile of this.scriptFileForDebuggerModel.values()) { if (scriptFile.hasDivergedFromVM() || scriptFile.isMergingToVM()) { return; } } await this.restoreBreakpointsAfterEditing(); } private async restoreBreakpointsAfterEditing(): Promise<void> { this.muted = false; if (this.mutedFromStart) { this.mutedFromStart = false; this.initializeBreakpoints(); return; } const decorations = Array.from(this.breakpointDecorations); this.breakpointDecorations.clear(); this.textEditor.operation(() => decorations.map(decoration => decoration.hide())); for (const decoration of decorations) { if (!decoration.breakpoint) { continue; } const enabled = decoration.enabled; decoration.breakpoint.remove(false); const location = decoration.handle.resolve(); if (location) { await this.setBreakpoint(location.lineNumber, location.columnNumber, decoration.condition, enabled); } } } private isIdentifier(tokenType: string): boolean { return tokenType.startsWith('js-variable') || tokenType.startsWith('js-property') || tokenType === 'js-def' || tokenType === 'variable'; } private getPopoverRequest(event: MouseEvent): UI.PopoverHelper.PopoverRequest|null { if (UI.KeyboardShortcut.KeyboardShortcut.eventHasCtrlEquivalentKey(event)) { return null; } const target = UI.Context.Context.instance().flavor(SDK.Target.Target); const debuggerModel = target ? target.model(SDK.DebuggerModel.DebuggerModel) : null; if (!debuggerModel || !debuggerModel.isPaused()) { return null; } const textPosition = this.textEditor.coordinatesToCursorPosition(event.x, event.y); if (!textPosition) { return null; } const mouseLine = textPosition.startLine; const mouseColumn = textPosition.startColumn; const textSelection = this.textEditor.selection().normalize(); let editorLineNumber = -1; let startHighlight = -1; let endHighlight = -1; const selectedCallFrame = (UI.Context.Context.instance().flavor(SDK.DebuggerModel.CallFrame) as SDK.DebuggerModel.CallFrame); if (!selectedCallFrame) { return null; } if (textSelection && !textSelection.isEmpty()) { if (textSelection.startLine !== textSelection.endLine || textSelection.startLine !== mouseLine || mouseColumn < textSelection.startColumn || mouseColumn > textSelection.endColumn) { return null; } editorLineNumber = textSelection.startLine; startHighlight = textSelection.startColumn; endHighlight = textSelection.endColumn - 1; } else if (this.uiSourceCode.mimeType() === 'application/wasm') { const token = this.textEditor.tokenAtTextPosition(textPosition.startLine, textPosition.startColumn); if (!token || token.type !== 'variable-2') { return null; } editorLineNumber = textPosition.startLine; startHighlight = token.startColumn; endHighlight = token.endColumn - 1; // For $label identifiers we can't show a meaningful preview (https://crbug.com/1155548), // so we suppress them for now. Label identifiers can only appear as operands to control // instructions[1], so we just check the first token on the line and filter them out. // // [1]: https://webassembly.github.io/spec/core/text/instructions.html#control-instructions for (let firstColumn = 0; firstColumn < startHighlight; ++firstColumn) { const firstToken = this.textEditor.tokenAtTextPosition(editorLineNumber, firstColumn); if (firstToken && firstToken.type === 'keyword') { const line = this.textEditor.line(editorLineNumber); switch (line.substring(firstToken.startColumn, firstToken.endColumn)) { case 'block': case 'loop': case 'if': case 'else': case 'end': case 'br': case 'br_if': case 'br_table': return null; default: break; } break; } } } else { let token = this.textEditor.tokenAtTextPosition(textPosition.startLine, textPosition.startColumn); if (!token) { return null; } editorLineNumber = textPosition.startLine; const line = this.textEditor.line(editorLineNumber); let tokenContent = line.substring(token.startColumn, token.endColumn); // When the user hovers an opening bracket, we look for the closing bracket // and kick off the matching from that below. if (tokenContent === '[') { const closingColumn = line.indexOf(']', token.startColumn); if (closingColumn < 0) { return null; } token = this.textEditor.tokenAtTextPosition(editorLineNumber, closingColumn); if (!token) { return null; } tokenContent = line.substring(token.startColumn, token.endColumn); } startHighlight = token.startColumn; endHighlight = token.endColumn - 1; // Consume multiple `[index][0]...[f(1)]` at the end of the expression. while (tokenContent === ']') { startHighlight = line.lastIndexOf('[', startHighlight) - 1; if (startHighlight < 0) { return null; } token = this.textEditor.tokenAtTextPosition(editorLineNumber, startHighlight); if (!token) { return null; } tokenContent = line.substring(token.startColumn, token.endColumn); startHighlight = token.startColumn; } if (!token.type) { return null; } const isIdentifier = this.isIdentifier(token.type); if (!isIdentifier && (token.type !== 'js-keyword' || tokenContent !== 'this')) { return null; } while (startHighlight > 1 && line.charAt(startHighlight - 1) === '.') { // Consume multiple `[index][0]...[f(1)]` preceeding a dot. while (line.charAt(startHighlight - 2) === ']') { startHighlight = line.lastIndexOf('[', startHighlight - 2) - 1; if (startHighlight < 0) { return null; } } const tokenBefore = this.textEditor.tokenAtTextPosition(editorLineNumber, startHighlight - 2); if (!tokenBefore || !tokenBefore.type) { return null; } if (tokenBefore.type === 'js-meta') { break; } if (tokenBefore.type === 'js-string-2') { // If we hit a template literal, find the opening ` in this line. // TODO(bmeurer): We should eventually replace this tokenization // approach with a proper soluation based on parsing, maybe reusing // the Parser and AST inside V8 for this (or potentially relying on // acorn to do the job). if (tokenBefore.endColumn < 2) { return null; } startHighlight = line.lastIndexOf('`', tokenBefore.endColumn - 2); if (startHighlight < 0) { return null; } break; } startHighlight = tokenBefore.startColumn; } } const leftCorner = (this.textEditor.cursorPositionToCoordinates(editorLineNumber, startHighlight) as TextEditor.CodeMirrorTextEditor.Coordinates); const rightCorner = (this.textEditor.cursorPositionToCoordinates(editorLineNumber, endHighlight) as TextEditor.CodeMirrorTextEditor.Coordinates); const box = new AnchorBox(leftCorner.x, leftCorner.y, rightCorner.x - leftCorner.x, leftCorner.height); let objectPopoverHelper: ObjectUI.ObjectPopoverHelper.ObjectPopoverHelper|null = null; let highlightDescriptor: CodeMirror.TextMarker|null = null; async function evaluate(uiSourceCode: Workspace.UISourceCode.UISourceCode, evaluationText: string): Promise<{ object: SDK.RemoteObject.RemoteObject, exceptionDetails?: Protocol.Runtime.ExceptionDetails, }|{ error: string, }|null> { const resolvedText = await resolveExpression( selectedCallFrame, evaluationText, uiSourceCode, editorLineNumber, startHighlight, endHighlight); return await selectedCallFrame.evaluate({ expression: resolvedText || evaluationText, objectGroup: 'popover', includeCommandLineAPI: false, silent: true, returnByValue: false, generatePreview: false, throwOnSideEffect: undefined, timeout: undefined, disableBreaks: undefined, replMode: undefined, allowUnsafeEvalBlockedByCSP: undefined, }); } return { box, show: async(popover: UI.GlassPane.GlassPane): Promise<boolean> => { const evaluationText = this.textEditor.line(editorLineNumber).substring(startHighlight, endHighlight + 1); const result = await evaluate(this.uiSourceCode, evaluationText); if (!result || 'error' in result || !result.object || (result.object.type === 'object' && result.object.subtype === 'error')) { return false; } objectPopoverHelper = await ObjectUI.ObjectPopoverHelper.ObjectPopoverHelper.buildObjectPopover(result.object, popover); const potentiallyUpdatedCallFrame = UI.Context.Context.instance().flavor(SDK.DebuggerModel.CallFrame); if (!objectPopoverHelper || selectedCallFrame !== potentiallyUpdatedCallFrame) { debuggerModel.runtimeModel().releaseObjectGroup('popover'); if (objectPopoverHelper) { objectPopoverHelper.dispose(); } return false; } const highlightRange = new TextUtils.TextRange.TextRange(editorLineNumber, startHighlight, editorLineNumber, endHighlight); highlightDescriptor = this.textEditor.highlightRange(highlightRange, 'source-frame-eval-expression'); return true; }, hide: (): void => { if (objectPopoverHelper) { objectPopoverHelper.dispose(); } debuggerModel.runtimeModel().releaseObjectGroup('popover'); if (highlightDescriptor) { this.textEditor.removeHighlight(highlightDescriptor); } }, }; } private onWheel(event: WheelEvent): void { if (this.executionLocation && UI.KeyboardShortcut.KeyboardShortcut.eventHasCtrlEquivalentKey(event)) { event.preventDefault(); } } private onKeyDown(event: KeyboardEvent): void { if (!event.ctrlKey || (!event.metaKey && Host.Platform.isMac())) { this.clearControlDown(); } if (event.key === Platform.KeyboardUtilities.ESCAPE_KEY) { if (this.popoverHelper.isPopoverVisible()) { this.popoverHelper.hidePopover(); event.consume(); } return; } if (UI.KeyboardShortcut.KeyboardShortcut.eventHasCtrlEquivalentKey(event) && this.executionLocation) { this.controlDown = true; if (event.key === (Host.Platform.isMac() ? 'Meta' : 'Control')) { this.controlTimeout = window.setTimeout(() => { if (this.executionLocation && this.controlDown) { this.showContinueToLocations(); } }, 150); } } } private onMouseMove(event: MouseEvent): void { if (this.executionLocation && this.controlDown && UI.KeyboardShortcut.KeyboardShortcut.eventHasCtrlEquivalentKey(event)) { if (!this.continueToLocationDecorations) { this.showContinueToLocations(); } } if (this.continueToLocationDecorations) { const target = (event.target as Element); const textPosition = this.textEditor.coordinatesToCursorPosition(event.x, event.y); const hovering = Boolean(target.enclosingNodeOrSelfWithClass('source-frame-async-step-in')); this.setAsyncStepInHoveredLine(textPosition ? textPosition.startLine : null, hovering); } } private setAsyncStepInHoveredLine(editorLineNumber: number|null, hovered: boolean): void { if (this.asyncStepInHoveredLine === editorLineNumber && this.asyncStepInHovered === hovered) { return; } if (this.asyncStepInHovered && this.asyncStepInHoveredLine) { this.textEditor.toggleLineClass(this.asyncStepInHoveredLine, 'source-frame-async-step-in-hovered', false); } this.asyncStepInHoveredLine = editorLineNumber; this.asyncStepInHovered = hovered; if (this.asyncStepInHovered && this.asyncStepInHoveredLine) { this.textEditor.toggleLineClass(this.asyncStepInHoveredLine, 'source-frame-async-step-in-hovered', true); } } private onMouseDown(event: MouseEvent): void { if (!this.executionLocation || !UI.KeyboardShortcut.KeyboardShortcut.eventHasCtrlEquivalentKey(event)) { return; } if (!this.continueToLocationDecorations) { return; } event.consume(); const textPosition = this.textEditor.coordinatesToCursorPosition(event.x, event.y); if (!textPosition) { return; } for (const decoration of this.continueToLocationDecorations.keys()) { const range = decoration.find(); if (!range) { continue; } if (range.from.line !== textPosition.startLine || range.to.line !== textPosition.startLine) { continue; } if (range.from.ch <= textPosition.startColumn && textPosition.startColumn <= range.to.ch) { const callback = this.continueToLocationDecorations.get(decoration); if (!callback) { throw new Error('Expected a function'); } callback(); break; } } } private onBlur(_event: Event): void { this.clearControlDown(); } private onKeyUp(_event: KeyboardEvent): void { this.clearControlDown(); } private clearControlDown(): void { this.controlDown = false; this.clearContinueToLocations(); if (this.controlTimeout) { clearTimeout(this.controlTimeout); } } private async editBreakpointCondition( editorLineNumber: number, breakpoint: Bindings.BreakpointManager.Breakpoint|null, location: { lineNumber: number, columnNumber: number, }|null, preferLogpoint?: boolean): Promise<void> { const oldCondition = breakpoint ? breakpoint.condition() : ''; const decorationElement = document.createElement('div'); const dialog = await BreakpointEditDialog.create(editorLineNumber, oldCondition, Boolean(preferLogpoint), async result => { dialog.detach(); this.textEditor.removeDecoration(decorationElement, editorLineNumber); if (!result.committed) { return; } if (breakpoint) { breakpoint.setCondition(result.condition); } else if (location) { await this.setBreakpoint(location.lineNumber, location.columnNumber, result.condition, true); } else { await this.createNewBreakpoint(editorLineNumber, result.condition, true); } }); this.textEditor.addDecoration(decorationElement, editorLineNumber); dialog.markAsExternallyManaged(); dialog.show(decorationElement); dialog.focusEditor(); } private async executionLineChanged(liveLocation: Bindings.LiveLocation.LiveLocation): Promise<void> { this.clearExecutionLine(); const uiLocation = await liveLocation.uiLocation(); if (!uiLocation || uiLocation.uiSourceCode.url() !== this.uiSourceCode.url()) { this.executionLocation = null; return; } this.executionLocation = uiLocation; const editorLocation = this.transformer.uiLocationToEditorLocation(uiLocation.lineNumber, uiLocation.columnNumber); this.textEditor.setExecutionLocation(editorLocation.lineNumber, editorLocation.columnNumber); if (this.textEditor.isShowing()) { // We need SourcesTextEditor to be initialized prior to this call. @see crbug.com/506566 queueMicrotask(() => { if (this.controlDown) { this.showContinueToLocations(); } else { this.generateValuesInSource(); } }); } } private generateValuesInSource(): void { if (!Common.Settings.Settings.instance().moduleSetting('inlineVariableValues').get()) { return; } const executionContext = UI.Context.Context.instance().flavor(SDK.RuntimeModel.ExecutionContext); if (!executionContext) { return; } const callFrame = UI.Context.Context.instance().flavor(SDK.DebuggerModel.CallFrame); if (!callFrame) { return; } const localScope = callFrame.localScope(); const functionLocation = callFrame.functionLocation(); if (localScope && functionLocation) { resolveScopeInObject(localScope) .getAllProperties(false, false) .then(this.prepareScopeVariables.bind(this, callFrame)); } } private showContinueToLocations(): void { this.popoverHelper.hidePopover(); const executionContext = UI.Context.Context.instance().flavor(SDK.RuntimeModel.ExecutionContext); if (!executionContext) { return; } const callFrame = UI.Context.Context.instance().flavor(SDK.DebuggerModel.CallFrame); if (!callFrame) { return; } const start = callFrame.functionLocation() || callFrame.location(); const debuggerModel = callFrame.debuggerModel; debuggerModel.getPossibleBreakpoints(start, null, true) .then(locations => this.textEditor.operation(renderLocations.bind(this, locations))); function renderLocations(this: DebuggerPlugin, locations: SDK.DebuggerModel.BreakLocation[]): void { this.clearContinueToLocationsNoRestore(); this.textEditor.hideExecutionLineBackground(); this.continueToLocationDecorations = new Map(); locations = locations.reverse(); let previousCallLine = -1; for (const location of locations) { const editorLocation = this.transformer.uiLocationToEditorLocation(location.lineNumber, location.columnNumber); const tokenThatIsPossiblyNull = this.textEditor.tokenAtTextPosition(editorLocation.lineNumber, editorLocation.columnNumber); if (!tokenThatIsPossiblyNull) { continue; } let token: TextEditor.CodeMirrorTextEditor.Token = (tokenThatIsPossiblyNull as TextEditor.CodeMirrorTextEditor.Token); const line = this.textEditor.line(editorLocation.lineNumber); let tokenContent = line.substring(token.startColumn, token.endColumn); if (!token.type && tokenContent === '.') { const nextToken = this.textEditor.tokenAtTextPosition(editorLocation.lineNumber, token.endColumn + 1); if (!nextToken) { throw new Error('nextToken should not be null.'); } token = nextToken; tokenContent = line.substring(token.startColumn, token.endColumn); } if (!token.type) { continue; } const validKeyword = token.type === 'js-keyword' && (tokenContent === 'this' || tokenContent === 'return' || tokenContent === 'new' || tokenContent === 'continue' || tokenContent === 'break'); if (!validKeyword && !this.isIdentifier(token.type)) { continue; } if (previousCallLine === editorLocation.lineNumber && location.type !== Protocol.Debugger.BreakLocationType.Call) { continue; } let highlightRange: TextUtils.TextRange.TextRange = new TextUtils.TextRange.TextRange( editorLocation.lineNumber, token.startColumn, editorLocation.lineNumber, token.endColumn - 1); let decoration = this.textEditor.highlightRange(highlightRange, 'source-frame-continue-to-location'); this.continueToLocationDecorations.set(decoration, location.continueToLocation.bind(location)); if (location.type === Protocol.Debugger.BreakLocationType.Call) { previousCallLine = editorLocation.lineNumber; } let isAsyncCall: boolean = (line[token.startColumn - 1] === '.' && tokenContent === 'then') || tokenContent === 'setTimeout' || tokenContent === 'setInterval' || tokenContent === 'postMessage'; if (tokenContent === 'new') { const nextToken = this.textEditor.tokenAtTextPosition(editorLocation.lineNumber, token.endColumn + 1); if (!nextToken) { throw new Error('nextToken should not be null.'); } token = nextToken; tokenContent = line.substring(token.startColumn, token.endColumn); isAsyncCall = tokenContent === 'Worker'; } const isCurrentPosition = this.executionLocation && location.lineNumber === this.executionLocation.lineNumber && location.columnNumber === this.executionLocation.columnNumber; if (location.type === Protocol.Debugger.BreakLocationType.Call && isAsyncCall) { const asyncStepInRange = this.findAsyncStepInRange(this.textEditor, editorLocation.lineNumber, line, token.endColumn); if (asyncStepInRange) { highlightRange = new TextUtils.TextRange.TextRange( editorLocation.lineNumber, asyncStepInRange.from, editorLocation.lineNumber, asyncStepInRange.to - 1); decoration = this.textEditor.highlightRange(highlightRange, 'source-frame-async-step-in'); this.continueToLocationDecorations.set( decoration, this.asyncStepIn.bind(this, location, Boolean(isCurrentPosition))); } } } this.continueToLocationRenderedForTest(); } } private continueToLocationRenderedForTest(): void { } private findAsyncStepInRange( textEditor: SourceFrame.SourcesTextEditor.SourcesTextEditor, editorLineNumber: number, line: string, column: number): { from: number, to: number, }|null { let token: (TextEditor.CodeMirrorTextEditor.Token|null)|null = null; let tokenText; let from: number = column; let to: number = line.length; let position = line.indexOf('(', column); const argumentsStart = position; if (position === -1) { return null; } position++; skipWhitespace(); if (position >= line.length) { return null; } token = nextToken(); if (!token) { return null; } from = token.startColumn; if (token.type === 'js-keyword' && tokenText === 'async') { skipWhitespace(); if (position >= line.length) { return {from: from, to: to}; } token = nextToken(); if (!token) { return {from: from, to: to}; } } if (token.type === 'js-keyword' && tokenText === 'function') { return {from: from, to: to}; } if (token.type === 'js-string') { return {from: argumentsStart, to: to}; } if (token.type && this.isIdentifier(token.type)) { return {from: from, to: to}; } if (tokenText !== '(') { return null; } const closeParen = line.indexOf(')', position); if (closeParen === -1 || line.substring(position, closeParen).indexOf('(') !== -1) { return {from: from, to: to}; } return {from: from, to: closeParen + 1}; function nextToken(): TextEditor.CodeMirrorTextEditor.Token|null { token = textEditor.tokenAtTextPosition(editorLineNumber, position); if (token) { position = token.endColumn; to = token.endColumn; tokenText = line.substring(token.startColumn, token.endColumn); } return token; } function skipWhitespace(): void { while (position < line.length) { if (line[position] === ' ') { position++; continue; } const token = textEditor.tokenAtTextPosition(editorLineNumber, position); if (!token) { throw new Error('expected token to not be null'); } if (token.type === 'js-comment') { position = token.endColumn; continue; } break; } } } private asyncStepIn(location: SDK.DebuggerModel.BreakLocation, isCurrentPosition: boolean): void { if (!isCurrentPosition) { location.continueToLocation(asyncStepIn); } else { asyncStepIn(); } function asyncStepIn(): void { location.debuggerModel.scheduleStepIntoAsync(); } } private async prepareScopeVariables( callFrame: SDK.DebuggerModel.CallFrame, allProperties: SDK.RemoteObject.GetPropertiesResult): Promise<void> { const properties = allProperties.properties; this.clearValueWidgets(); if (!properties || !properties.length || properties.length > 500 || !this.textEditor.isShowing()) { return; } const functionUILocationPromise = Bindings.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().rawLocationToUILocation( (callFrame.functionLocation() as SDK.DebuggerModel.Location)); const executionUILocationPromise = Bindings.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().rawLocationToUILocation( callFrame.location()); const [functionUILocation, executionUILocation] = await Promise.all([functionUILocationPromise, executionUILocationPromise]); if (!functionUILocation || !executionUILocation || functionUILocation.uiSourceCode.url() !== this.uiSourceCode.url() || executionUILocation.uiSourceCode.url() !== this.uiSourceCode.url()) { return; } const functionEditorLocation = this.transformer.uiLocationToEditorLocation(functionUILocation.lineNumber, functionUILocation.columnNumber); const executionEditorLocation = this.transformer.uiLocationToEditorLocation(executionUILocation.lineNumber, executionUILocation.columnNumber); const fromLine = functionEditorLocation.lineNumber; const fromColumn = functionEditorLocation.columnNumber; const toLine = executionEditorLocation.lineNumber; if (fromLine >= toLine || toLine - fromLine > 500 || fromLine < 0 || toLine >= this.textEditor.linesCount) { return; } const valuesMap = new Map<string, SDK.RemoteObject.RemoteObject|null|undefined>(); for (const property of properties) { valuesMap.set(property.name, property.value); } const namesPerLine = new Map<number, Set<string>>(); let skipObjectProperty = false; const tokenizer = TextUtils.CodeMirrorUtils.TokenizerFactory.instance().createTokenizer('text/javascript'); tokenizer(this.textEditor.line(fromLine).substring(fromColumn), processToken.bind(this, fromLine)); for (let i = fromLine + 1; i < toLine; ++i) { tokenizer(this.textEditor.line(i), processToken.bind(this, i)); } function processToken( this: DebuggerPlugin, editorLineNumber: number, tokenValue: string, tokenType: string|null, _column: number, _newColumn: number): void { if (!skipObjectProperty && tokenType && this.isIdentifier(tokenType) && valuesMap.get(tokenValue)) { let names = namesPerLine.get(editorLineNumber); if (!names) { names = new Set(); namesPerLine.set(editorLineNumber, names); } names.add(tokenValue); } skipObjectProperty = tokenValue === '.'; } // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // @ts-expect-error this.textEditor.operation(this.renderDecorations.bind(this, valuesMap, namesPerLine, fromLine, toLine)); } private renderDecorations( valuesMap: Map<string, SDK.RemoteObject.RemoteObject>, namesPerLine: Map<number, Set<string>>, fromLine: number, toLine: number): void { const formatter = new ObjectUI.RemoteObjectPreviewFormatter.RemoteObjectPreviewFormatter(); for (let i = fromLine; i < toLine; ++i) { const names = namesPerLine.get(i); const oldWidget = this.valueWidgets.get(i); if (!names) { if (oldWidget) { this.valueWidgets.delete(i); this.textEditor.removeDecoration(oldWidget, i); } continue; } const widget = (document.createElement('div') as DecoratorWidget); widget.classList.add('text-editor-value-decoration'); const base = this.textEditor.cursorPositionToCoordinates(i, 0); if (!base) { throw new Error('base is expected to not be null'); } const offset = this.textEditor.cursorPositionToCoordinates(i, this.textEditor.line(i).length); if (!offset) { throw new Error('offset is expected to not be null'); } const codeMirrorLinesLeftPadding = 4; const left = offset.x - base.x + codeMirrorLinesLeftPadding; widget.style.left = left + 'px'; widget.nameToToken = new Map(); let renderedNameCount = 0; for (const name of names) { if (renderedNameCount > 10) { break; } const names = namesPerLine.get(i - 1); if (names && names.has(name)) { continue; } // Only render name once in the given continuous block. if (renderedNameCount) { UI.UIUtils.createTextChild(widget, ', '); } const nameValuePair = (widget.createChild('span') as HTMLElement); widget.nameToToken.set(name, nameValuePair); UI.UIUtils.createTextChild(nameValuePair, name + ' = '); const value = valuesMap.get(name); if (!value) { throw new Error('value is expected to be null'); } const propertyCount = value.preview ? value.preview.properties.length : 0; const entryCount = value.preview && value.preview.entries ? value.preview.entries.length : 0; if (value.preview && propertyCount + entryCount < 10) { formatter.appendObjectPreview(nameValuePair, value.preview, false /* isEntry */); } else { const propertyValue = ObjectUI.ObjectPropertiesSection.ObjectPropertiesSection.createPropertyValue( value, /* wasThrown */ false, /* showPreview */ false); nameValuePair.appendChild(propertyValue.element); } ++renderedNameCount; } let widgetChanged = true; if (oldWidget) { widgetChanged = false; for (const name of widget.nameToToken.keys()) { const oldTextElement = oldWidget.nameToToken.get(name); const newTextElement = widget.nameToToken.get(name); const oldText = oldTextElement ? oldTextElement.textContent : ''; const newText = newTextElement ? newTextElement.textContent : ''; if (newText !== oldText) { widgetChanged = true; UI.UIUtils.runCSSAnimationOnce( (widget.nameToToken.get(name) as Element), 'source-frame-value-update-highlight'); } } if (widgetChanged) { this.valueWidgets.delete(i); this.textEditor.removeDecoration(oldWidget, i); } } if (widgetChanged) { this.valueWidgets.set(i, widget); this.textEditor.addDecoration(widget, i); } } } private clearExecutionLine(): void { this.textEditor.operation(() => { if (this.executionLocation) { this.textEditor.clearExecutionLine(); } this.executionLocation = null; if (this.clearValueWidgetsTimer) { clearTimeout(this.clearValueWidgetsTimer); this.clearValueWidgetsTimer = null; } this.clearValueWidgetsTimer = window.setTimeout(this.clearValueWidgets.bind(this), 1000); this.clearContinueToLocationsNoRestore(); }); } private clearValueWidgets(): void { if (this.clearValueWidgetsTimer) { clearTimeout(this.clearValueWidgetsTimer); } this.clearValueWidgetsTimer = null; this.textEditor.operation(() => { for (const line of this.valueWidgets.keys()) { const valueWidget = this.valueWidgets.get(line); if (valueWidget) { this.textEditor.removeDecoration(valueWidget, line); } } this.valueWidgets.clear(); }); } private clearContinueToLocationsNoRestore(): void { const continueToLocationDecorations = this.continueToLocationDecorations; if (!continueToLocationDecorations) { return; } this.textEditor.operation(() => { for (const decoration of continueToLocationDecorations.keys()) { this.textEditor.removeHighlight(decoration); } this.continueToLocationDecorations = null; this.setAsyncStepInHoveredLine(null, false); }); } private clearContinueToLocations(): void { if (!this.continueToLocationDecorations) { return; } this.textEditor.operation(() => { this.textEditor.showExecutionLineBackground(); this.generateValuesInSource(); this.clearContinueToLocationsNoRestore(); }); } private lineBreakpointDecorations(lineNumber: number): BreakpointDecoration[] { return Array.from(this.breakpointDecorations) .filter(decoration => (decoration.handle.resolve() || {}).lineNumber === lineNumber); } private breakpointDecoration(editorLineNumber: number, editorColumnNumber: number): BreakpointDecoration|null { for (const decoration of this.breakpointDecorations) { const location = decoration.handle.resolve(); if (!location) { continue; } if (location.lineNumber === editorLineNumber && location.columnNumber === editorColumnNumber) { return decoration; } } return null; } private updateBreakpointDecoration(decoration: BreakpointDecoration): void { if (!this.scheduledBreakpointDecorationUpdates) { this.scheduledBreakpointDecorationUpdates = new Set(); queueMicrotask(() => { this.textEditor.operation(update.bind(this)); }); } this.scheduledBreakpointDecorationUpdates.add(decoration); function update(this: DebuggerPlugin): void { if (!this.scheduledBreakpointDecorationUpdates) { return; } const editorLineNumbers = new Set<number>(); for (const decoration of this.scheduledBreakpointDecorationUpdates) { const location = decoration.handle.resolve(); if (!location) { continue; } editorLineNumbers.add(location.lineNumber); } this.scheduledBreakpointDecorationUpdates = null; let waitingForInlineDecorations = false; for (const lineNumber of editorLineNumbers) { const decorations = this.lineBreakpointDecorations(lineNumber); updateGutter.call(this, lineNumber, decorations); if (this.possibleBreakpointsRequested.has(lineNumber)) { waitingForInlineDecorations = true; continue; } updateInlineDecorations.call(this, lineNumber, decorations); } if (!waitingForInlineDecorations) { this.breakpointDecorationsUpdatedForTest(); } } function updateGutter(this: DebuggerPlugin, editorLineNumber: number, decorations: BreakpointDecoration[]): void { this.textEditor.toggleLineClass(editorLineNumber, 'cm-breakpoint', false); this.textEditor.toggleLineClass(editorLineNumber, 'cm-breakpoint-disabled', false); this.textEditor.toggleLineClass(editorLineNumber, 'cm-breakpoint-unbound', false); this.textEditor.toggleLineClass(editorLineNumber, 'cm-breakpoint-conditional', false); this.textEditor.toggleLineClass(editorLineNumber, 'cm-breakpoint-logpoint', false); if (decorations.length) { decorations.sort(BreakpointDecoration.mostSpecificFirst); const isDisabled = !decorations[0].enabled || this.muted; const isLogpoint = decorations[0].condition.includes(LogpointPrefix); const isUnbound = !decorations[0].bound; const isConditionalBreakpoint = Boolean(decorations[0].condition) && !isLogpoint; this.textEditor.toggleLineClass(editorLineNumber, 'cm-breakpoint', true); this.textEditor.toggleLineClass(editorLineNumber, 'cm-breakpoint-disabled', isDisabled); this.textEditor.toggleLineClass(editorLineNumber, 'cm-breakpoint-unbound', isUnbound && !isDisabled); this.textEditor.toggleLineClass(editorLineNumber, 'cm-breakpoint-logpoint', isLogpoint); this.textEditor.toggleLineClass(editorLineNumber, 'cm-breakpoint-conditional', isConditionalBreakpoint); } } function updateInlineDecorations( this: DebuggerPlugin, editorLineNumber: number, decorations: BreakpointDecoration[]): void { const actualBookmarks = new Set<TextEditor.CodeMirrorTextEditor.TextEditorBookMark>( // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // @ts-expect-error decorations.map(decoration => decoration.bookmark).filter(bookmark => Boolean(bookmark))); const lineEnd = this.textEditor.line(editorLineNumber).length; const bookmarks = this.textEditor.bookmarks( new TextUtils.TextRange.TextRange(editorLineNumber, 0, editorLineNumber, lineEnd), BreakpointDecoration.bookmarkSymbol); for (const bookmark of bookmarks) { if (!actualBookmarks.has(bookmark)) { bookmark.clear(); } } if (!decorations.length) { return; } if (decorations.length > 1) { for (const decoration of decorations) { decoration.update(); if (!this.muted) { decoration.show(); } else { decoration.hide(); } } } else { decorations[0].update(); decorations[0].hide(); } } } private breakpointDecorationsUpdatedForTest(): void { } private async inlineBreakpointClick(decoration: BreakpointDecoration, event: MouseEvent): Promise<void> { event.consume(true); if (decoration.breakpoint) { if (event.shiftKey) { decoration.breakpoint.setEnabled(!decoration.breakpoint.enabled()); } else { decoration.breakpoint.remove(false); } } else { const editorLocation = decoration.handle.resolve(); if (!editorLocation) { return; } const location = this.transformer.editorLocationToUILocation(editorLocation.lineNumber, editorLocation.columnNumber); await this.setBreakpoint(location.lineNumber, location.columnNumber, decoration.condition, true); } } private inlineBreakpointContextMenu(decoration: BreakpointDecoration, event: Event): void { event.consume(true); const editorLocation = decoration.handle.resolve(); if (!editorLocation) { return; } if (this.textEditor.hasLineClass(editorLocation.lineNumber, 'cm-non-breakable-line')) { return; } if (!Bindings.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().supportsConditionalBreakpoints( this.uiSourceCode)) { // Editing breakpoints only make sense for conditional breakpoints // and logpoints. return; } const location = this.transformer.editorLocationToUILocation(editorLocation.lineNumber, editorLocation.columnNumber); const contextMenu = new UI.ContextMenu.ContextMenu(event); if (decoration.breakpoint) { contextMenu.debugSection().appendItem( i18nString(UIStrings.editBreakpoint), this.editBreakpointCondition.bind( this, editorLocation.lineNumber, decoration.breakpoint, null, false /* preferLogpoint */)); } else { contextMenu.debugSection().appendItem( i18nString(UIStrings.addConditionalBreakpoint), this.editBreakpointCondition.bind( this, editorLocation.lineNumber, null, editorLocation, false /* preferLogpoint */)); contextMenu.debugSection().appendItem( i18nString(UIStrings.addLogpoint), this.editBreakpointCondition.bind( this, editorLocation.lineNumber, null, editorLocation, true /* preferLogpoint */)); contextMenu.debugSection().appendItem( i18nString(UIStrings.neverPauseHere), this.setBreakpoint.bind(this, location.lineNumber, location.columnNumber, 'false', true)); } contextMenu.show(); } private shouldIgnoreExternalBreakpointEvents( event: Common.EventTarget.EventTargetEvent<Bindings.BreakpointManager.BreakpointLocation>): boolean { const {uiLocation} = event.data; if (uiLocation.uiSourceCode !== this.uiSourceCode) { return true; } if (this.muted) { return true; } for (const scriptFile of this.scriptFileForDebuggerModel.values()) { if (scriptFile.isDivergingFromVM() || scriptFile.isMergingToVM()) { return true; } } return false; } private breakpointAdded(event: Common.EventTarget.EventTargetEvent<Bindings.BreakpointManager.BreakpointLocation>): void { if (this.shouldIgnoreExternalBreakpointEvents(event)) { return; } const {breakpoint, uiLocation} = event.data; this.addBreakpoint(uiLocation, breakpoint); } private addBreakpoint( uiLocation: Workspace.UISourceCode.UILocation, breakpoint: Bindings.BreakpointManager.Breakpoint): void { const editorLocation = this.transformer.uiLocationToEditorLocation(uiLocation.lineNumber, uiLocation.columnNumber); const lineDecorations = this.lineBreakpointDecorations(uiLocation.lineNumber); let decoration = this.breakpointDecoration(editorLocation.lineNumber, editorLocation.columnNumber); if (decoration) { decoration.breakpoint = breakpoint; decoration.condition = breakpoint.condition(); decoration.enabled = breakpoint.enabled(); } else { const handle = this.textEditor.textEditorPositionHandle(editorLocation.lineNumber, editorLocation.columnNumber); decoration = new BreakpointDecoration( this.textEditor, handle, breakpoint.condition(), breakpoint.enabled(), breakpoint.bound() || !breakpoint.hasBoundScript(), breakpoint); decoration.element.addEventListener('click', this.inlineBreakpointClick.bind(this, decoration), true); decoration.element.addEventListener('contextmenu', this.inlineBreakpointContextMenu.bind(this, decoration), true); this.breakpointDecorations.add(decoration); } let uiLocationsForBreakpoint = this.decorationByBreakpoint.get(breakpoint); if (!uiLocationsForBreakpoint) { uiLocationsForBreakpoint = new Map(); this.decorationByBreakpoint.set(breakpoint, uiLocationsForBreakpoint); } uiLocationsForBreakpoint.set(uiLocation.id(), decoration); this.updateBreakpointDecoration(decoration); if (breakpoint.enabled() && !lineDecorations.length) { this.possibleBreakpointsRequested.add(editorLocation.lineNumber); const start = this.transformer.editorLocationToUILocation(editorLocation.lineNumber, 0); const end = this.transformer.editorLocationToUILocation(editorLocation.lineNumber + 1, 0); this.breakpointManager .possibleBreakpoints( this.uiSourceCode, new TextUtils.TextRange.TextRange( start.lineNumber, start.columnNumber || 0, end.lineNumber, end.columnNumber || 0)) .then(addInlineDecorations.bind(this, editorLocation.lineNumber)); } function addInlineDecorations( this: DebuggerPlugin, editorLineNumber: number, possibleLocations: Workspace.UISourceCode.UILocation[]): void { this.possibleBreakpointsRequested.delete(editorLineNumber); const decorations = this.lineBreakpointDecorations(editorLineNumber); for (const decoration of decorations) { this.updateBreakpointDecoration(decoration); } if (!decorations.some(decoration => Boolean(decoration.breakpoint))) { return; } const columns = new Set<number>(); for (const decoration of decorations) { const editorLocation = decoration.handle.resolve(); if (!editorLocation) { continue; } columns.add(editorLocation.columnNumber); } // Only consider the first 100 inline breakpoints, as DevTools might appear to hang while CodeMirror is updating // the inline breakpoints. See crbug.com/1060105. for (const location of possibleLocations.slice(0, 100)) { const editorLocation = this.transformer.uiLocationToEditorLocation(location.lineNumber, location.columnNumber); if (editorLocation.lineNumber !== editorLineNumber) { continue; } if (columns.has(editorLocation.columnNumber)) { continue; } const handle = this.textEditor.textEditorPositionHandle(editorLocation.lineNumber, editorLocation.columnNumber); const decoration = new BreakpointDecoration( this.textEditor, handle, '', /** enabled */ false, /** bound */ false, /** breakpoint */ null); decoration.element.addEventListener('click', this.inlineBreakpointClick.bind(this, decoration), true); decoration.element.addEventListener( 'contextmenu', this.inlineBreakpointContextMenu.bind(this, decoration), true); this.breakpointDecorations.add(decoration); this.updateBreakpointDecoration(decoration); } } } private breakpointRemoved(event: Common.EventTarget.EventTargetEvent<Bindings.BreakpointManager.BreakpointLocation>): void { if (this.shouldIgnoreExternalBreakpointEvents(event)) { return; } const {breakpoint, uiLocation} = event.data; const uiLocationsForBreakpoint = this.decorationByBreakpoint.get(breakpoint); if (!uiLocationsForBreakpoint) { return; } const decoration = uiLocationsForBreakpoint.get(uiLocation.id()); uiLocationsForBreakpoint.delete(uiLocation.id()); if (uiLocationsForBreakpoint.size === 0) { this.decorationByBreakpoint.delete(breakpoint); } if (!decoration) { return; } const editorLocation = this.transformer.uiLocationToEditorLocation(uiLocation.lineNumber, uiLocation.columnNumber); decoration.breakpoint = null; decoration.enabled = false; const lineDecorations = this.lineBreakpointDecorations(editorLocation.lineNumber); if (!lineDecorations.some(decoration => Boolean(decoration.breakpoint))) { for (const lineDecoration of lineDecorations) { this.breakpointDecorations.delete(lineDecoration); this.updateBreakpointDecoration(lineDecoration); } } else { this.updateBreakpointDecoration(decoration); } } private initializeBreakpoints(): void { const breakpointLocations = this.breakpointManager.breakpointLocationsForUISourceCode(this.uiSourceCode); for (const breakpointLocation of breakpointLocations) { this.addBreakpoint(breakpointLocation.uiLocation, breakpointLocation.breakpoint); } } private updateLinesWithoutMappingHighlight(): void { if (Bindings.CompilerScriptMapping.CompilerScriptMapping.uiSourceCodeOrigin(this.uiSourceCode).length) { const linesCount = this.textEditor.linesCount; for (let i = 0; i < linesCount; ++i) { const lineHasMapping = Bindings.CompilerScriptMapping.CompilerScriptMapping.uiLineHasMapping(this.uiSourceCode, i); if (!lineHasMapping) { this.hasLineWithoutMapping = true; } if (this.hasLineWithoutMapping) { this.textEditor.toggleLineClass(i, 'cm-non-breakable-line', !lineHasMapping); } } return; } const {pluginManager} = Bindings.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance(); if (pluginManager) { pluginManager.getMappedLines(this.uiSourceCode) .then(mappedLines => { if (mappedLines === undefined) { return; } const linesCount = this.textEditor.linesCount; for (let i = 0; i < linesCount; ++i) { const lineHasMapping = mappedLines.has(i); if (!lineHasMapping) { this.hasLineWithoutMapping = true; } if (this.hasLineWithoutMapping) { this.textEditor.toggleLineClass(i, 'cm-non-breakable-line', !lineHasMapping); } } }) .catch(console.error); } } private updateScriptFiles(): void { for (const debuggerModel of SDK.TargetManager.TargetManager.instance().models(SDK.DebuggerModel.DebuggerModel)) { const scriptFile = Bindings.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().scriptFile( this.uiSourceCode, debuggerModel); if (scriptFile) { this.updateScriptFile(debuggerModel); } } } private updateScriptFile(debuggerModel: SDK.DebuggerModel.DebuggerModel): void { const oldScriptFile = this.scriptFileForDebuggerModel.get(debuggerModel); const newScriptFile = Bindings.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().scriptFile( this.uiSourceCode, debuggerModel); this.scriptFileForDebuggerModel.delete(debuggerModel); if (oldScriptFile) { oldScriptFile.removeEventListener( Bindings.ResourceScriptMapping.ResourceScriptFile.Events.DidMergeToVM, this.didMergeToVM, this); oldScriptFile.removeEventListener( Bindings.ResourceScriptMapping.ResourceScriptFile.Events.DidDivergeFromVM, this.didDivergeFromVM, this); if (this.muted && !this.uiSourceCode.isDirty()) { this.restoreBreakpointsIfConsistentScripts(); } } if (!newScriptFile) { return; } this.scriptFileForDebuggerModel.set(debuggerModel, newScriptFile); newScriptFile.addEventListener( Bindings.ResourceScriptMapping.ResourceScriptFile.Events.DidMergeToVM, this.didMergeToVM, this); newScriptFile.addEventListener( Bindings.ResourceScriptMapping.ResourceScriptFile.Events.DidDivergeFromVM, this.didDivergeFromVM, this); newScriptFile.checkMapping(); if (newScriptFile.hasSourceMapURL()) { this.showSourceMapInfobar(); } } private showSourceMapInfobar(): void { if (this.sourceMapInfobar) { return; } this.sourceMapInfobar = UI.Infobar.Infobar.create( UI.Infobar.Type.Info, i18nString(UIStrings.sourceMapDetected), [], Common.Settings.Settings.instance().createSetting('sourceMapInfobarDisabled', false)); if (!this.sourceMapInfobar) { return; } this.sourceMapInfobar.createDetailsRowMessage(i18nString(UIStrings.associatedFilesShouldBeAdded)); this.sourceMapInfobar.createDetailsRowMessage(i18nString(UIStrings.associatedFilesAreAvailable, { PH1: String(UI.ShortcutRegistry.ShortcutRegistry.instance().shortcutTitleForAction('quickOpen.show')), })); this.sourceMapInfobar.setCloseCallback(() => { this.sourceMapInfobar = null; }); this.textEditor.attachInfobar(this.sourceMapInfobar); } private async detectMinified(): Promise<void> { const content = this.uiSourceCode.content(); if (!content || !TextUtils.TextUtils.isMinified(content)) { return; } const editorActions = getRegisteredEditorActions(); let formatterCallback: (() => void)|null = null; for (const editorAction of editorActions) { if (editorAction instanceof ScriptFormatterEditorAction) { // Check if the source code is formattable the same way the pretty print button does if (!editorAction.isCurrentUISourceCodeFormattable()) { return; } formatterCallback = editorAction.toggleFormatScriptSource.bind(editorAction); break; } } this.prettyPrintInfobar = UI.Infobar.Infobar.create( UI.Infobar.Type.Info, i18nString(UIStrings.prettyprintThisMinifiedFile), [{text: i18nString(UIStrings.prettyprint), delegate: formatterCallback, highlight: true, dismiss: true}], Common.Settings.Settings.instance().createSetting('prettyPrintInfobarDisabled', false)); if (!this.prettyPrintInfobar) { return; } this.prettyPrintInfobar.setCloseCallback(() => { this.prettyPrintInfobar = null; }); const toolbar = new UI.Toolbar.Toolbar(''); const button = new UI.Toolbar.ToolbarButton('', 'largeicon-pretty-print'); toolbar.appendToolbarItem(button); toolbar.element.style.display = 'inline-block'; toolbar.element.style.verticalAlign = 'middle'; toolbar.element.style.marginBottom = '3px'; toolbar.element.style.pointerEvents = 'none'; toolbar.element.tabIndex = -1; const element = this.prettyPrintInfobar.createDetailsRowMessage(); element.appendChild( i18n.i18n.getFormatLocalizedString(str_, UIStrings.prettyprintingWillFormatThisFile, {PH1: toolbar.element})); UI.ARIAUtils.markAsAlert(element); this.textEditor.attachInfobar(this.prettyPrintInfobar); } private async handleGutterClick( event: Common.EventTarget.EventTargetEvent<SourceFrame.SourcesTextEditor.GutterClickEventData>): Promise<void> { if (this.muted) { return; } const {gutterType, lineNumber: editorLineNumber, event: eventObject} = event.data; if (gutterType !== SourceFrame.SourcesTextEditor.lineNumbersGutterType) { return; } if (eventObject.button !== 0 || eventObject.altKey || eventObject.ctrlKey || eventObject.metaKey) { return; } await this.toggleBreakpoint(editorLineNumber, eventObject.shiftKey); eventObject.consume(true); } private async toggleBreakpoint(editorLineNumber: number, onlyDisable: boolean): Promise<void> { const decorations = this.lineBreakpointDecorations(editorLineNumber); if (!decorations.length) { await this.createNewBreakpoint(editorLineNumber, '', true); return; } const hasDisabled = this.textEditor.hasLineClass(editorLineNumber, 'cm-breakpoint-disabled'); const breakpoints = (decorations.map(decoration => decoration.breakpoint).filter(breakpoint => Boolean(breakpoint)) as Bindings.BreakpointManager.Breakpoint[]); for (const breakpoint of breakpoints) { if (onlyDisable) { breakpoint.setEnabled(hasDisabled); } else { breakpoint.remove(false); } } } private async createNewBreakpoint(editorLineNumber: number, condition: string, enabled: boolean): Promise<void> { if (this.textEditor.hasLineClass(editorLineNumber, 'cm-non-breakable-line')) { return; } Host.userMetrics.actionTaken(Host.UserMetrics.Action.ScriptsBreakpointSet); const origin = this.transformer.editorLocationToUILocation(editorLineNumber); await this.setBreakpoint(origin.lineNumber, origin.columnNumber, condition, enabled); } private async setBreakpoint(lineNumber: number, columnNumber: number|undefined, condition: string, enabled: boolean): Promise<void> { Common.Settings.Settings.instance().moduleSetting('breakpointsActive').set(true); await this.breakpointManager.setBreakpoint(this.uiSourceCode, lineNumber, columnNumber, condition, enabled); this.breakpointWasSetForTest(lineNumber, columnNumber, condition, enabled); } private breakpointWasSetForTest( _lineNumber: number, _columnNumber: number|undefined, _condition: string, _enabled: boolean): void { } private async callFrameChanged(): Promise<void> { this.liveLocationPool.disposeAll(); const callFrame = UI.Context.Context.instance().flavor(SDK.DebuggerModel.CallFrame); if (!callFrame) { this.clearExecutionLine(); return; } await Bindings.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().createCallFrameLiveLocation( callFrame.location(), this.executionLineChanged.bind(this), this.liveLocationPool); } dispose(): void { for (const decoration of this.breakpointDecorations) { decoration.dispose(); } this.breakpointDecorations.clear(); if (this.scheduledBreakpointDecorationUpdates) { for (const decoration of this.scheduledBreakpointDecorationUpdates) { decoration.dispose(); } this.scheduledBreakpointDecorationUpdates.clear(); } this.hideIgnoreListInfobar(); if (this.sourceMapInfobar) { this.sourceMapInfobar.dispose(); } if (this.prettyPrintInfobar) { this.prettyPrintInfobar.dispose(); } this.scriptsPanel.element.removeEventListener('scroll', this.boundPopoverHelperHide, true); for (const script of this.scriptFileForDebuggerModel.values()) { script.removeEventListener( Bindings.ResourceScriptMapping.ResourceScriptFile.Events.DidMergeToVM, this.didMergeToVM, this); script.removeEventListener( Bindings.ResourceScriptMapping.ResourceScriptFile.Events.DidDivergeFromVM, this.didDivergeFromVM, this); } this.scriptFileForDebuggerModel.clear(); this.textEditor.element.removeEventListener('keydown', this.boundKeyDown, true); this.textEditor.element.removeEventListener('keyup', this.boundKeyUp, true); this.textEditor.element.removeEventListener('mousemove', this.boundMouseMove, false); this.textEditor.element.removeEventListener('mousedown', this.boundMouseDown, true); this.textEditor.element.removeEventListener('focusout', this.boundBlur, false); this.textEditor.element.removeEventListener('wheel', this.boundWheel, true); this.textEditor.removeEventListener(SourceFrame.SourcesTextEditor.Events.GutterClick, this.boundGutterClick, this); this.popoverHelper.hidePopover(); this.popoverHelper.dispose(); this.breakpointManager.removeEventListener( Bindings.BreakpointManager.Events.BreakpointAdded, this.breakpointAdded, this); this.breakpointManager.removeEventListener( Bindings.BreakpointManager.Events.BreakpointRemoved, this.breakpointRemoved, this); this.uiSourceCode.removeEventListener( Workspace.UISourceCode.Events.WorkingCopyChanged, this.workingCopyChanged, this); this.uiSourceCode.removeEventListener( Workspace.UISourceCode.Events.WorkingCopyCommitted, this.workingCopyCommitted, this); Common.Settings.Settings.instance() .moduleSetting('skipStackFramesPattern') .removeChangeListener(this.showIgnoreListInfobarIfNeeded, this); Common.Settings.Settings.instance() .moduleSetting('skipContentScripts') .removeChangeListener(this.showIgnoreListInfobarIfNeeded, this); super.dispose(); this.clearExecutionLine(); UI.Context.Context.instance().removeFlavorChangeListener(SDK.DebuggerModel.CallFrame, this.callFrameChanged, this); this.liveLocationPool.disposeAll(); } } export class BreakpointDecoration { private textEditor: SourceFrame.SourcesTextEditor.SourcesTextEditor; handle: TextEditor.CodeMirrorTextEditor.TextEditorPositionHandle; condition: string; enabled: boolean; bound: boolean; breakpoint: Bindings.BreakpointManager.Breakpoint|null; element: HTMLSpanElement; bookmark: TextEditor.CodeMirrorTextEditor.TextEditorBookMark|null; constructor( textEditor: SourceFrame.SourcesTextEditor.SourcesTextEditor, handle: TextEditor.CodeMirrorTextEditor.TextEditorPositionHandle, condition: string, enabled: boolean, bound: boolean, breakpoint: Bindings.BreakpointManager.Breakpoint|null) { this.textEditor = textEditor; this.handle = handle; this.condition = condition; this.enabled = enabled; this.bound = bound; this.breakpoint = breakpoint; this.element = document.createElement('span'); this.element.classList.toggle('cm-inline-breakpoint', true); this.bookmark = null; } static mostSpecificFirst(decoration1: BreakpointDecoration, decoration2: BreakpointDecoration): number { if (decoration1.enabled !== decoration2.enabled) { return decoration1.enabled ? -1 : 1; } if (decoration1.bound !== decoration2.bound) { return decoration1.bound ? -1 : 1; } if (Boolean(decoration1.condition) !== Boolean(decoration2.condition)) { return Boolean(decoration1.condition) ? -1 : 1; } return 0; } update(): void { const isLogpoint = Boolean(this.condition) && this.condition.includes(LogpointPrefix); const isConditionalBreakpoint = Boolean(this.condition) && !isLogpoint; this.element.classList.toggle('cm-inline-logpoint', isLogpoint); this.element.classList.toggle('cm-inline-breakpoint-conditional', isConditionalBreakpoint); this.element.classList.toggle('cm-inline-disabled', !this.enabled); } show(): void { if (this.bookmark) { return; } const editorLocation = this.handle.resolve(); if (!editorLocation) { return; } this.bookmark = this.textEditor.addBookmark( editorLocation.lineNumber, editorLocation.columnNumber, this.element, BreakpointDecoration.bookmarkSymbol); // @ts-ignore Only used for layout tests this.bookmark[BreakpointDecoration.elementSymbolForTest] = this.element; } hide(): void { if (!this.bookmark) { return; } this.bookmark.clear(); this.bookmark = null; } dispose(): void { const location = this.handle.resolve(); if (location) { this.textEditor.toggleLineClass(location.lineNumber, 'cm-breakpoint', false); this.textEditor.toggleLineClass(location.lineNumber, 'cm-breakpoint-disabled', false); this.textEditor.toggleLineClass(location.lineNumber, 'cm-breakpoint-unbound', false); this.textEditor.toggleLineClass(location.lineNumber, 'cm-breakpoint-conditional', false); this.textEditor.toggleLineClass(location.lineNumber, 'cm-breakpoint-logpoint', false); } this.hide(); } // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/naming-convention static readonly bookmarkSymbol = Symbol('bookmark'); // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/naming-convention private static readonly elementSymbolForTest = Symbol('element'); } export const continueToLocationDecorationSymbol = Symbol('bookmark');
the_stack
import * as React from 'react'; import { IPropertyFieldDimensionPickerPropsInternal, IPropertyFieldDimension } from './PropertyFieldDimensionPicker'; import { Label } from 'office-ui-fabric-react/lib/Label'; import { Dropdown, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown'; import { Async } from 'office-ui-fabric-react/lib/Utilities'; import { Checkbox } from 'office-ui-fabric-react/lib/Checkbox'; import { TextField } from 'office-ui-fabric-react/lib/TextField'; import GuidHelper from './GuidHelper'; import * as strings from 'sp-client-custom-fields/strings'; /** * @interface * PropertyFieldDimensionPickerHost properties interface * */ export interface IPropertyFieldDimensionPickerHostProps extends IPropertyFieldDimensionPickerPropsInternal { } export interface IPropertyFieldDimensionPickerState { width?: number; height?: number; widthUnit?: string; heightUnit?: string; conserveRatio?: boolean; errorMessage: string; } /** * @class * Renders the controls for PropertyFieldDimensionPicker component */ export default class PropertyFieldDimensionPickerHost extends React.Component<IPropertyFieldDimensionPickerHostProps, IPropertyFieldDimensionPickerState> { private async: Async; private delayedValidate: (value: IPropertyFieldDimension) => void; private _key: string; private units: IDropdownOption[] = [ { key: 'px', text: 'px'}, { key: '%', text: '%'} ]; /** * @function * Constructor */ constructor(props: IPropertyFieldDimensionPickerHostProps) { super(props); this._key = GuidHelper.getGuid(); this.async = new Async(this); this.state = ({ errorMessage: '', width: 0, height: 0, widthUnit: 'px', heightUnit: 'px', conserveRatio: this.props.preserveRatio } as IPropertyFieldDimensionPickerState); this.loadDefaultData(); //Bind the current object to the external called onSelectDate method this.onWidthChanged = this.onWidthChanged.bind(this); this.onHeightChanged = this.onHeightChanged.bind(this); this.onWidthUnitChanged = this.onWidthUnitChanged.bind(this); this.onHeightUnitChanged = this.onHeightUnitChanged.bind(this); this.onRatioChanged = this.onRatioChanged.bind(this); this.saveDimension = this.saveDimension.bind(this); this.validate = this.validate.bind(this); this.notifyAfterValidate = this.notifyAfterValidate.bind(this); this.delayedValidate = this.async.debounce(this.validate, this.props.deferredValidationTime); } /** * @function * Function called to load data from the initialValue */ private loadDefaultData(): void { if (this.props.initialValue != null && this.props.initialValue !== undefined) { if (this.props.initialValue.width != null && this.props.initialValue.width !== undefined) { if (this.props.initialValue.width.indexOf('px') > -1) { this.state.widthUnit = 'px'; this.state.width = Math.round(+this.props.initialValue.width.replace('px', '')); } else if (this.props.initialValue.height.indexOf('%') > -1) { this.state.widthUnit = '%'; this.state.width = Math.round(+this.props.initialValue.width.replace('%', '')); } } if (this.props.initialValue.height != null && this.props.initialValue.height !== undefined) { if (this.props.initialValue.height.indexOf('px') > -1) { this.state.heightUnit = 'px'; this.state.height = Math.round(+this.props.initialValue.height.replace('px', '')); } else if (this.props.initialValue.height.indexOf('%') > -1) { this.state.heightUnit = '%'; this.state.height = Math.round(+this.props.initialValue.height.replace('%', '')); } } } } /** * @function * Function called when the width changed */ private onWidthChanged(newValue: any): void { if (this.state.widthUnit === this.state.heightUnit && this.state.conserveRatio === true && this.props.preserveRatioEnabled === true) { if (this.state.width != 0) this.state.height = Math.round((this.state.height / this.state.width) * +newValue); } this.state.width = Math.round(+newValue); this.setState(this.state); this.saveDimension(); } /** * @function * Function called when the height changed */ private onHeightChanged(newValue: any): void { if (this.state.widthUnit === this.state.heightUnit && this.state.conserveRatio === true && this.props.preserveRatioEnabled === true) { if (this.state.height != 0) this.state.width = Math.round((this.state.width / this.state.height) * +newValue); } this.state.height = Math.round(+newValue); this.setState(this.state); this.saveDimension(); } /** * @function * Function called when the width unit changed */ private onWidthUnitChanged(element?: IDropdownOption): void { if (element != null) { var newValue: string = element.key.toString(); this.state.widthUnit = newValue; this.setState(this.state); this.saveDimension(); } } /** * @function * Function called when the height unit changed */ private onHeightUnitChanged(element?: IDropdownOption): void { if (element != null) { var newValue: string = element.key.toString(); this.state.heightUnit = newValue; this.setState(this.state); this.saveDimension(); } } /** * @function * Function called when the ratio changed */ private onRatioChanged(element: any, isChecked: boolean): void { if (element) { this.state.conserveRatio = isChecked; this.setState(this.state); } } /** * @function * Saves the dimension */ private saveDimension(): void { var dimension: IPropertyFieldDimension = { width: this.state.width + this.state.widthUnit, height: this.state.height + this.state.heightUnit }; this.delayedValidate(dimension); } /** * @function * Validates the new custom field value */ private validate(value: IPropertyFieldDimension): void { if (this.props.onGetErrorMessage === null || this.props.onGetErrorMessage === undefined) { this.notifyAfterValidate(this.props.initialValue, value); return; } var result: string | PromiseLike<string> = this.props.onGetErrorMessage(value || ''); if (result !== undefined) { if (typeof result === 'string') { if (result === undefined || result === '') this.notifyAfterValidate(this.props.initialValue, value); this.setState({ errorMessage: result} as IPropertyFieldDimensionPickerState); } else { result.then((errorMessage: string) => { if (errorMessage === undefined || errorMessage === '') this.notifyAfterValidate(this.props.initialValue, value); this.setState({ errorMessage } as IPropertyFieldDimensionPickerState); }); } } else { this.notifyAfterValidate(this.props.initialValue, value); } } /** * @function * Notifies the parent Web Part of a property value change */ private notifyAfterValidate(oldValue: IPropertyFieldDimension, newValue: IPropertyFieldDimension) { this.props.properties[this.props.targetProperty] = newValue; this.props.onPropertyChange(this.props.targetProperty, oldValue, newValue); if (!this.props.disableReactivePropertyChanges && this.props.render != null) this.props.render(); } /** * @function * Called when the component will unmount */ public componentWillUnmount() { if (this.async != null) this.async.dispose(); } /** * @function * Renders the controls */ public render(): JSX.Element { //Renders content return ( <div style={{ marginBottom: '8px'}}> <Label>{this.props.label}</Label> <table style={{paddingTop: '10px'}}> <tbody> <tr> <td style={{verticalAlign: 'top', minWidth: '55px'}}> <Label disabled={this.props.disabled}>{strings.DimensionWidth}</Label> </td> <td style={{verticalAlign: 'top', width: '80px'}}> <TextField disabled={this.props.disabled} role="textbox" aria-multiline="false" type="number" min='0' value={this.state.width !== undefined ? this.state.width.toString():''} onChanged={this.onWidthChanged} /> </td> <td style={{verticalAlign: 'top'}}> <Dropdown label="" options={this.units} selectedKey={this.state.widthUnit} disabled={this.props.disabled} onChanged={this.onWidthUnitChanged} /> </td> </tr> <tr> <td style={{verticalAlign: 'top', minWidth: '55px'}}> <Label disabled={this.props.disabled}>{strings.DimensionHeight}</Label> </td> <td style={{verticalAlign: 'top', width: '80px'}}> <TextField disabled={this.props.disabled} role="textbox" aria-multiline="false" type="number" min='0' value={this.state.height !== undefined ? this.state.height.toString():''} onChanged={this.onHeightChanged} /> </td> <td style={{verticalAlign: 'top'}}> <Dropdown label="" options={this.units} selectedKey={this.state.heightUnit} disabled={this.props.disabled} onChanged={this.onHeightUnitChanged} /> </td> </tr> { this.props.preserveRatioEnabled === true ? <tr> <td></td> <td colSpan={2}> <div className="ms-ChoiceField" style={{paddingLeft: '0px'}}> <Checkbox checked={this.state.conserveRatio} disabled={this.props.disabled} label={strings.DimensionRatio} onChange={this.onRatioChanged} /> </div> </td> </tr> : ''} </tbody> </table> { this.state.errorMessage != null && this.state.errorMessage != '' && this.state.errorMessage != undefined ? <div><div aria-live='assertive' className='ms-u-screenReaderOnly' data-automation-id='error-message'>{ this.state.errorMessage }</div> <span> <p className='ms-TextField-errorMessage ms-u-slideDownIn20'>{ this.state.errorMessage }</p> </span> </div> : ''} </div> ); } }
the_stack
import { ParsedFailedJobPayload, Job, Queue, Worker, Plugin } from "../../src"; import specHelper from "../utils/specHelper"; class MyPlugin extends Plugin { async beforeEnqueue() { return true; } async afterEnqueue() { return true; } async beforePerform() { return true; } async afterPerform() { this.options.afterPerform(this); return true; } } const jobs: { [key: string]: Job<any> } = { add: { perform: (a, b) => { return a + b; }, } as Job<any>, //@ts-ignore badAdd: { perform: () => { throw new Error("Blue Smoke"); }, } as Job<any>, messWithData: { perform: (a) => { a.data = "new thing"; return a; }, } as Job<any>, async: { perform: async () => { await new Promise((resolve) => { setTimeout(resolve, 100); }); return "yay"; }, } as Job<any>, twoSeconds: { perform: async () => { await new Promise((resolve) => { setTimeout(resolve, 1000 * 2); }); return "slow"; }, } as Job<any>, //@ts-ignore quickDefine: async () => { return "ok"; }, }; let worker: Worker; let queue: Queue; describe("worker", () => { afterAll(async () => { await specHelper.disconnect(); }); test("can connect", async () => { const worker = new Worker( { connection: specHelper.connectionDetails, queues: [specHelper.queue] }, {} ); await worker.connect(); await worker.end(); }); describe("performInline", () => { beforeAll(() => { worker = new Worker( { connection: specHelper.connectionDetails, timeout: specHelper.timeout, queues: [specHelper.queue], }, jobs ); }); test("can run a successful job", async () => { const result = await worker.performInline("add", [1, 2]); expect(result).toBe(3); }); test("can run a successful async job", async () => { const result = await worker.performInline("async"); expect(result).toBe("yay"); }); test("can run a failing job", async () => { try { await worker.performInline("badAdd", [1, 2]); throw new Error("should not get here"); } catch (error) { expect(String(error)).toBe("Error: Blue Smoke"); } }); test("can call a Plugin's afterPerform given the job throws an error", async () => { let actual = null; let expected = new TypeError("John"); let failingJob = { plugins: [MyPlugin], pluginOptions: { MyPlugin: { afterPerform: (plugin: Plugin) => { actual = plugin.worker.error; delete plugin.worker.error; }, }, }, perform: (x: string) => { throw new TypeError(x); }, }; let worker = new Worker({}, { failingJob }); await worker.performInline("failingJob", ["John"]); expect(actual).toEqual(expected); }); }); describe("[with connection]", () => { beforeAll(async () => { await specHelper.connect(); queue = new Queue({ connection: specHelper.connectionDetails }, {}); await queue.connect(); }); afterAll(async () => { await specHelper.cleanup(); }); test("can boot and stop", async () => { worker = new Worker( { connection: specHelper.connectionDetails, timeout: specHelper.timeout, queues: [specHelper.queue], }, jobs ); await worker.connect(); await worker.start(); await worker.end(); }); test("will determine the proper queue names", async () => { const worker = new Worker( { connection: specHelper.connectionDetails, timeout: specHelper.timeout, }, jobs ); await worker.connect(); expect(worker.queues).toEqual([]); await queue.enqueue(specHelper.queue, "badAdd", [1, 2]); await worker.checkQueues(); expect(worker.queues).toEqual([specHelper.queue]); //@ts-ignore await queue.del(specHelper.queue); await worker.end(); }); describe("integration", () => { test("will notice new job queues when started with queues=*", async () => { await new Promise(async (resolve) => { const wildcardWorker = new Worker( { connection: specHelper.connectionDetails, timeout: specHelper.timeout, queues: ["*"], }, jobs ); await wildcardWorker.connect(); await wildcardWorker.start(); setTimeout(async () => { await queue.enqueue("__newQueue", "add", [1, 2]); }, 501); wildcardWorker.on("success", async (q, job, result, duration) => { expect(q).toBe("__newQueue"); expect(job.class).toBe("add"); expect(result).toBe(3); expect(wildcardWorker.result).toBe(result); expect(duration).toBeGreaterThanOrEqual(0); wildcardWorker.removeAllListeners("success"); await wildcardWorker.end(); resolve(null); }); }); }); describe("with worker", () => { beforeEach(async () => { worker = new Worker( { connection: specHelper.connectionDetails, timeout: specHelper.timeout, queues: [specHelper.queue], }, jobs ); await worker.connect(); }); afterEach(async () => { await worker.end(); }); test("will mark a job as failed", async () => { await new Promise(async (resolve) => { await queue.enqueue(specHelper.queue, "badAdd", [1, 2]); await worker.start(); worker.on("failure", (q, job, failire) => { expect(q).toBe(specHelper.queue); expect(job.class).toBe("badAdd"); expect(failire.message).toBe("Blue Smoke"); worker.removeAllListeners("failure"); resolve(null); }); }); }); test("can work a job and return successful things", async () => { await new Promise(async (resolve) => { await queue.enqueue(specHelper.queue, "add", [1, 2]); worker.start(); worker.on("success", (q, job, result, duration) => { expect(q).toBe(specHelper.queue); expect(job.class).toBe("add"); expect(result).toBe(3); expect(worker.result).toBe(result); expect(duration).toBeGreaterThanOrEqual(0); worker.removeAllListeners("success"); resolve(null); }); }); }); // TODO: Typescript seems to have trouble with frozen objects // test('job arguments are immutable', async (done) => { // await queue.enqueue(specHelper.queue, 'messWithData', { a: 'starting value' }) // worker.start() // worker.on('success', (q, job, result) => { // expect(result.a).toBe('starting value') // expect(worker.result).toBe(result) // worker.removeAllListeners('success') // done() // }) // }) test("can accept jobs that are simple functions", async () => { await new Promise(async (resolve) => { await queue.enqueue(specHelper.queue, "quickDefine"); worker.start(); worker.on("success", (q, job, result, duration) => { expect(result).toBe("ok"); expect(duration).toBeGreaterThanOrEqual(0); worker.removeAllListeners("success"); resolve(null); }); }); }); test("will not work jobs that are not defined", async () => { await new Promise(async (resolve) => { await queue.enqueue(specHelper.queue, "somethingFake"); worker.start(); worker.on("failure", (q, job, failure, duration) => { expect(q).toBe(specHelper.queue); expect(String(failure)).toBe( 'Error: No job defined for class "somethingFake"' ); expect(duration).toBeGreaterThanOrEqual(0); worker.removeAllListeners("failure"); resolve(null); }); }); }); test("will place failed jobs in the failed queue", async () => { let str = await specHelper.redis.rpop( specHelper.namespace + ":" + "failed" ); const data = JSON.parse(str) as ParsedFailedJobPayload; expect(data.queue).toBe(specHelper.queue); expect(data.exception).toBe("Error"); expect(data.error).toBe('No job defined for class "somethingFake"'); }); test("will ping with status even when working a slow job", async () => { await new Promise(async (resolve) => { const nowInSeconds = Math.round(new Date().getTime() / 1000); await worker.start(); await new Promise((resolve) => setTimeout(resolve, worker.options.timeout * 2) ); const pingKey = worker.connection.key( "worker", "ping", worker.name ); const firstPayload = JSON.parse( await specHelper.redis.get(pingKey) ); expect(firstPayload.name).toEqual(worker.name); expect(firstPayload.time).toBeGreaterThanOrEqual(nowInSeconds); await queue.enqueue(specHelper.queue, "twoSeconds"); worker.on("success", (q, job, result) => { expect(result).toBe("slow"); worker.removeAllListeners("success"); resolve(null); }); const secondPayload = JSON.parse( await specHelper.redis.get(pingKey) ); expect(secondPayload.name).toEqual(worker.name); expect(secondPayload.time).toBeGreaterThanOrEqual( firstPayload.time ); }); }); }); }); }); });
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * Manages an RDS Aurora Cluster Endpoint. * You can refer to the [User Guide](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Overview.Endpoints.html#Aurora.Endpoints.Cluster). * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const _default = new aws.rds.Cluster("default", { * clusterIdentifier: "aurora-cluster-demo", * availabilityZones: [ * "us-west-2a", * "us-west-2b", * "us-west-2c", * ], * databaseName: "mydb", * masterUsername: "foo", * masterPassword: "bar", * backupRetentionPeriod: 5, * preferredBackupWindow: "07:00-09:00", * }); * const test1 = new aws.rds.ClusterInstance("test1", { * applyImmediately: true, * clusterIdentifier: _default.id, * identifier: "test1", * instanceClass: "db.t2.small", * engine: _default.engine, * engineVersion: _default.engineVersion, * }); * const test2 = new aws.rds.ClusterInstance("test2", { * applyImmediately: true, * clusterIdentifier: _default.id, * identifier: "test2", * instanceClass: "db.t2.small", * engine: _default.engine, * engineVersion: _default.engineVersion, * }); * const test3 = new aws.rds.ClusterInstance("test3", { * applyImmediately: true, * clusterIdentifier: _default.id, * identifier: "test3", * instanceClass: "db.t2.small", * engine: _default.engine, * engineVersion: _default.engineVersion, * }); * const eligible = new aws.rds.ClusterEndpoint("eligible", { * clusterIdentifier: _default.id, * clusterEndpointIdentifier: "reader", * customEndpointType: "READER", * excludedMembers: [ * test1.id, * test2.id, * ], * }); * const static = new aws.rds.ClusterEndpoint("static", { * clusterIdentifier: _default.id, * clusterEndpointIdentifier: "static", * customEndpointType: "READER", * staticMembers: [ * test1.id, * test3.id, * ], * }); * ``` * * ## Import * * RDS Clusters Endpoint can be imported using the `cluster_endpoint_identifier`, e.g. * * ```sh * $ pulumi import aws:rds/clusterEndpoint:ClusterEndpoint custom_reader aurora-prod-cluster-custom-reader * ``` * * [1]https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Overview.Endpoints.html#Aurora.Endpoints.Cluster */ export class ClusterEndpoint extends pulumi.CustomResource { /** * Get an existing ClusterEndpoint resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ClusterEndpointState, opts?: pulumi.CustomResourceOptions): ClusterEndpoint { return new ClusterEndpoint(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'aws:rds/clusterEndpoint:ClusterEndpoint'; /** * Returns true if the given object is an instance of ClusterEndpoint. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is ClusterEndpoint { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === ClusterEndpoint.__pulumiType; } /** * Amazon Resource Name (ARN) of cluster */ public /*out*/ readonly arn!: pulumi.Output<string>; /** * The identifier to use for the new endpoint. This parameter is stored as a lowercase string. */ public readonly clusterEndpointIdentifier!: pulumi.Output<string>; /** * The cluster identifier. */ public readonly clusterIdentifier!: pulumi.Output<string>; /** * The type of the endpoint. One of: READER , ANY . */ public readonly customEndpointType!: pulumi.Output<string>; /** * A custom endpoint for the Aurora cluster */ public /*out*/ readonly endpoint!: pulumi.Output<string>; /** * List of DB instance identifiers that aren't part of the custom endpoint group. All other eligible instances are reachable through the custom endpoint. Only relevant if the list of static members is empty. Conflicts with `staticMembers`. */ public readonly excludedMembers!: pulumi.Output<string[] | undefined>; /** * List of DB instance identifiers that are part of the custom endpoint group. Conflicts with `excludedMembers`. */ public readonly staticMembers!: pulumi.Output<string[] | undefined>; /** * Key-value map of resource tags. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * A map of tags assigned to the resource, including those inherited from the provider . */ public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>; /** * Create a ClusterEndpoint resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: ClusterEndpointArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: ClusterEndpointArgs | ClusterEndpointState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as ClusterEndpointState | undefined; inputs["arn"] = state ? state.arn : undefined; inputs["clusterEndpointIdentifier"] = state ? state.clusterEndpointIdentifier : undefined; inputs["clusterIdentifier"] = state ? state.clusterIdentifier : undefined; inputs["customEndpointType"] = state ? state.customEndpointType : undefined; inputs["endpoint"] = state ? state.endpoint : undefined; inputs["excludedMembers"] = state ? state.excludedMembers : undefined; inputs["staticMembers"] = state ? state.staticMembers : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["tagsAll"] = state ? state.tagsAll : undefined; } else { const args = argsOrState as ClusterEndpointArgs | undefined; if ((!args || args.clusterEndpointIdentifier === undefined) && !opts.urn) { throw new Error("Missing required property 'clusterEndpointIdentifier'"); } if ((!args || args.clusterIdentifier === undefined) && !opts.urn) { throw new Error("Missing required property 'clusterIdentifier'"); } if ((!args || args.customEndpointType === undefined) && !opts.urn) { throw new Error("Missing required property 'customEndpointType'"); } inputs["clusterEndpointIdentifier"] = args ? args.clusterEndpointIdentifier : undefined; inputs["clusterIdentifier"] = args ? args.clusterIdentifier : undefined; inputs["customEndpointType"] = args ? args.customEndpointType : undefined; inputs["excludedMembers"] = args ? args.excludedMembers : undefined; inputs["staticMembers"] = args ? args.staticMembers : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["arn"] = undefined /*out*/; inputs["endpoint"] = undefined /*out*/; inputs["tagsAll"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(ClusterEndpoint.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering ClusterEndpoint resources. */ export interface ClusterEndpointState { /** * Amazon Resource Name (ARN) of cluster */ arn?: pulumi.Input<string>; /** * The identifier to use for the new endpoint. This parameter is stored as a lowercase string. */ clusterEndpointIdentifier?: pulumi.Input<string>; /** * The cluster identifier. */ clusterIdentifier?: pulumi.Input<string>; /** * The type of the endpoint. One of: READER , ANY . */ customEndpointType?: pulumi.Input<string>; /** * A custom endpoint for the Aurora cluster */ endpoint?: pulumi.Input<string>; /** * List of DB instance identifiers that aren't part of the custom endpoint group. All other eligible instances are reachable through the custom endpoint. Only relevant if the list of static members is empty. Conflicts with `staticMembers`. */ excludedMembers?: pulumi.Input<pulumi.Input<string>[]>; /** * List of DB instance identifiers that are part of the custom endpoint group. Conflicts with `excludedMembers`. */ staticMembers?: pulumi.Input<pulumi.Input<string>[]>; /** * Key-value map of resource tags. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * A map of tags assigned to the resource, including those inherited from the provider . */ tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; } /** * The set of arguments for constructing a ClusterEndpoint resource. */ export interface ClusterEndpointArgs { /** * The identifier to use for the new endpoint. This parameter is stored as a lowercase string. */ clusterEndpointIdentifier: pulumi.Input<string>; /** * The cluster identifier. */ clusterIdentifier: pulumi.Input<string>; /** * The type of the endpoint. One of: READER , ANY . */ customEndpointType: pulumi.Input<string>; /** * List of DB instance identifiers that aren't part of the custom endpoint group. All other eligible instances are reachable through the custom endpoint. Only relevant if the list of static members is empty. Conflicts with `staticMembers`. */ excludedMembers?: pulumi.Input<pulumi.Input<string>[]>; /** * List of DB instance identifiers that are part of the custom endpoint group. Conflicts with `excludedMembers`. */ staticMembers?: pulumi.Input<pulumi.Input<string>[]>; /** * Key-value map of resource tags. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; }
the_stack
import "../../Operator" import type * as C from "../../Cause" import * as Chunk from "../../Collections/Immutable/Chunk" import * as Map from "../../Collections/Immutable/Map" import * as Tp from "../../Collections/Immutable/Tuple" import * as Ex from "../../Exit" import type { Predicate, Refinement } from "../../Function" import { not, pipe, tuple } from "../../Function" import type { Finalizer } from "../../Managed/ReleaseMap" import * as O from "../../Option" import * as RM from "../../RefM" import * as T from "../_internal/effect" import * as M from "../_internal/managed" import * as R from "../_internal/ref" // Contract notes for transducers: // - When a None is received, the transducer must flush all of its internal state // and remain empty until subsequent Some(Chunk) values. // // Stated differently, after a first push(None), all subsequent push(None) must // result in empty []. export class Transducer<R, E, I, O> { constructor( readonly push: M.Managed< R, never, (c: O.Option<Chunk.Chunk<I>>) => T.Effect<R, E, Chunk.Chunk<O>> > ) {} } /** * Contract notes for transducers: * - When a None is received, the transducer must flush all of its internal state * and remain empty until subsequent Some(Chunk) values. * * Stated differently, after a first push(None), all subsequent push(None) must * result in empty []. */ export const transducer = <R, E, I, O, R1>( push: M.Managed< R, never, (c: O.Option<Chunk.Chunk<I>>) => T.Effect<R1, E, Chunk.Chunk<O>> > ) => new Transducer<R & R1, E, I, O>(push) /** * Compose this transducer with another transducer, resulting in a composite transducer. */ export const then = <R1, E1, O, O1>(that: Transducer<R1, E1, O, O1>) => <R, E, I>(self: Transducer<R, E, I, O>): Transducer<R & R1, E1 | E, I, O1> => transducer( pipe( self.push, M.zipWith(that.push, (pushLeft, pushRight) => O.fold( () => pipe( pushLeft(O.none), T.chain((cl) => Chunk.isEmpty(cl) ? pushRight(O.none) : pipe( pushRight(O.some(cl)), T.zipWith(pushRight(O.none), Chunk.concat_) ) ) ), (inputs) => pipe( pushLeft(O.some(inputs)), T.chain((cl) => pushRight(O.some(cl))) ) ) ) ) ) /** * Transforms the outputs of this transducer. */ export function map_<R, E, I, O, O1>( fa: Transducer<R, E, I, O>, f: (o: O) => O1 ): Transducer<R, E, I, O1> { return new Transducer( M.map_(fa.push, (push) => (input) => T.map_(push(input), Chunk.map(f))) ) } /** * Transforms the outputs of this transducer. */ export function map<O, P>( f: (o: O) => P ): <R, E, I>(fa: Transducer<R, E, I, O>) => Transducer<R, E, I, P> { return (fa) => map_(fa, f) } /** * Transforms the chunks emitted by this transducer. */ export function mapChunks_<R, E, I, O, O1>( fa: Transducer<R, E, I, O>, f: (chunks: Chunk.Chunk<O>) => Chunk.Chunk<O1> ): Transducer<R, E, I, O1> { return new Transducer(M.map_(fa.push, (push) => (input) => T.map_(push(input), f))) } /** * Transforms the chunks emitted by this transducer. */ export function mapChunks<O, O1>( f: (chunks: Chunk.Chunk<O>) => Chunk.Chunk<O1> ): <R, E, I>(fa: Transducer<R, E, I, O>) => Transducer<R, E, I, O1> { return (fa) => mapChunks_(fa, f) } /** * Effectfully transforms the chunks emitted by this transducer. */ export function mapChunksM_<R, E, I, O, R1, E1, O1>( fa: Transducer<R, E, I, O>, f: (chunk: Chunk.Chunk<O>) => T.Effect<R1, E1, Chunk.Chunk<O1>> ): Transducer<R & R1, E | E1, I, O1> { return new Transducer(M.map_(fa.push, (push) => (input) => T.chain_(push(input), f))) } /** * Effectfully transforms the chunks emitted by this transducer. */ export function mapChunksM<O, R1, E1, O1>( f: (chunk: Chunk.Chunk<O>) => T.Effect<R1, E1, Chunk.Chunk<O1>> ): <R, E, I>(fa: Transducer<R, E, I, O>) => Transducer<R & R1, E | E1, I, O1> { return (fa) => mapChunksM_(fa, f) } /** * Effectually transforms the outputs of this transducer */ export function mapM_<R, E, I, O, R1, E1, O1>( fa: Transducer<R, E, I, O>, f: (o: O) => T.Effect<R1, E1, O1> ): Transducer<R & R1, E | E1, I, O1> { return new Transducer( M.map_(fa.push, (push) => (input) => T.chain_(push(input), Chunk.mapM(f))) ) } /** * Effectually transforms the outputs of this transducer */ export function mapM<O, R1, E1, O1>( f: (o: O) => T.Effect<R1, E1, O1> ): <R, E, I>(fa: Transducer<R, E, I, O>) => Transducer<R & R1, E | E1, I, O1> { return (fa) => mapM_(fa, f) } /** * Transforms the errors of this transducer. */ export function mapError_<R, E, I, O, E1>( pab: Transducer<R, E, I, O>, f: (e: E) => E1 ): Transducer<R, E1, I, O> { return new Transducer(M.map_(pab.push, (push) => (is) => T.mapError_(push(is), f))) } /** * Transforms the errors of this transducer. */ export function mapError<E, E1>( f: (e: E) => E1 ): <R, I, O>(pab: Transducer<R, E, I, O>) => Transducer<R, E1, I, O> { return (pab) => mapError_(pab, f) } /** * Creates a transducer that always fails with the specified failure. */ export function fail<E>(e: E): Transducer<unknown, E, unknown, never> { return new Transducer(M.succeed((_) => T.fail(e))) } /** * Creates a transducer that always dies with the specified exception. */ export function die(error: unknown): Transducer<unknown, never, unknown, never> { return new Transducer(M.succeed((_) => T.die(error))) } /** * Creates a transducer that always fails with the specified cause. */ export function halt<E>(c: C.Cause<E>): Transducer<unknown, E, unknown, never> { return new Transducer(M.succeed((_) => T.halt(c))) } /** * The identity transducer. Passes elements through. */ export function identity<I>(): Transducer<unknown, never, I, I> { return fromPush(O.fold(() => T.succeed(Chunk.empty()), T.succeed)) } /** * Creates a transducer from a chunk processing function. */ export function fromPush<R, E, I, O>( push: (input: O.Option<Chunk.Chunk<I>>) => T.Effect<R, E, Chunk.Chunk<O>> ): Transducer<R, E, I, O> { return new Transducer(M.succeed(push)) } /** * Creates a transducer that always evaluates the specified effect. */ export function fromEffect<R, E, A>( task: T.Effect<R, E, A> ): Transducer<R, E, unknown, A> { return new Transducer(M.succeed((_: any) => T.map_(task, Chunk.single))) } /** * Creates a transducer that purely transforms incoming values. */ export function fromFunction<I, O>(f: (i: I) => O): Transducer<unknown, never, I, O> { return map_(identity(), f) } /** * Creates a transducer that effectfully transforms incoming values. */ export function fromFunctionM<R, E, I, O>( f: (i: I) => T.Effect<R, E, O> ): Transducer<R, E, I, O> { return mapM_(identity(), f) } /** * Creates a transducer that returns the first element of the stream, if it exists. */ export function head<O>(): Transducer<unknown, never, O, O.Option<O>> { return foldLeft(O.none as O.Option<O>, (acc, o) => O.fold_( acc, () => O.some(o), () => acc ) ) } /** * Creates a transducer that returns the last element of the stream, if it exists. */ export function last<O>(): Transducer<unknown, never, O, O.Option<O>> { return foldLeft(O.none as O.Option<O>, (_, o) => O.some(o)) } /** * Emits the provided chunk before emitting any other value. */ export function prepend<O>(values: Chunk.Chunk<O>): Transducer<unknown, never, O, O> { return new Transducer( M.map_( R.makeManagedRef(values), (state) => (is: O.Option<Chunk.Chunk<O>>) => O.fold_( is, () => R.getAndSet_(state, Chunk.empty()), (os) => pipe( state, R.getAndSet(Chunk.empty()), T.map((c) => (Chunk.isEmpty(c) ? os : Chunk.concat_(c, os))) ) ) ) ) } /** * Reads the first n values from the stream and uses them to choose the transducer that will be used for the remainder of the stream. * If the stream ends before it has collected n values the partial chunk will be provided to f. */ export function branchAfter<R, E, I, O>( n: number, f: (c: Chunk.Chunk<I>) => Transducer<R, E, I, O> ): Transducer<R, E, I, O> { interface Collecting { _tag: "Collecting" data: Chunk.Chunk<I> } interface Emitting { _tag: "Emitting" finalizer: Finalizer push: (is: O.Option<Chunk.Chunk<I>>) => T.Effect<R, E, Chunk.Chunk<O>> } type State = Collecting | Emitting const initialState: State = { _tag: "Collecting", data: Chunk.empty() } const toCollect = Math.max(0, n) return new Transducer( M.chain_(M.scope, (allocate) => M.map_( RM.makeManagedRefM<State>(initialState), (state) => (is: O.Option<Chunk.Chunk<I>>) => O.fold_( is, () => pipe( RM.getAndSet_(state, initialState), T.chain((s) => { switch (s._tag) { case "Collecting": { return M.use_(f(s.data).push, (f) => f(O.none)) } case "Emitting": { return T.zipLeft_(s.push(O.none), s.finalizer(Ex.unit)) } } }) ), (data) => RM.modify_(state, (s) => { switch (s._tag) { case "Emitting": { return T.map_(s.push(O.some(data)), (_) => Tp.tuple(_, s)) } case "Collecting": { if (Chunk.isEmpty(data)) { return T.succeed(Tp.tuple(Chunk.empty<O>(), s)) } else { const remaining = toCollect - Chunk.size(s.data) if (remaining <= Chunk.size(data)) { const { tuple: [newCollected, remainder] } = Chunk.splitAt_(data, remaining) return T.chain_( allocate(f(Chunk.concat_(s.data, newCollected)).push), ({ tuple: [finalizer, push] }) => T.map_(push(O.some(remainder)), (_) => Tp.tuple<[Chunk.Chunk<O>, State]>(_, { _tag: "Emitting", finalizer, push }) ) ) } else { return T.succeed( Tp.tuple<[Chunk.Chunk<O>, State]>(Chunk.empty(), { _tag: "Collecting", data: Chunk.concat_(s.data, data) }) ) } } } } }) ) ) ) ) } /** * Creates a transducer that starts consuming values as soon as one fails * the predicate `p`. */ export function dropWhile<I>( predicate: Predicate<I> ): Transducer<unknown, never, I, I> { return new Transducer( M.map_( R.makeManagedRef(true), (dropping) => (is: O.Option<Chunk.Chunk<I>>) => O.fold_( is, () => T.succeed(Chunk.empty()), (is) => R.modify_(dropping, (b) => { switch (b) { case true: { const is1 = Chunk.dropWhile_(is, predicate) return Tp.tuple(is1, Chunk.isEmpty(is1)) } case false: { return Tp.tuple(is, false) } } }) ) ) ) } /** * Creates a transducer that starts consuming values as soon as one fails * the effectful predicate `p`. */ export function dropWhileM<R, E, I>( p: (i: I) => T.Effect<R, E, boolean> ): Transducer<R, E, I, I> { return new Transducer( pipe( M.do, M.bind("dropping", () => R.makeManagedRef(true)), M.let( "push", ({ dropping }) => (is: O.Option<Chunk.Chunk<I>>) => O.fold_( is, () => T.succeed(Chunk.empty<I>()), (is) => pipe( dropping.get, T.chain((b) => b ? T.map_( Chunk.dropWhileM_(is, p), (l: Chunk.Chunk<I>) => [l, Chunk.isEmpty(l)] as const ) : T.succeed([is, false] as const) ), T.chain(([is, pt]) => T.as_(dropping.set(pt), is)) ) ) ), M.map(({ push }) => push) ) ) } function foldGo<I, O>( in_: Chunk.Chunk<I>, state: O, progress: boolean, initial: O, contFn: (o: O) => boolean, f: (output: O, input: I) => O ): readonly [Chunk.Chunk<O>, O, boolean] { return Chunk.reduce_( in_, [Chunk.empty<O>(), state, progress] as const, ([os0, state, _], i) => { const o = f(state, i) if (contFn(o)) { return [os0, o, true] as const } else { return [Chunk.append_(os0, o), initial, false] as const } } ) } /** * Creates a transducer by folding over a structure of type `O` for as long as * `contFn` results in `true`. The transducer will emit a value when `contFn` * evaluates to `false` and then restart the folding. */ export function fold<I, O>( initial: O, contFn: (o: O) => boolean, f: (output: O, input: I) => O ): Transducer<unknown, never, I, O> { return new Transducer( M.map_( R.makeManagedRef(O.some(initial)), (state) => (is: O.Option<Chunk.Chunk<I>>) => O.fold_( is, () => pipe( R.getAndSet_(state, O.none), T.map(O.fold(() => Chunk.empty(), Chunk.single)) ), (in_) => R.modify_(state, (s) => { const [o, s2, progress] = foldGo( in_, O.getOrElse_(s, () => initial), O.isSome(s), initial, contFn, f ) if (progress) { return Tp.tuple(o, O.some(s2)) } else { return Tp.tuple(o, O.none) } }) ) ) ) } /** * Creates a transducer by folding over a structure of type `O`. The transducer will * fold the inputs until the stream ends, resulting in a stream with one element. */ export function foldLeft<I, O>( initial: O, f: (output: O, input: I) => O ): Transducer<unknown, never, I, O> { return fold(initial, () => true, f) } /** * Creates a sink by effectfully folding over a structure of type `S`. */ export function foldM<R, E, I, O>( initial: O, contFn: (o: O) => boolean, f: (output: O, input: I) => T.Effect<R, E, O> ): Transducer<R, E, I, O> { const init = O.some(initial) const go = ( in_: Chunk.Chunk<I>, state: O, progress: boolean ): T.Effect<R, E, readonly [Chunk.Chunk<O>, O, boolean]> => Chunk.reduce_( in_, T.succeed([Chunk.empty(), state, progress]) as T.Effect< R, E, readonly [Chunk.Chunk<O>, O, boolean] >, (b, i) => T.chain_(b, ([os0, state, _]) => T.map_(f(state, i), (o) => { if (contFn(o)) { return [os0, o, true] as const } else { return [Chunk.append_(os0, o), initial, false] as const } }) ) ) return new Transducer( M.map_( R.makeManagedRef(init), (state) => (is: O.Option<Chunk.Chunk<I>>) => O.fold_( is, () => pipe( state, R.getAndSet(O.none as O.Option<O>), T.map(O.fold(() => Chunk.empty(), Chunk.single)) ), (in_) => pipe( state.get, T.chain((s) => go( in_, O.getOrElse_(s, () => initial), O.isSome(s) ) ), T.chain(([os, s, progress]) => progress ? T.zipRight_(state.set(O.some(s)), T.succeed(os)) : T.zipRight_(state.set(O.none), T.succeed(os)) ) ) ) ) ) } /** * Creates a transducer by effectfully folding over a structure of type `O`. The transducer will * fold the inputs until the stream ends, resulting in a stream with one element. */ export function foldLeftM<R, E, I, O>( initial: O, f: (output: O, input: I) => T.Effect<R, E, O> ): Transducer<R, E, I, O> { return foldM(initial, () => true, f) } /** * Creates a transducer that folds elements of type `I` into a structure * of type `O` until `max` elements have been folded. * * Like `foldWeighted`, but with a constant cost function of 1. */ export function foldUntil<I, O>( initial: O, max: number, f: (output: O, input: I) => O ): Transducer<unknown, never, I, O> { return pipe( fold( tuple(initial, 0), ([_, n]) => n < max, ([o, count], i: I) => [f(o, i), count + 1] as const ), map((t) => t[0]) ) } /** * Creates a transducer that effectfully folds elements of type `I` into a structure * of type `O` until `max` elements have been folded. * * Like `foldWeightedM`, but with a constant cost function of 1. */ export function foldUntilM<R, E, I, O>( initial: O, max: number, f: (output: O, input: I) => T.Effect<R, E, O> ): Transducer<R, E, I, O> { return pipe( foldM( tuple(initial, 0), ([_, n]) => n < max, ([o, count], i: I) => T.map_(f(o, i), (o) => [o, count + 1] as const) ), map((t) => t[0]) ) } /** * Creates a transducer that folds elements of type `I` into a structure * of type `O`, until `max` worth of elements (determined by the `costFn`) * have been folded. * * The `decompose` function will be used for decomposing elements that * cause an `O` aggregate to cross `max` into smaller elements. * * Be vigilant with this function, it has to generate "simpler" values * or the fold may never end. A value is considered indivisible if * `decompose` yields the empty chunk or a single-valued chunk. In * these cases, there is no other choice than to yield a value that * will cross the threshold. * * The foldWeightedDecomposeM allows the decompose function * to return an `Effect` value, and consequently it allows the transducer * to fail. */ export function foldWeightedDecompose<I, O>( initial: O, costFn: (output: O, input: I) => number, max: number, decompose: (input: I) => Chunk.Chunk<I>, f: (output: O, input: I) => O ): Transducer<unknown, never, I, O> { interface FoldWeightedState { result: O cost: number } const initialState: FoldWeightedState = { result: initial, cost: 0 } const go = ( in_: Chunk.Chunk<I>, os0: Chunk.Chunk<O>, state: FoldWeightedState, dirty: boolean ): readonly [Chunk.Chunk<O>, FoldWeightedState, boolean] => Chunk.reduce_(in_, [os0, state, dirty] as const, ([os0, state, _], i) => { const total = state.cost + costFn(state.result, i) if (total > max) { const is = decompose(i) if (Chunk.size(is) <= 1 && !dirty) { return [ Chunk.append_( os0, f(state.result, !Chunk.isEmpty(is) ? Chunk.unsafeGet_(is, 0) : i) ), initialState, false ] as const } else if (Chunk.size(is) <= 1 && dirty) { const elem = !Chunk.isEmpty(is) ? Chunk.unsafeGet_(is, 0) : i return [ Chunk.append_(os0, state.result), { result: f(initialState.result, elem), cost: costFn(initialState.result, elem) }, true ] as const } else { return go(is, os0, state, dirty) } } else { return [os0, { result: f(state.result, i), cost: total }, true] as const } }) return new Transducer( M.map_( R.makeManagedRef(O.some(initialState)), (state) => (is: O.Option<Chunk.Chunk<I>>) => O.fold_( is, () => pipe( state, R.getAndSet(O.none as O.Option<FoldWeightedState>), T.map( O.fold( () => Chunk.empty(), (s) => Chunk.single(s.result) ) ) ), (in_) => R.modify_(state, (s) => { const [o, s2, dirty] = go( in_, Chunk.empty(), O.getOrElse_(s, () => initialState), O.isSome(s) ) if (dirty) { return Tp.tuple(o, O.some(s2)) } else { return Tp.tuple(o, O.none) } }) ) ) ) } /** * Creates a transducer that effectfully folds elements of type `I` into a structure * of type `S`, until `max` worth of elements (determined by the `costFn`) have * been folded. * * The `decompose` function will be used for decomposing elements that * cause an `S` aggregate to cross `max` into smaller elements. Be vigilant with * this function, it has to generate "simpler" values or the fold may never end. * A value is considered indivisible if `decompose` yields the empty chunk or a * single-valued chunk. In these cases, there is no other choice than to yield * a value that will cross the threshold. * * See foldWeightedDecompose for an example. */ export function foldWeightedDecomposeM<R, E, I, O>( initial: O, costFn: (output: O, input: I) => T.Effect<R, E, number>, max: number, decompose: (input: I) => T.Effect<R, E, Chunk.Chunk<I>>, f: (output: O, input: I) => T.Effect<R, E, O> ): Transducer<R, E, I, O> { interface FoldWeightedState { result: O cost: number } const initialState: FoldWeightedState = { result: initial, cost: 0 } const go = ( in_: Chunk.Chunk<I>, os: Chunk.Chunk<O>, state: FoldWeightedState, dirty: boolean ): T.Effect<R, E, readonly [Chunk.Chunk<O>, FoldWeightedState, boolean]> => Chunk.reduce_( in_, T.succeed([os, state, dirty]) as T.Effect< R, E, readonly [Chunk.Chunk<O>, FoldWeightedState, boolean] >, (o, i) => T.chain_(o, ([os, state, _]) => T.chain_(costFn(state.result, i), (cost) => { const total = cost + state.cost if (total > max) { return T.chain_(decompose(i), (is) => { if (Chunk.size(is) <= 1 && !dirty) { return T.map_( f(state.result, !Chunk.isEmpty(is) ? Chunk.unsafeGet_(is, 0) : i), (o) => [Chunk.append_(os, o), initialState, false] as const ) } else if (Chunk.size(is) <= 1 && dirty) { const elem = !Chunk.isEmpty(is) ? Chunk.unsafeGet_(is, 0) : i return T.zipWith_( f(initialState.result, elem), costFn(initialState.result, elem), (result, cost) => [ Chunk.append_(os, state.result), { result, cost }, true ] ) } else { return go(is, os, state, dirty) } }) } else { return T.map_( f(state.result, i), (o) => [os, { result: o, cost: total }, true] as const ) } }) ) ) return new Transducer( M.map_( R.makeManagedRef(O.some(initialState)), (state) => (is: O.Option<Chunk.Chunk<I>>) => O.fold_( is, () => pipe( state, R.getAndSet(O.none as O.Option<FoldWeightedState>), T.map( O.fold( () => Chunk.empty(), (s) => Chunk.single(s.result) ) ) ), (in_) => pipe( state.get, T.chain((s) => go( in_, Chunk.empty(), O.getOrElse_(s, () => initialState), O.isSome(s) ) ), T.chain(([os, s, dirty]) => dirty ? T.zipRight_(state.set(O.some(s)), T.succeed(os)) : T.zipRight_(state.set(O.none), T.succeed(os)) ) ) ) ) ) } /** * Creates a transducer that folds elements of type `I` into a structure * of type `O`, until `max` worth of elements (determined by the `costFn`) * have been folded. * * @note Elements that have an individual cost larger than `max` will * force the transducer to cross the `max` cost. See `foldWeightedDecompose` * for a variant that can handle these cases. */ export function foldWeighted<I, O>( initial: O, costFn: (o: O, i: I) => number, max: number, f: (o: O, i: I) => O ): Transducer<unknown, never, I, O> { return foldWeightedDecompose(initial, costFn, max, Chunk.single, f) } function collectAllNGo<I>( n: number, in_: Chunk.Chunk<I>, leftover: Chunk.Chunk<I>, acc: Chunk.Chunk<Chunk.Chunk<I>> ): Tp.Tuple<[Chunk.Chunk<Chunk.Chunk<I>>, Chunk.Chunk<I>]> { // eslint-disable-next-line no-constant-condition while (1) { const { tuple: [left, nextIn] } = Chunk.splitAt_(in_, n - Chunk.size(leftover)) if (Chunk.size(leftover) + Chunk.size(left) < n) return Tp.tuple(acc, Chunk.concat_(leftover, left)) else { const nextOut = !Chunk.isEmpty(leftover) ? Chunk.append_(acc, Chunk.concat_(leftover, left)) : Chunk.append_(acc, left) in_ = nextIn leftover = Chunk.empty() acc = nextOut } } throw new Error("Bug") } /** * Creates a transducer accumulating incoming values into chunks of maximum size `n`. */ export function collectAllN<I>( n: number ): Transducer<unknown, never, I, Chunk.Chunk<I>> { return new Transducer( M.map_( R.makeManagedRef(Chunk.empty<I>()), (state) => (is: O.Option<Chunk.Chunk<I>>) => O.fold_( is, () => T.map_(R.getAndSet_(state, Chunk.empty()), (leftover) => !Chunk.isEmpty(leftover) ? Chunk.single(leftover) : Chunk.empty() ), (in_) => R.modify_(state, (leftover) => collectAllNGo(n, in_, leftover, Chunk.empty()) ) ) ) ) } /** * Creates a transducer accumulating incoming values into maps of up to `n` keys. Elements * are mapped to keys using the function `key`; elements mapped to the same key will * be merged with the function `f`. */ export function collectAllToMapN<K, I>( n: number, key: (i: I) => K, merge: (i: I, i1: I) => I ): Transducer<unknown, never, I, ReadonlyMap<K, I>> { return pipe( foldWeighted<I, ReadonlyMap<K, I>>( Map.empty, (acc, i) => (acc.has(key(i)) ? 0 : 1), n, (acc, i) => { const k = key(i) if (acc.has(k)) return Map.insert(k, merge(acc.get(k) as I, i))(acc) else return Map.insert(k, i)(acc) } ), filter(not(Map.isEmpty)) ) } /** * Accumulates incoming elements into a chunk as long as they verify predicate `p`. */ export function collectAllWhile<I>( p: Predicate<I> ): Transducer<unknown, never, I, Chunk.Chunk<I>> { return pipe( fold<I, [Chunk.Chunk<I>, boolean]>( [Chunk.empty(), true], (t) => t[1], ([is, _], i) => (p(i) ? [Chunk.append_(is, i), true] : [is, false]) ), map((t) => t[0]), filter((x) => !Chunk.isEmpty(x)) ) } /** * Accumulates incoming elements into a chunk as long as they verify effectful predicate `p`. */ export function collectAllWhileM<R, E, I>( p: (i: I) => T.Effect<R, E, boolean> ): Transducer<R, E, I, Chunk.Chunk<I>> { return pipe( foldM<R, E, I, [Chunk.Chunk<I>, boolean]>( [Chunk.empty(), true], (t) => t[1], ([is, _], i) => T.map_(p(i), (b) => (b ? [Chunk.append_(is, i), true] : [is, false])) ), map((t) => t[0]), filter((x) => !Chunk.isEmpty(x)) ) } /** * Filters the outputs of this transducer. */ export function filter_<R, E, I, O>( fa: Transducer<R, E, I, O>, predicate: Predicate<O> ): Transducer<R, E, I, O> export function filter_<R, E, I, O, B extends O>( fa: Transducer<R, E, I, O>, refinement: Refinement<O, B> ): Transducer<R, E, I, B> export function filter_<R, E, I, O>( fa: Transducer<R, E, I, O>, predicate: Predicate<O> ): Transducer<R, E, I, O> { return new Transducer( M.map_(fa.push, (push) => (is) => T.map_(push(is), Chunk.filter(predicate))) ) } /** * Filters the outputs of this transducer. */ export function filter<O>( predicate: Predicate<O> ): <R, E, I>(fa: Transducer<R, E, I, O>) => Transducer<R, E, I, O> export function filter<O, B extends O>( refinement: Refinement<O, B> ): <R, E, I>(fa: Transducer<R, E, I, O>) => Transducer<R, E, I, B> export function filter<O>( predicate: Predicate<O> ): <R, E, I>(fa: Transducer<R, E, I, O>) => Transducer<R, E, I, O> { return (fa) => filter_(fa, predicate) } /** * Filters the inputs of this transducer. */ export function filterInput_<R, E, I, O>( fa: Transducer<R, E, I, O>, predicate: Predicate<I> ): Transducer<R, E, I, O> export function filterInput_<R, E, I, O, I1 extends I>( fa: Transducer<R, E, I, O>, refinement: Refinement<I, I1> ): Transducer<R, E, I1, O> export function filterInput_<R, E, I, O>( fa: Transducer<R, E, I, O>, predicate: Predicate<I> ): Transducer<R, E, I, O> { return new Transducer( M.map_(fa.push, (push) => (is) => push(O.map_(is, Chunk.filter(predicate)))) ) } /** * Filters the inputs of this transducer. */ export function filterInput<I>( predicate: Predicate<I> ): <R, E, O>(fa: Transducer<R, E, I, O>) => Transducer<R, E, I, O> export function filterInput<I, I1 extends I>( refinement: Refinement<I, I1> ): <R, E, O>(fa: Transducer<R, E, I, O>) => Transducer<R, E, I1, O> export function filterInput<I>( predicate: Predicate<I> ): <R, E, O>(fa: Transducer<R, E, I, O>) => Transducer<R, E, I, O> { return (fa) => filterInput_(fa, predicate) } /** * Effectually filters the inputs of this transducer. */ export function filterInputM_<R, E, I, O, R1, E1>( fa: Transducer<R, E, I, O>, predicate: (i: I) => T.Effect<R1, E1, boolean> ): Transducer<R & R1, E | E1, I, O> { return new Transducer( M.map_( fa.push, (push) => (is) => O.fold_( is, () => push(O.none), (x) => pipe( x, Chunk.filterM(predicate), T.chain((in_) => push(O.some(in_))) ) ) ) ) } /** * Effectually filters the inputs of this transducer. */ export function filterInputM<I, R1, E1>( predicate: (i: I) => T.Effect<R1, E1, boolean> ): <R, E, O>(fa: Transducer<R, E, I, O>) => Transducer<R & R1, E | E1, I, O> { return (fa) => filterInputM_(fa, predicate) } /** * Creates a transducer produced from an effect. */ export function unwrap<R, E, I, O>( effect: T.Effect<R, E, Transducer<R, E, I, O>> ): Transducer<R, E, I, O> { return unwrapManaged(T.toManaged(effect)) } /** * Creates a transducer produced from a managed effect. */ export function unwrapManaged<R, E, I, O>( managed: M.Managed<R, E, Transducer<R, E, I, O>> ): Transducer<R, E, I, O> { return new Transducer( M.chain_( M.fold_( managed, (err) => fail<E>(err), (_) => _ ), (_) => _.push ) ) }
the_stack
import { createLocalVue, mount, shallowMount, Wrapper } from '@vue/test-utils'; import Vuex from 'vuex'; import DeleteConfirmationModal from '@/components/DeleteConfirmationModal.vue'; import PipelineComponent from '@/components/Pipeline.vue'; import * as clipboardUtils from '@/lib/clipboard'; import { Pipeline } from '@/lib/steps'; import { VQBnamespace } from '@/store'; import { buildStateWithOnePipeline, setupMockStore } from './utils'; jest.mock('@/components/FAIcon.vue'); const localVue = createLocalVue(); localVue.use(Vuex); describe('Pipeline.vue', () => { it('renders steps', () => { const pipeline: Pipeline = [ { name: 'domain', domain: 'GoT' }, { name: 'replace', search_column: 'characters', to_replace: [['Snow', 'Targaryen']] }, { name: 'sort', columns: [{ column: 'death', order: 'asc' }] }, ]; const store = setupMockStore(buildStateWithOnePipeline(pipeline)); const wrapper = shallowMount(PipelineComponent, { store, localVue }); const steps = wrapper.findAll('step-stub'); expect(steps.length).toEqual(3); const [step1, step2, step3] = steps.wrappers.map(stub => stub.props()); expect(step1).toEqual({ step: pipeline[0], isActive: true, isLastActive: false, isDisabled: false, isFirst: true, isLast: false, toDelete: false, isEditable: true, indexInPipeline: 0, }); expect(step2).toEqual({ step: pipeline[1], isActive: true, isLastActive: false, isDisabled: false, isFirst: false, isLast: false, toDelete: false, isEditable: true, indexInPipeline: 1, }); expect(step3).toEqual({ step: pipeline[2], isActive: false, isLastActive: true, isDisabled: false, isFirst: false, isLast: true, toDelete: false, isEditable: true, indexInPipeline: 2, }); }); it('should render a container with tips', () => { const pipeline: Pipeline = [{ name: 'domain', domain: 'GoT' }]; const store = setupMockStore({ pipeline }); const wrapper = shallowMount(PipelineComponent, { store, localVue }); expect(wrapper.find('.query-pipeline__tips').text()).toEqual( 'Interact with the widgets and table on the right to add steps', ); const icons = wrapper.findAll('FAIcon-stub'); expect(icons.at(0).props().icon).toBe('magic'); }); describe('toggle delete step', () => { let wrapper: Wrapper<PipelineComponent>, stepToDelete: Wrapper<any>; beforeEach(async () => { const pipeline: Pipeline = [ { name: 'domain', domain: 'GoT' }, { name: 'rename', toRename: [['foo', 'bar']] }, { name: 'sort', columns: [{ column: 'death', order: 'asc' }] }, ]; const store = setupMockStore(buildStateWithOnePipeline(pipeline)); wrapper = shallowMount(PipelineComponent, { store, localVue }); const steps = wrapper.findAll('step-stub'); stepToDelete = steps.at(1); stepToDelete.vm.$emit('toggleDelete'); await wrapper.vm.$nextTick(); }); it('should add step index to steps to delete', () => { expect((wrapper.vm as any).selectedSteps).toContain(1); }); it('should apply delete class to step', () => { expect(stepToDelete.props().toDelete).toBe(true); }); describe('when already selected', () => { beforeEach(async () => { stepToDelete.vm.$emit('toggleDelete'); await wrapper.vm.$nextTick(); }); it('should remove step index from step to delete', () => { expect((wrapper.vm as any).selectedSteps).not.toContain(1); }); it('should remove delete class from step', () => { expect(stepToDelete.props().toDelete).toBe(false); }); }); describe('when there is steps selected', () => { beforeEach(async () => { wrapper.setData({ selectedSteps: [1, 2] }); await wrapper.vm.$nextTick(); }); it('should show the delete steps button', () => { expect(wrapper.find('.query-pipeline__delete-steps-container').exists()).toBe(true); }); it('should display the number of selected steps into the delete steps button', () => { expect(wrapper.find('.query-pipeline__delete-steps').text()).toContain( 'Delete [2] selected', ); }); it('should make steps uneditable', () => { const steps = wrapper.findAll('step-stub'); steps.wrappers.map(stub => expect(stub.props().isEditable).toBe(false)); }); }); describe('when there is no steps to delete', () => { beforeEach(async () => { wrapper.setData({ selectedSteps: [] }); await wrapper.vm.$nextTick(); }); it('should hide the delete steps button', () => { expect(wrapper.find('.qquery-pipeline__delete-steps-container').exists()).toBe(false); }); }); }); it('does not render a delete confirmation modal by default', () => { const pipeline: Pipeline = [ { name: 'domain', domain: 'GoT' }, { name: 'rename', toRename: [['foo', 'bar']] }, { name: 'sort', columns: [{ column: 'death', order: 'asc' }] }, ]; const store = setupMockStore(buildStateWithOnePipeline(pipeline)); const wrapper = shallowMount(PipelineComponent, { store, localVue }); const modal = wrapper.find('deleteconfirmationmodal-stub'); expect(modal.exists()).toBe(false); }); describe('clicking on the delete button', () => { let wrapper: Wrapper<PipelineComponent>, modal: Wrapper<any>, dispatchSpy: jest.SpyInstance; const selectedSteps = [1, 2]; beforeEach(async () => { const pipeline: Pipeline = [ { name: 'domain', domain: 'GoT' }, { name: 'rename', toRename: [['foo', 'bar']] }, { name: 'sort', columns: [{ column: 'death', order: 'asc' }] }, ]; const store = setupMockStore(buildStateWithOnePipeline(pipeline)); dispatchSpy = jest.spyOn(store, 'dispatch'); wrapper = mount(PipelineComponent, { store, localVue }); wrapper.setData({ selectedSteps }); wrapper.find('.query-pipeline__delete-steps').trigger('click'); await wrapper.vm.$nextTick(); modal = wrapper.find(DeleteConfirmationModal); }); it('should render a delete confirmation modal', async () => { expect(modal.exists()).toBe(true); }); describe('when cancel confirmation', () => { beforeEach(async () => { modal.find('.vqb-modal__action--secondary').trigger('click'); await wrapper.vm.$nextTick(); modal = wrapper.find(DeleteConfirmationModal); }); it('should close the confirmation modal', () => { // close the modal expect(modal.exists()).toBe(false); }); it('should not delete the selected steps', () => { expect(dispatchSpy).not.toHaveBeenCalled(); }); it('should keep the selected steps unchanged', () => { expect((wrapper.vm as any).selectedSteps).toStrictEqual(selectedSteps); }); }); describe('when validate', () => { beforeEach(async () => { modal.find('.vqb-modal__action--primary').trigger('click'); await wrapper.vm.$nextTick(); modal = wrapper.find(DeleteConfirmationModal); }); it('should close the confirmation modal', () => { // close the modal expect(modal.exists()).toBe(false); }); it('should delete the selected steps', () => { expect(dispatchSpy).toHaveBeenCalledWith(VQBnamespace('deleteSteps'), { indexes: selectedSteps, }); }); it('should clean the selected steps', () => { expect((wrapper.vm as any).selectedSteps).toStrictEqual([]); }); }); }); describe('clicking on backspace', () => { let wrapper: Wrapper<PipelineComponent>, modal: Wrapper<any>; const selectedSteps = [1, 2]; beforeEach(async () => { const pipeline: Pipeline = [ { name: 'domain', domain: 'GoT' }, { name: 'rename', toRename: [['foo', 'bar']] }, { name: 'sort', columns: [{ column: 'death', order: 'asc' }] }, ]; const store = setupMockStore(buildStateWithOnePipeline(pipeline)); wrapper = mount(PipelineComponent, { store, localVue }); wrapper.setData({ selectedSteps }); (wrapper.vm as any).keyDownEventHandler({ key: 'Backspace' }); await wrapper.vm.$nextTick(); modal = wrapper.find(DeleteConfirmationModal); }); it('should render a delete confirmation modal', async () => { expect(modal.exists()).toBe(true); }); }); describe('reorder steps', () => { let wrapper: Wrapper<PipelineComponent>, commitSpy: jest.SpyInstance, dispatchSpy: jest.SpyInstance; beforeEach(async () => { const pipeline: Pipeline = [ { name: 'domain', domain: 'GoT' }, { name: 'rename', toRename: [['foo', 'bar']] }, { name: 'sort', columns: [{ column: 'death', order: 'asc' }] }, { name: 'sort', columns: [{ column: 'death', order: 'desc' }] }, ]; const store = setupMockStore(buildStateWithOnePipeline(pipeline)); commitSpy = jest.spyOn(store, 'commit'); dispatchSpy = jest.spyOn(store, 'dispatch'); wrapper = shallowMount(PipelineComponent, { store, localVue }); }); it('should have a draggable steps list as pipeline', () => { expect(wrapper.find('Draggable-stub').exists()).toBe(true); }); describe('when steps position are arranged', () => { const reorderedPipeline: Pipeline = [ { name: 'domain', domain: 'GoT' }, { name: 'rename', toRename: [['foo', 'bar']] }, { name: 'sort', columns: [{ column: 'death', order: 'desc' }] }, { name: 'sort', columns: [{ column: 'death', order: 'asc' }] }, ]; beforeEach(async () => { wrapper.find('draggable-stub').vm.$emit('input', reorderedPipeline); // fake drag/drop step action await wrapper.vm.$nextTick(); }); it('should rerender pipeline', () => { expect(commitSpy).toHaveBeenCalledWith( VQBnamespace('setPipeline'), { pipeline: reorderedPipeline }, undefined, ); }); it('should update active step index', () => { expect(dispatchSpy).toHaveBeenCalledWith(VQBnamespace('selectStep'), { index: 2 }); }); }); }); describe('copy steps', () => { let wrapper: Wrapper<PipelineComponent>, copyToClipboardStub: jest.SpyInstance; const ctrlC = () => { (wrapper.vm as any).keyDownEventHandler({ key: 'c', ctrlKey: true }); // fake ctrl + c; }; const cmdC = () => { (wrapper.vm as any).keyDownEventHandler({ key: 'c', metaKey: true }); // fake cmd + c; }; beforeEach(() => { const pipeline: Pipeline = [ { name: 'domain', domain: 'GoT' }, { name: 'rename', toRename: [['foo', 'bar']] }, { name: 'sort', columns: [{ column: 'death', order: 'asc' }] }, ]; const store = setupMockStore(buildStateWithOnePipeline(pipeline)); copyToClipboardStub = jest.spyOn(clipboardUtils, 'copyToClipboard').mockImplementation(); wrapper = shallowMount(PipelineComponent, { store, localVue }); }); afterEach(() => { jest.clearAllMocks(); }); describe('with ctrl + c', () => { it('should not copy selected steps content if empty', () => { ctrlC(); expect(copyToClipboardStub).not.toHaveBeenCalled(); }); it('should copy selected steps content to clipboard', () => { const selectedSteps = [1, 2]; wrapper.setData({ selectedSteps }); ctrlC(); const stringifiedStepsContent = JSON.stringify([ { name: 'rename', toRename: [['foo', 'bar']] }, { name: 'sort', columns: [{ column: 'death', order: 'asc' }] }, ]); expect(copyToClipboardStub).toHaveBeenCalledWith(stringifiedStepsContent); }); }); describe('with cmd + c', () => { it('should not copy selected steps content if empty', () => { cmdC(); expect(copyToClipboardStub).not.toHaveBeenCalled(); }); it('should copy selected steps content to clipboard', () => { const selectedSteps = [1, 2]; wrapper.setData({ selectedSteps }); cmdC(); const stringifiedStepsContent = JSON.stringify([ { name: 'rename', toRename: [['foo', 'bar']] }, { name: 'sort', columns: [{ column: 'death', order: 'asc' }] }, ]); expect(copyToClipboardStub).toHaveBeenCalledWith(stringifiedStepsContent); }); }); }); describe('paste steps', () => { let wrapper: Wrapper<PipelineComponent>, dispatchSpy: jest.SpyInstance, pasteFromClipboardStub: jest.SpyInstance; const ctrlV = () => { (wrapper.vm as any).keyDownEventHandler({ key: 'v', ctrlKey: true }); // fake ctrl + v; }; const cmdV = () => { (wrapper.vm as any).keyDownEventHandler({ key: 'v', metaKey: true }); // fake cmd + v; }; beforeEach(async () => { const pipeline: Pipeline = [ { name: 'domain', domain: 'GoT' }, { name: 'rename', toRename: [['foo', 'bar']] }, { name: 'sort', columns: [{ column: 'death', order: 'asc' }] }, { name: 'sort', columns: [{ column: 'death', order: 'desc' }] }, ]; const store = setupMockStore(buildStateWithOnePipeline(pipeline)); dispatchSpy = jest.spyOn(store, 'dispatch'); pasteFromClipboardStub = jest .spyOn(clipboardUtils, 'pasteFromClipboard') .mockImplementation(); wrapper = shallowMount(PipelineComponent, { store, localVue }); }); describe('with valid steps', () => { const stepsFromClipboard = [ { name: 'rename', toRename: [['foo', 'bar']] }, { name: 'sort', columns: [{ column: 'death', order: 'asc' }] }, ]; beforeEach(async () => { pasteFromClipboardStub.mockResolvedValue(JSON.stringify(stepsFromClipboard)); ctrlV(); }); it('should retrieved selected steps from clipboard', () => { expect(pasteFromClipboardStub).toHaveBeenCalled(); }); it('should add steps to pipeline', () => { expect(dispatchSpy).toHaveBeenCalledWith(VQBnamespace('addSteps'), { steps: stepsFromClipboard, }); }); }); describe('with cmd + v', () => { const stepsFromClipboard = [ { name: 'rename', toRename: [['foo', 'bar']] }, { name: 'sort', columns: [{ column: 'death', order: 'asc' }] }, ]; beforeEach(async () => { pasteFromClipboardStub.mockResolvedValue(JSON.stringify(stepsFromClipboard)); cmdV(); }); it('should retrieved selected steps from clipboard', () => { expect(pasteFromClipboardStub).toHaveBeenCalled(); }); it('should add steps to pipeline', () => { expect(dispatchSpy).toHaveBeenCalledWith(VQBnamespace('addSteps'), { steps: stepsFromClipboard, }); }); }); describe('with invalid steps', () => { const stepsFromClipboard = [ 'TOTO', { name: 'sort', columns: [{ column: 'death', order: 'asc' }] }, ]; beforeEach(async () => { pasteFromClipboardStub.mockResolvedValue(JSON.stringify(stepsFromClipboard)); ctrlV(); }); it('should not add steps to pipeline', () => { expect(dispatchSpy).not.toHaveBeenCalledWith(VQBnamespace('addSteps'), { steps: stepsFromClipboard, }); }); }); describe('when passed steps are not an array', () => { const stepsFromClipboard = 'TOTO'; beforeEach(async () => { pasteFromClipboardStub.mockResolvedValue(JSON.stringify(stepsFromClipboard)); ctrlV(); }); it('should not add steps to pipeline', () => { expect(dispatchSpy).not.toHaveBeenCalledWith(VQBnamespace('addSteps'), { steps: stepsFromClipboard, }); }); }); }); describe('without supported steps', () => { let wrapper: Wrapper<PipelineComponent>; beforeEach(() => { const store = setupMockStore( buildStateWithOnePipeline([], { translator: 'empty', // there is no supported actions in empty translator dataset: { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [['value1', 'value2', 'value3']], paginationContext: { totalCount: 10, pagesize: 10, pageno: 1, }, }, }), ); wrapper = shallowMount(PipelineComponent, { store, localVue }); }); it('should hide the pipeline tips', () => { expect(wrapper.find('.query-pipeline__tips-container').exists()).toBeFalsy(); }); }); });
the_stack
import { BoolPropertyDefinition } from "../../../PropertyDefinitions/BoolPropertyDefinition"; import { ComplexPropertyDefinition } from "../../../PropertyDefinitions/ComplexPropertyDefinition"; import { DateTimePropertyDefinition } from "../../../PropertyDefinitions/DateTimePropertyDefinition"; import { DoublePropertyDefinition } from "../../../PropertyDefinitions/DoublePropertyDefinition"; import { ExchangeVersion } from "../../../Enumerations/ExchangeVersion"; import { GenericPropertyDefinition } from "../../../PropertyDefinitions/GenericPropertyDefinition"; import { IntPropertyDefinition } from "../../../PropertyDefinitions/IntPropertyDefinition"; import { PropertyDefinition } from "../../../PropertyDefinitions/PropertyDefinition"; import { PropertyDefinitionFlags } from "../../../Enumerations/PropertyDefinitionFlags"; import { RecurrencePropertyDefinition } from "../../../PropertyDefinitions/RecurrencePropertyDefinition"; import { Schemas } from "./Schemas"; import { StringList } from "../../../ComplexProperties/StringList"; import { StringPropertyDefinition } from "../../../PropertyDefinitions/StringPropertyDefinition"; import { TaskDelegationStatePropertyDefinition } from "../../../PropertyDefinitions/TaskDelegationStatePropertyDefinition"; import { TaskMode } from "../../../Enumerations/TaskMode"; import { TaskStatus } from "../../../Enumerations/TaskStatus"; import { XmlElementNames } from "../../XmlElementNames"; import { ItemSchema } from "./ItemSchema"; /** * Field URIs for tasks. */ module FieldUris { export var ActualWork: string = "task:ActualWork"; export var AssignedTime: string = "task:AssignedTime"; export var BillingInformation: string = "task:BillingInformation"; export var ChangeCount: string = "task:ChangeCount"; export var Companies: string = "task:Companies"; export var CompleteDate: string = "task:CompleteDate"; export var Contacts: string = "task:Contacts"; export var DelegationState: string = "task:DelegationState"; export var Delegator: string = "task:Delegator"; export var DueDate: string = "task:DueDate"; export var IsAssignmentEditable: string = "task:IsAssignmentEditable"; export var IsComplete: string = "task:IsComplete"; export var IsRecurring: string = "task:IsRecurring"; export var IsTeamTask: string = "task:IsTeamTask"; export var Mileage: string = "task:Mileage"; export var Owner: string = "task:Owner"; export var PercentComplete: string = "task:PercentComplete"; export var Recurrence: string = "task:Recurrence"; export var StartDate: string = "task:StartDate"; export var Status: string = "task:Status"; export var StatusDescription: string = "task:StatusDescription"; export var TotalWork: string = "task:TotalWork"; } /** * Represents the schema for task items. */ export class TaskSchema extends ItemSchema { /** * Defines the **ActualWork** property. */ public static ActualWork: PropertyDefinition = new IntPropertyDefinition( "ActualWork", XmlElementNames.ActualWork, FieldUris.ActualWork, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, true ); /** * Defines the **AssignedTime** property. */ public static AssignedTime: PropertyDefinition = new DateTimePropertyDefinition( "AssignedTime", XmlElementNames.AssignedTime, FieldUris.AssignedTime, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, true ); /** * Defines the **BillingInformation** property. */ public static BillingInformation: PropertyDefinition = new StringPropertyDefinition( "BillingInformation", XmlElementNames.BillingInformation, FieldUris.BillingInformation, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **ChangeCount** property. */ public static ChangeCount: PropertyDefinition = new IntPropertyDefinition( "ChangeCount", XmlElementNames.ChangeCount, FieldUris.ChangeCount, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **Companies** property. */ public static Companies: PropertyDefinition = new ComplexPropertyDefinition<StringList>( "Companies", XmlElementNames.Companies, FieldUris.Companies, PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, () => { return new StringList(); } ); /** * Defines the **CompleteDate** property. */ public static CompleteDate: PropertyDefinition = new DateTimePropertyDefinition( "CompleteDate", XmlElementNames.CompleteDate, FieldUris.CompleteDate, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, true ); /** * Defines the **Contacts** property. */ public static Contacts: PropertyDefinition = new ComplexPropertyDefinition<StringList>( "Contacts", XmlElementNames.Contacts, FieldUris.Contacts, PropertyDefinitionFlags.AutoInstantiateOnRead | PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, () => { return new StringList(); } ); /** * Defines the **DelegationState** property. */ public static DelegationState: PropertyDefinition = new TaskDelegationStatePropertyDefinition( "DelegationState", XmlElementNames.DelegationState, FieldUris.DelegationState, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **Delegator** property. */ public static Delegator: PropertyDefinition = new StringPropertyDefinition( "Delegator", XmlElementNames.Delegator, FieldUris.Delegator, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **DueDate** property. */ public static DueDate: PropertyDefinition = new DateTimePropertyDefinition( "DueDate", XmlElementNames.DueDate, FieldUris.DueDate, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, true ); /** * Defines the **Mode** property. */ public static Mode: PropertyDefinition = new GenericPropertyDefinition<TaskMode>( "IsAssignmentEditable", XmlElementNames.IsAssignmentEditable, FieldUris.IsAssignmentEditable, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, TaskMode ); /** * Defines the **IsComplete** property. */ public static IsComplete: PropertyDefinition = new BoolPropertyDefinition( "IsComplete", XmlElementNames.IsComplete, FieldUris.IsComplete, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **IsRecurring** property. */ public static IsRecurring: PropertyDefinition = new BoolPropertyDefinition( "IsRecurring", XmlElementNames.IsRecurring, FieldUris.IsRecurring, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **IsTeamTask** property. */ public static IsTeamTask: PropertyDefinition = new BoolPropertyDefinition( "IsTeamTask", XmlElementNames.IsTeamTask, FieldUris.IsTeamTask, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **Mileage** property. */ public static Mileage: PropertyDefinition = new StringPropertyDefinition( "Mileage", XmlElementNames.Mileage, FieldUris.Mileage, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **Owner** property. */ public static Owner: PropertyDefinition = new StringPropertyDefinition( "Owner", XmlElementNames.Owner, FieldUris.Owner, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **PercentComplete** property. */ public static PercentComplete: PropertyDefinition = new DoublePropertyDefinition( "PercentComplete", XmlElementNames.PercentComplete, FieldUris.PercentComplete, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **Recurrence** property. */ public static Recurrence: PropertyDefinition = new RecurrencePropertyDefinition( "Recurrence", XmlElementNames.Recurrence, FieldUris.Recurrence, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **StartDate** property. */ public static StartDate: PropertyDefinition = new DateTimePropertyDefinition( "StartDate", XmlElementNames.StartDate, FieldUris.StartDate, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, true ); /** * Defines the **Status** property. */ public static Status: PropertyDefinition = new GenericPropertyDefinition<TaskStatus>( "Status", XmlElementNames.Status, FieldUris.Status, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, TaskStatus ); /** * Defines the **StatusDescription** property. */ public static StatusDescription: PropertyDefinition = new StringPropertyDefinition( "StatusDescription", XmlElementNames.StatusDescription, FieldUris.StatusDescription, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1 ); /** * Defines the **TotalWork** property. */ public static TotalWork: PropertyDefinition = new IntPropertyDefinition( "TotalWork", XmlElementNames.TotalWork, FieldUris.TotalWork, PropertyDefinitionFlags.CanSet | PropertyDefinitionFlags.CanUpdate | PropertyDefinitionFlags.CanDelete | PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1, true ); /** * @internal Instance of **TaskSchema** */ static Instance: TaskSchema = new TaskSchema(); /** * Registers properties. * * /remarks/ IMPORTANT NOTE: PROPERTIES MUST BE REGISTERED IN SCHEMA ORDER (i.e. the same order as they are defined in types.xsd) */ RegisterProperties(): void { super.RegisterProperties(); this.RegisterProperty(TaskSchema, TaskSchema.ActualWork); this.RegisterProperty(TaskSchema, TaskSchema.AssignedTime); this.RegisterProperty(TaskSchema, TaskSchema.BillingInformation); this.RegisterProperty(TaskSchema, TaskSchema.ChangeCount); this.RegisterProperty(TaskSchema, TaskSchema.Companies); this.RegisterProperty(TaskSchema, TaskSchema.CompleteDate); this.RegisterProperty(TaskSchema, TaskSchema.Contacts); this.RegisterProperty(TaskSchema, TaskSchema.DelegationState); this.RegisterProperty(TaskSchema, TaskSchema.Delegator); this.RegisterProperty(TaskSchema, TaskSchema.DueDate); this.RegisterProperty(TaskSchema, TaskSchema.Mode); this.RegisterProperty(TaskSchema, TaskSchema.IsComplete); this.RegisterProperty(TaskSchema, TaskSchema.IsRecurring); this.RegisterProperty(TaskSchema, TaskSchema.IsTeamTask); this.RegisterProperty(TaskSchema, TaskSchema.Mileage); this.RegisterProperty(TaskSchema, TaskSchema.Owner); this.RegisterProperty(TaskSchema, TaskSchema.PercentComplete); this.RegisterProperty(TaskSchema, TaskSchema.Recurrence); this.RegisterProperty(TaskSchema, TaskSchema.StartDate); this.RegisterProperty(TaskSchema, TaskSchema.Status); this.RegisterProperty(TaskSchema, TaskSchema.StatusDescription); this.RegisterProperty(TaskSchema, TaskSchema.TotalWork); } } /** * Represents the schema for task items. */ export interface TaskSchema { /** * Defines the **ActualWork** property. */ ActualWork: PropertyDefinition; /** * Defines the **AssignedTime** property. */ AssignedTime: PropertyDefinition; /** * Defines the **BillingInformation** property. */ BillingInformation: PropertyDefinition; /** * Defines the **ChangeCount** property. */ ChangeCount: PropertyDefinition; /** * Defines the **Companies** property. */ Companies: PropertyDefinition; /** * Defines the **CompleteDate** property. */ CompleteDate: PropertyDefinition; /** * Defines the **Contacts** property. */ Contacts: PropertyDefinition; /** * Defines the **DelegationState** property. */ DelegationState: PropertyDefinition; /** * Defines the **Delegator** property. */ Delegator: PropertyDefinition; /** * Defines the **DueDate** property. */ DueDate: PropertyDefinition; /** * Defines the **Mode** property. */ Mode: PropertyDefinition; /** * Defines the **IsComplete** property. */ IsComplete: PropertyDefinition; /** * Defines the **IsRecurring** property. */ IsRecurring: PropertyDefinition; /** * Defines the **IsTeamTask** property. */ IsTeamTask: PropertyDefinition; /** * Defines the **Mileage** property. */ Mileage: PropertyDefinition; /** * Defines the **Owner** property. */ Owner: PropertyDefinition; /** * Defines the **PercentComplete** property. */ PercentComplete: PropertyDefinition; /** * Defines the **Recurrence** property. */ Recurrence: PropertyDefinition; /** * Defines the **StartDate** property. */ StartDate: PropertyDefinition; /** * Defines the **Status** property. */ Status: PropertyDefinition; /** * Defines the **StatusDescription** property. */ StatusDescription: PropertyDefinition; /** * Defines the **TotalWork** property. */ TotalWork: PropertyDefinition; /** * @internal Instance of **TaskSchema** */ Instance: TaskSchema; } /** * Represents the schema for task items. */ export interface TaskSchemaStatic extends TaskSchema { }
the_stack
import { KubernetesObject } from "kpt-functions"; import * as apiCoreV1 from "./io.k8s.api.core.v1"; import * as apisMetaV1 from "./io.k8s.apimachinery.pkg.apis.meta.v1"; import * as apimachineryPkgRuntime from "./io.k8s.apimachinery.pkg.runtime"; import * as pkgUtilIntstr from "./io.k8s.apimachinery.pkg.util.intstr"; // DEPRECATED - This group version of ControllerRevision is deprecated by apps/v1beta2/ControllerRevision. See the release notes for more information. ControllerRevision implements an immutable snapshot of state data. Clients are responsible for serializing and deserializing the objects that contain their internal state. Once a ControllerRevision has been successfully created, it can not be updated. The API Server will fail validation of all requests that attempt to mutate the Data field. ControllerRevisions may, however, be deleted. Note that, due to its use by both the DaemonSet and StatefulSet controllers for update and rollback, this object is beta. However, it may be subject to name and representation changes in future releases, and clients should not depend on its stability. It is primarily for internal use by controllers. export class ControllerRevision implements KubernetesObject { // APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources public apiVersion: string; // Data is the serialized representation of the state. public data?: apimachineryPkgRuntime.RawExtension; // Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds public kind: string; // Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata public metadata: apisMetaV1.ObjectMeta; // Revision indicates the revision of the state represented by Data. public revision: number; constructor(desc: ControllerRevision.Interface) { this.apiVersion = ControllerRevision.apiVersion; this.data = desc.data; this.kind = ControllerRevision.kind; this.metadata = desc.metadata; this.revision = desc.revision; } } export function isControllerRevision(o: any): o is ControllerRevision { return ( o && o.apiVersion === ControllerRevision.apiVersion && o.kind === ControllerRevision.kind ); } export namespace ControllerRevision { export const apiVersion = "apps/v1beta1"; export const group = "apps"; export const version = "v1beta1"; export const kind = "ControllerRevision"; // DEPRECATED - This group version of ControllerRevision is deprecated by apps/v1beta2/ControllerRevision. See the release notes for more information. ControllerRevision implements an immutable snapshot of state data. Clients are responsible for serializing and deserializing the objects that contain their internal state. Once a ControllerRevision has been successfully created, it can not be updated. The API Server will fail validation of all requests that attempt to mutate the Data field. ControllerRevisions may, however, be deleted. Note that, due to its use by both the DaemonSet and StatefulSet controllers for update and rollback, this object is beta. However, it may be subject to name and representation changes in future releases, and clients should not depend on its stability. It is primarily for internal use by controllers. export interface Interface { // Data is the serialized representation of the state. data?: apimachineryPkgRuntime.RawExtension; // Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata metadata: apisMetaV1.ObjectMeta; // Revision indicates the revision of the state represented by Data. revision: number; } } // ControllerRevisionList is a resource containing a list of ControllerRevision objects. export class ControllerRevisionList { // APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources public apiVersion: string; // Items is the list of ControllerRevisions public items: ControllerRevision[]; // Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds public kind: string; // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata public metadata?: apisMetaV1.ListMeta; constructor(desc: ControllerRevisionList) { this.apiVersion = ControllerRevisionList.apiVersion; this.items = desc.items.map(i => new ControllerRevision(i)); this.kind = ControllerRevisionList.kind; this.metadata = desc.metadata; } } export function isControllerRevisionList(o: any): o is ControllerRevisionList { return ( o && o.apiVersion === ControllerRevisionList.apiVersion && o.kind === ControllerRevisionList.kind ); } export namespace ControllerRevisionList { export const apiVersion = "apps/v1beta1"; export const group = "apps"; export const version = "v1beta1"; export const kind = "ControllerRevisionList"; // ControllerRevisionList is a resource containing a list of ControllerRevision objects. export interface Interface { // Items is the list of ControllerRevisions items: ControllerRevision[]; // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata metadata?: apisMetaV1.ListMeta; } } // DEPRECATED - This group version of Deployment is deprecated by apps/v1beta2/Deployment. See the release notes for more information. Deployment enables declarative updates for Pods and ReplicaSets. export class Deployment implements KubernetesObject { // APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources public apiVersion: string; // Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds public kind: string; // Standard object metadata. public metadata: apisMetaV1.ObjectMeta; // Specification of the desired behavior of the Deployment. public spec?: DeploymentSpec; // Most recently observed status of the Deployment. public status?: DeploymentStatus; constructor(desc: Deployment.Interface) { this.apiVersion = Deployment.apiVersion; this.kind = Deployment.kind; this.metadata = desc.metadata; this.spec = desc.spec; this.status = desc.status; } } export function isDeployment(o: any): o is Deployment { return ( o && o.apiVersion === Deployment.apiVersion && o.kind === Deployment.kind ); } export namespace Deployment { export const apiVersion = "apps/v1beta1"; export const group = "apps"; export const version = "v1beta1"; export const kind = "Deployment"; // named constructs a Deployment with metadata.name set to name. export function named(name: string): Deployment { return new Deployment({ metadata: { name } }); } // DEPRECATED - This group version of Deployment is deprecated by apps/v1beta2/Deployment. See the release notes for more information. Deployment enables declarative updates for Pods and ReplicaSets. export interface Interface { // Standard object metadata. metadata: apisMetaV1.ObjectMeta; // Specification of the desired behavior of the Deployment. spec?: DeploymentSpec; // Most recently observed status of the Deployment. status?: DeploymentStatus; } } // DeploymentCondition describes the state of a deployment at a certain point. export class DeploymentCondition { // Last time the condition transitioned from one status to another. public lastTransitionTime?: apisMetaV1.Time; // The last time this condition was updated. public lastUpdateTime?: apisMetaV1.Time; // A human readable message indicating details about the transition. public message?: string; // The reason for the condition's last transition. public reason?: string; // Status of the condition, one of True, False, Unknown. public status: string; // Type of deployment condition. public type: string; constructor(desc: DeploymentCondition) { this.lastTransitionTime = desc.lastTransitionTime; this.lastUpdateTime = desc.lastUpdateTime; this.message = desc.message; this.reason = desc.reason; this.status = desc.status; this.type = desc.type; } } // DeploymentList is a list of Deployments. export class DeploymentList { // APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources public apiVersion: string; // Items is the list of Deployments. public items: Deployment[]; // Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds public kind: string; // Standard list metadata. public metadata?: apisMetaV1.ListMeta; constructor(desc: DeploymentList) { this.apiVersion = DeploymentList.apiVersion; this.items = desc.items.map(i => new Deployment(i)); this.kind = DeploymentList.kind; this.metadata = desc.metadata; } } export function isDeploymentList(o: any): o is DeploymentList { return ( o && o.apiVersion === DeploymentList.apiVersion && o.kind === DeploymentList.kind ); } export namespace DeploymentList { export const apiVersion = "apps/v1beta1"; export const group = "apps"; export const version = "v1beta1"; export const kind = "DeploymentList"; // DeploymentList is a list of Deployments. export interface Interface { // Items is the list of Deployments. items: Deployment[]; // Standard list metadata. metadata?: apisMetaV1.ListMeta; } } // DEPRECATED. DeploymentRollback stores the information required to rollback a deployment. export class DeploymentRollback { // APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources public apiVersion: string; // Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds public kind: string; // Required: This must match the Name of a deployment. public name: string; // The config of this deployment rollback. public rollbackTo: RollbackConfig; // The annotations to be updated to a deployment public updatedAnnotations?: { [key: string]: string }; constructor(desc: DeploymentRollback) { this.apiVersion = DeploymentRollback.apiVersion; this.kind = DeploymentRollback.kind; this.name = desc.name; this.rollbackTo = desc.rollbackTo; this.updatedAnnotations = desc.updatedAnnotations; } } export function isDeploymentRollback(o: any): o is DeploymentRollback { return ( o && o.apiVersion === DeploymentRollback.apiVersion && o.kind === DeploymentRollback.kind ); } export namespace DeploymentRollback { export const apiVersion = "apps/v1beta1"; export const group = "apps"; export const version = "v1beta1"; export const kind = "DeploymentRollback"; // DEPRECATED. DeploymentRollback stores the information required to rollback a deployment. export interface Interface { // Required: This must match the Name of a deployment. name: string; // The config of this deployment rollback. rollbackTo: RollbackConfig; // The annotations to be updated to a deployment updatedAnnotations?: { [key: string]: string }; } } // DeploymentSpec is the specification of the desired behavior of the Deployment. export class DeploymentSpec { // Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready) public minReadySeconds?: number; // Indicates that the deployment is paused. public paused?: boolean; // The maximum time in seconds for a deployment to make progress before it is considered to be failed. The deployment controller will continue to process failed deployments and a condition with a ProgressDeadlineExceeded reason will be surfaced in the deployment status. Note that progress will not be estimated during the time a deployment is paused. Defaults to 600s. public progressDeadlineSeconds?: number; // Number of desired pods. This is a pointer to distinguish between explicit zero and not specified. Defaults to 1. public replicas?: number; // The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 2. public revisionHistoryLimit?: number; // DEPRECATED. The config this deployment is rolling back to. Will be cleared after rollback is done. public rollbackTo?: RollbackConfig; // Label selector for pods. Existing ReplicaSets whose pods are selected by this will be the ones affected by this deployment. public selector?: apisMetaV1.LabelSelector; // The deployment strategy to use to replace existing pods with new ones. public strategy?: DeploymentStrategy; // Template describes the pods that will be created. public template: apiCoreV1.PodTemplateSpec; constructor(desc: DeploymentSpec) { this.minReadySeconds = desc.minReadySeconds; this.paused = desc.paused; this.progressDeadlineSeconds = desc.progressDeadlineSeconds; this.replicas = desc.replicas; this.revisionHistoryLimit = desc.revisionHistoryLimit; this.rollbackTo = desc.rollbackTo; this.selector = desc.selector; this.strategy = desc.strategy; this.template = desc.template; } } // DeploymentStatus is the most recently observed status of the Deployment. export class DeploymentStatus { // Total number of available pods (ready for at least minReadySeconds) targeted by this deployment. public availableReplicas?: number; // Count of hash collisions for the Deployment. The Deployment controller uses this field as a collision avoidance mechanism when it needs to create the name for the newest ReplicaSet. public collisionCount?: number; // Represents the latest available observations of a deployment's current state. public conditions?: DeploymentCondition[]; // The generation observed by the deployment controller. public observedGeneration?: number; // Total number of ready pods targeted by this deployment. public readyReplicas?: number; // Total number of non-terminated pods targeted by this deployment (their labels match the selector). public replicas?: number; // Total number of unavailable pods targeted by this deployment. This is the total number of pods that are still required for the deployment to have 100% available capacity. They may either be pods that are running but not yet available or pods that still have not been created. public unavailableReplicas?: number; // Total number of non-terminated pods targeted by this deployment that have the desired template spec. public updatedReplicas?: number; } // DeploymentStrategy describes how to replace existing pods with new ones. export class DeploymentStrategy { // Rolling update config params. Present only if DeploymentStrategyType = RollingUpdate. public rollingUpdate?: RollingUpdateDeployment; // Type of deployment. Can be "Recreate" or "RollingUpdate". Default is RollingUpdate. public type?: string; } // DEPRECATED. export class RollbackConfig { // The revision to rollback to. If set to 0, rollback to the last revision. public revision?: number; } // Spec to control the desired behavior of rolling update. export class RollingUpdateDeployment { // The maximum number of pods that can be scheduled above the desired number of pods. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is calculated from percentage by rounding up. Defaults to 25%. Example: when this is set to 30%, the new ReplicaSet can be scaled up immediately when the rolling update starts, such that the total number of old and new pods do not exceed 130% of desired pods. Once old pods have been killed, new ReplicaSet can be scaled up further, ensuring that total number of pods running at any time during the update is at most 130% of desired pods. public maxSurge?: pkgUtilIntstr.IntOrString; // The maximum number of pods that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). Absolute number is calculated from percentage by rounding down. This can not be 0 if MaxSurge is 0. Defaults to 25%. Example: when this is set to 30%, the old ReplicaSet can be scaled down to 70% of desired pods immediately when the rolling update starts. Once new pods are ready, old ReplicaSet can be scaled down further, followed by scaling up the new ReplicaSet, ensuring that the total number of pods available at all times during the update is at least 70% of desired pods. public maxUnavailable?: pkgUtilIntstr.IntOrString; } // RollingUpdateStatefulSetStrategy is used to communicate parameter for RollingUpdateStatefulSetStrategyType. export class RollingUpdateStatefulSetStrategy { // Partition indicates the ordinal at which the StatefulSet should be partitioned. public partition?: number; } // Scale represents a scaling request for a resource. export class Scale implements KubernetesObject { // APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources public apiVersion: string; // Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds public kind: string; // Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata. public metadata: apisMetaV1.ObjectMeta; // defines the behavior of the scale. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status. public spec?: ScaleSpec; // current status of the scale. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status. Read-only. public status?: ScaleStatus; constructor(desc: Scale.Interface) { this.apiVersion = Scale.apiVersion; this.kind = Scale.kind; this.metadata = desc.metadata; this.spec = desc.spec; this.status = desc.status; } } export function isScale(o: any): o is Scale { return o && o.apiVersion === Scale.apiVersion && o.kind === Scale.kind; } export namespace Scale { export const apiVersion = "apps/v1beta1"; export const group = "apps"; export const version = "v1beta1"; export const kind = "Scale"; // named constructs a Scale with metadata.name set to name. export function named(name: string): Scale { return new Scale({ metadata: { name } }); } // Scale represents a scaling request for a resource. export interface Interface { // Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata. metadata: apisMetaV1.ObjectMeta; // defines the behavior of the scale. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status. spec?: ScaleSpec; // current status of the scale. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status. Read-only. status?: ScaleStatus; } } // ScaleSpec describes the attributes of a scale subresource export class ScaleSpec { // desired number of instances for the scaled object. public replicas?: number; } // ScaleStatus represents the current status of a scale subresource. export class ScaleStatus { // actual number of observed instances of the scaled object. public replicas: number; // label query over pods that should match the replicas count. More info: http://kubernetes.io/docs/user-guide/labels#label-selectors public selector?: { [key: string]: string }; // label selector for pods that should match the replicas count. This is a serializated version of both map-based and more expressive set-based selectors. This is done to avoid introspection in the clients. The string will be in the same format as the query-param syntax. If the target type only supports map-based selectors, both this field and map-based selector field are populated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors public targetSelector?: string; constructor(desc: ScaleStatus) { this.replicas = desc.replicas; this.selector = desc.selector; this.targetSelector = desc.targetSelector; } } // DEPRECATED - This group version of StatefulSet is deprecated by apps/v1beta2/StatefulSet. See the release notes for more information. StatefulSet represents a set of pods with consistent identities. Identities are defined as: // - Network: A single stable DNS and hostname. // - Storage: As many VolumeClaims as requested. // The StatefulSet guarantees that a given network identity will always map to the same storage identity. export class StatefulSet implements KubernetesObject { // APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources public apiVersion: string; // Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds public kind: string; public metadata: apisMetaV1.ObjectMeta; // Spec defines the desired identities of pods in this set. public spec?: StatefulSetSpec; // Status is the current status of Pods in this StatefulSet. This data may be out of date by some window of time. public status?: StatefulSetStatus; constructor(desc: StatefulSet.Interface) { this.apiVersion = StatefulSet.apiVersion; this.kind = StatefulSet.kind; this.metadata = desc.metadata; this.spec = desc.spec; this.status = desc.status; } } export function isStatefulSet(o: any): o is StatefulSet { return ( o && o.apiVersion === StatefulSet.apiVersion && o.kind === StatefulSet.kind ); } export namespace StatefulSet { export const apiVersion = "apps/v1beta1"; export const group = "apps"; export const version = "v1beta1"; export const kind = "StatefulSet"; // named constructs a StatefulSet with metadata.name set to name. export function named(name: string): StatefulSet { return new StatefulSet({ metadata: { name } }); } // DEPRECATED - This group version of StatefulSet is deprecated by apps/v1beta2/StatefulSet. See the release notes for more information. StatefulSet represents a set of pods with consistent identities. Identities are defined as: // - Network: A single stable DNS and hostname. // - Storage: As many VolumeClaims as requested. // The StatefulSet guarantees that a given network identity will always map to the same storage identity. export interface Interface { metadata: apisMetaV1.ObjectMeta; // Spec defines the desired identities of pods in this set. spec?: StatefulSetSpec; // Status is the current status of Pods in this StatefulSet. This data may be out of date by some window of time. status?: StatefulSetStatus; } } // StatefulSetCondition describes the state of a statefulset at a certain point. export class StatefulSetCondition { // Last time the condition transitioned from one status to another. public lastTransitionTime?: apisMetaV1.Time; // A human readable message indicating details about the transition. public message?: string; // The reason for the condition's last transition. public reason?: string; // Status of the condition, one of True, False, Unknown. public status: string; // Type of statefulset condition. public type: string; constructor(desc: StatefulSetCondition) { this.lastTransitionTime = desc.lastTransitionTime; this.message = desc.message; this.reason = desc.reason; this.status = desc.status; this.type = desc.type; } } // StatefulSetList is a collection of StatefulSets. export class StatefulSetList { // APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources public apiVersion: string; public items: StatefulSet[]; // Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds public kind: string; public metadata?: apisMetaV1.ListMeta; constructor(desc: StatefulSetList) { this.apiVersion = StatefulSetList.apiVersion; this.items = desc.items.map(i => new StatefulSet(i)); this.kind = StatefulSetList.kind; this.metadata = desc.metadata; } } export function isStatefulSetList(o: any): o is StatefulSetList { return ( o && o.apiVersion === StatefulSetList.apiVersion && o.kind === StatefulSetList.kind ); } export namespace StatefulSetList { export const apiVersion = "apps/v1beta1"; export const group = "apps"; export const version = "v1beta1"; export const kind = "StatefulSetList"; // StatefulSetList is a collection of StatefulSets. export interface Interface { items: StatefulSet[]; metadata?: apisMetaV1.ListMeta; } } // A StatefulSetSpec is the specification of a StatefulSet. export class StatefulSetSpec { // podManagementPolicy controls how pods are created during initial scale up, when replacing pods on nodes, or when scaling down. The default policy is `OrderedReady`, where pods are created in increasing order (pod-0, then pod-1, etc) and the controller will wait until each pod is ready before continuing. When scaling down, the pods are removed in the opposite order. The alternative policy is `Parallel` which will create pods in parallel to match the desired scale without waiting, and on scale down will delete all pods at once. public podManagementPolicy?: string; // replicas is the desired number of replicas of the given Template. These are replicas in the sense that they are instantiations of the same Template, but individual replicas also have a consistent identity. If unspecified, defaults to 1. public replicas?: number; // revisionHistoryLimit is the maximum number of revisions that will be maintained in the StatefulSet's revision history. The revision history consists of all revisions not represented by a currently applied StatefulSetSpec version. The default value is 10. public revisionHistoryLimit?: number; // selector is a label query over pods that should match the replica count. If empty, defaulted to labels on the pod template. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors public selector?: apisMetaV1.LabelSelector; // serviceName is the name of the service that governs this StatefulSet. This service must exist before the StatefulSet, and is responsible for the network identity of the set. Pods get DNS/hostnames that follow the pattern: pod-specific-string.serviceName.default.svc.cluster.local where "pod-specific-string" is managed by the StatefulSet controller. public serviceName: string; // template is the object that describes the pod that will be created if insufficient replicas are detected. Each pod stamped out by the StatefulSet will fulfill this Template, but have a unique identity from the rest of the StatefulSet. public template: apiCoreV1.PodTemplateSpec; // updateStrategy indicates the StatefulSetUpdateStrategy that will be employed to update Pods in the StatefulSet when a revision is made to Template. public updateStrategy?: StatefulSetUpdateStrategy; // volumeClaimTemplates is a list of claims that pods are allowed to reference. The StatefulSet controller is responsible for mapping network identities to claims in a way that maintains the identity of a pod. Every claim in this list must have at least one matching (by name) volumeMount in one container in the template. A claim in this list takes precedence over any volumes in the template, with the same name. public volumeClaimTemplates?: apiCoreV1.PersistentVolumeClaim[]; constructor(desc: StatefulSetSpec) { this.podManagementPolicy = desc.podManagementPolicy; this.replicas = desc.replicas; this.revisionHistoryLimit = desc.revisionHistoryLimit; this.selector = desc.selector; this.serviceName = desc.serviceName; this.template = desc.template; this.updateStrategy = desc.updateStrategy; this.volumeClaimTemplates = desc.volumeClaimTemplates !== undefined ? desc.volumeClaimTemplates.map( i => new apiCoreV1.PersistentVolumeClaim(i) ) : undefined; } } // StatefulSetStatus represents the current state of a StatefulSet. export class StatefulSetStatus { // collisionCount is the count of hash collisions for the StatefulSet. The StatefulSet controller uses this field as a collision avoidance mechanism when it needs to create the name for the newest ControllerRevision. public collisionCount?: number; // Represents the latest available observations of a statefulset's current state. public conditions?: StatefulSetCondition[]; // currentReplicas is the number of Pods created by the StatefulSet controller from the StatefulSet version indicated by currentRevision. public currentReplicas?: number; // currentRevision, if not empty, indicates the version of the StatefulSet used to generate Pods in the sequence [0,currentReplicas). public currentRevision?: string; // observedGeneration is the most recent generation observed for this StatefulSet. It corresponds to the StatefulSet's generation, which is updated on mutation by the API Server. public observedGeneration?: number; // readyReplicas is the number of Pods created by the StatefulSet controller that have a Ready Condition. public readyReplicas?: number; // replicas is the number of Pods created by the StatefulSet controller. public replicas: number; // updateRevision, if not empty, indicates the version of the StatefulSet used to generate Pods in the sequence [replicas-updatedReplicas,replicas) public updateRevision?: string; // updatedReplicas is the number of Pods created by the StatefulSet controller from the StatefulSet version indicated by updateRevision. public updatedReplicas?: number; constructor(desc: StatefulSetStatus) { this.collisionCount = desc.collisionCount; this.conditions = desc.conditions; this.currentReplicas = desc.currentReplicas; this.currentRevision = desc.currentRevision; this.observedGeneration = desc.observedGeneration; this.readyReplicas = desc.readyReplicas; this.replicas = desc.replicas; this.updateRevision = desc.updateRevision; this.updatedReplicas = desc.updatedReplicas; } } // StatefulSetUpdateStrategy indicates the strategy that the StatefulSet controller will use to perform updates. It includes any additional parameters necessary to perform the update for the indicated strategy. export class StatefulSetUpdateStrategy { // RollingUpdate is used to communicate parameters when Type is RollingUpdateStatefulSetStrategyType. public rollingUpdate?: RollingUpdateStatefulSetStrategy; // Type indicates the type of the StatefulSetUpdateStrategy. public type?: string; }
the_stack
import { AfterContentInit, Component, ContentChild, ContentChildren, ElementRef, EventEmitter, HostBinding, HostListener, Inject, Injector, Input, OnDestroy, Output, QueryList, Renderer2, ViewEncapsulation, } from '@angular/core'; import {MatButton} from '@angular/material/button'; import {DOCUMENT} from '@angular/common'; import {forkJoin, fromEvent, Subscription} from 'rxjs'; import {take} from 'rxjs/operators'; const Z_INDEX_ITEM = 23; export type Direction = 'up' | 'down' | 'left' | 'right'; export type AnimationMode = 'fling' | 'scale'; @Component({ selector: 'eco-fab-speed-dial-actions', template: ` <ng-content select="[mat-mini-fab]" *ngIf="miniFabVisible"></ng-content>`, }) export class EcoFabSpeedDialActionsComponent implements AfterContentInit { private _parent: EcoFabSpeedDialComponent; @ContentChildren(MatButton) _buttons: QueryList<MatButton>; /** * Whether the min-fab button exist in DOM */ public miniFabVisible = false; /** * The timeout ID for the callback to show the mini-fab buttons */ private showMiniFabAnimation: ReturnType<typeof setTimeout>; /** * When we will remove mini-fab buttons from DOM, after the animation is complete */ private hideMiniFab: Subscription | null; constructor(injector: Injector, private renderer: Renderer2) { this._parent = injector.get(EcoFabSpeedDialComponent); } ngAfterContentInit(): void { this._buttons.changes.subscribe(() => { this.initButtonStates(); this._parent.setActionsVisibility(); }); this.initButtonStates(); } private initButtonStates(): void { this._buttons.forEach((button, i) => { this.renderer.addClass(button._getHostElement(), 'eco-fab-action-item'); this.changeElementStyle(button._getHostElement(), 'z-index', '' + (Z_INDEX_ITEM - i)); }); } show(): void { if (!this._buttons) { return; } this.resetAnimationState(); this.miniFabVisible = true; this.showMiniFabAnimation = setTimeout(() => { this._buttons.forEach((button, i) => { let transitionDelay = 0; let transform; if (this._parent.animationMode === 'scale') { // Incremental transition delay of 65ms for each action button transitionDelay = 3 + 65 * i; transform = 'scale(1)'; } else { transform = this.getTranslateFunction('0'); } const hostElement = button._getHostElement(); this.changeElementStyle(hostElement, 'transition-delay', transitionDelay + 'ms'); this.changeElementStyle(hostElement, 'opacity', '1'); this.changeElementStyle(hostElement, 'transform', transform); }); }, 50); // Be sure that *ngIf can show elements before trying to animate them } private resetAnimationState(): void { clearTimeout(this.showMiniFabAnimation); if (this.hideMiniFab) { this.hideMiniFab.unsubscribe(); this.hideMiniFab = null; } } hide(): void { if (!this._buttons) { return; } this.resetAnimationState(); const obs = this._buttons.map((button, i) => { let opacity = '1'; let transitionDelay = 0; let transform; if (this._parent.animationMode === 'scale') { transitionDelay = 3 - 65 * i; transform = 'scale(0)'; opacity = '0'; } else { transform = this.getTranslateFunction(55 * (i + 1) - i * 5 + 'px'); } const hostElement = button._getHostElement(); this.changeElementStyle(hostElement, 'transition-delay', transitionDelay + 'ms'); this.changeElementStyle(hostElement, 'opacity', opacity); this.changeElementStyle(hostElement, 'transform', transform); return fromEvent(hostElement, 'transitionend').pipe(take(1)); }); // Wait for all animation to finish, then destroy their elements this.hideMiniFab = forkJoin(obs).subscribe(() => (this.miniFabVisible = false)); } private getTranslateFunction(value: string): string { const dir = this._parent.direction; const translateFn = dir === 'up' || dir === 'down' ? 'translateY' : 'translateX'; const sign = dir === 'down' || dir === 'right' ? '-' : ''; return translateFn + '(' + sign + value + ')'; } private changeElementStyle(elem: any, style: string, value: string) { // FIXME - Find a way to create a "wrapper" around the action button(s) provided by the user, so we don't change it's style tag this.renderer.setStyle(elem, style, value); } } /** @dynamic @see https://github.com/angular/angular/issues/20351#issuecomment-344009887 */ @Component({ selector: 'eco-fab-speed-dial', template: ` <div class="eco-fab-speed-dial-container"> <ng-content select="eco-fab-speed-dial-trigger"></ng-content> <ng-content select="eco-fab-speed-dial-actions"></ng-content> </div> `, styleUrls: ['fab-speed-dial.scss'], encapsulation: ViewEncapsulation.None, }) export class EcoFabSpeedDialComponent implements OnDestroy, AfterContentInit { private isInitialized = false; private _direction: Direction = 'up'; private _open = false; private _animationMode: AnimationMode = 'fling'; private _fixed = false; private _documentClickUnlistener: (() => void) | null = null; /** * Whether this speed dial is fixed on screen (user cannot change it by clicking) */ @Input() get fixed(): boolean { return this._fixed; } set fixed(fixed: boolean) { this._fixed = fixed; this._processOutsideClickState(); } /** * Whether this speed dial is opened */ @HostBinding('class.eco-opened') @Input() get open(): boolean { return this._open; } set open(open: boolean) { const previousOpen = this._open; this._open = open; if (previousOpen !== this._open) { this.openChange.emit(this._open); if (this.isInitialized) { this.setActionsVisibility(); } } } /** * The direction of the speed dial. Can be 'up', 'down', 'left' or 'right' */ @Input() get direction(): Direction { return this._direction; } set direction(direction: Direction) { const previousDirection = this._direction; this._direction = direction; if (previousDirection !== this.direction) { this._setElementClass(previousDirection, false); this._setElementClass(this.direction, true); if (this.isInitialized) { this.setActionsVisibility(); } } } /** * The animation mode to open the speed dial. Can be 'fling' or 'scale' */ @Input() get animationMode(): AnimationMode { return this._animationMode; } set animationMode(animationMode: AnimationMode) { const previousAnimationMode = this._animationMode; this._animationMode = animationMode; if (previousAnimationMode !== this._animationMode) { this._setElementClass(previousAnimationMode, false); this._setElementClass(this.animationMode, true); if (this.isInitialized) { // To start another detect lifecycle and force the "close" on the action buttons Promise.resolve(null).then(() => (this.open = false)); } } } @Output() openChange: EventEmitter<boolean> = new EventEmitter<boolean>(); @ContentChild(EcoFabSpeedDialActionsComponent) _childActions: EcoFabSpeedDialActionsComponent; constructor( private elementRef: ElementRef, private renderer: Renderer2, @Inject(DOCUMENT) private document: Document, ) {} ngAfterContentInit(): void { this.isInitialized = true; this.setActionsVisibility(); this._setElementClass(this.direction, true); this._setElementClass(this.animationMode, true); } ngOnDestroy() { this._unsetDocumentClickListener(); } /** * Toggle the open state of this speed dial */ public toggle(): void { this.open = !this.open; } @HostListener('click') _onClick(): void { if (!this.fixed && this.open) { this.open = false; } } setActionsVisibility(): void { if (!this._childActions) { return; } if (this.open) { this._childActions.show(); } else { this._childActions.hide(); } this._processOutsideClickState(); } private _setElementClass(elemClass: string, isAdd: boolean): void { const finalClass = `eco-${elemClass}`; if (isAdd) { this.renderer.addClass(this.elementRef.nativeElement, finalClass); } else { this.renderer.removeClass(this.elementRef.nativeElement, finalClass); } } private _processOutsideClickState() { if (!this.fixed && this.open) { this._setDocumentClickListener(); } else { this._unsetDocumentClickListener(); } } private _setDocumentClickListener() { if (!this._documentClickUnlistener) { this._documentClickUnlistener = this.renderer.listen(this.document, 'click', () => { this.open = false; }); } } private _unsetDocumentClickListener() { if (this._documentClickUnlistener) { this._documentClickUnlistener(); this._documentClickUnlistener = null; } } } @Component({ selector: 'eco-fab-speed-dial-trigger', template: ` <ng-content select="[mat-fab]"></ng-content>`, }) export class EcoFabSpeedDialTriggerComponent { private _parent: EcoFabSpeedDialComponent; /** * Whether this trigger should spin (360dg) while opening the speed dial */ @HostBinding('class.eco-spin') get sp() { return this.spin; } @Input() spin = false; constructor(injector: Injector) { this._parent = injector.get(EcoFabSpeedDialComponent); } @HostListener('click', ['$event']) _onClick(event: Event): void { if (!this._parent.fixed) { this._parent.toggle(); event.stopPropagation(); } } }
the_stack
import { ILinkifier2, ILinkProvider, IBufferCellPosition, ILink, ILinkifierEvent, ILinkDecorations, ILinkWithState } from 'browser/Types'; import { IDisposable } from 'common/Types'; import { IMouseService, IRenderService } from './services/Services'; import { IBufferService } from 'common/services/Services'; import { EventEmitter, IEvent } from 'common/EventEmitter'; import { Disposable, getDisposeArrayDisposable, disposeArray } from 'common/Lifecycle'; import { addDisposableDomListener } from 'browser/Lifecycle'; export class Linkifier2 extends Disposable implements ILinkifier2 { private _element: HTMLElement | undefined; private _mouseService: IMouseService | undefined; private _renderService: IRenderService | undefined; private _linkProviders: ILinkProvider[] = []; public get currentLink(): ILinkWithState | undefined { return this._currentLink; } protected _currentLink: ILinkWithState | undefined; private _lastMouseEvent: MouseEvent | undefined; private _linkCacheDisposables: IDisposable[] = []; private _lastBufferCell: IBufferCellPosition | undefined; private _isMouseOut: boolean = true; private _activeProviderReplies: Map<Number, ILinkWithState[] | undefined> | undefined; private _activeLine: number = -1; private _onShowLinkUnderline = this.register(new EventEmitter<ILinkifierEvent>()); public get onShowLinkUnderline(): IEvent<ILinkifierEvent> { return this._onShowLinkUnderline.event; } private _onHideLinkUnderline = this.register(new EventEmitter<ILinkifierEvent>()); public get onHideLinkUnderline(): IEvent<ILinkifierEvent> { return this._onHideLinkUnderline.event; } constructor( @IBufferService private readonly _bufferService: IBufferService ) { super(); this.register(getDisposeArrayDisposable(this._linkCacheDisposables)); } public registerLinkProvider(linkProvider: ILinkProvider): IDisposable { this._linkProviders.push(linkProvider); return { dispose: () => { // Remove the link provider from the list const providerIndex = this._linkProviders.indexOf(linkProvider); if (providerIndex !== -1) { this._linkProviders.splice(providerIndex, 1); } } }; } public attachToDom(element: HTMLElement, mouseService: IMouseService, renderService: IRenderService): void { this._element = element; this._mouseService = mouseService; this._renderService = renderService; this.register(addDisposableDomListener(this._element, 'mouseleave', () => { this._isMouseOut = true; this._clearCurrentLink(); })); this.register(addDisposableDomListener(this._element, 'mousemove', this._onMouseMove.bind(this))); this.register(addDisposableDomListener(this._element, 'click', this._onClick.bind(this))); } private _onMouseMove(event: MouseEvent): void { this._lastMouseEvent = event; if (!this._element || !this._mouseService) { return; } const position = this._positionFromMouseEvent(event, this._element, this._mouseService); if (!position) { return; } this._isMouseOut = false; // Ignore the event if it's an embedder created hover widget const composedPath = event.composedPath() as HTMLElement[]; for (let i = 0; i < composedPath.length; i++) { const target = composedPath[i]; // Hit Terminal.element, break and continue if (target.classList.contains('xterm')) { break; } // It's a hover, don't respect hover event if (target.classList.contains('xterm-hover')) { return; } } if (!this._lastBufferCell || (position.x !== this._lastBufferCell.x || position.y !== this._lastBufferCell.y)) { this._onHover(position); this._lastBufferCell = position; } } private _onHover(position: IBufferCellPosition): void { // TODO: This currently does not cache link provider results across wrapped lines, activeLine should be something like `activeRange: {startY, endY}` // Check if we need to clear the link if (this._activeLine !== position.y) { this._clearCurrentLink(); this._askForLink(position, false); return; } // Check the if the link is in the mouse position const isCurrentLinkInPosition = this._currentLink && this._linkAtPosition(this._currentLink.link, position); if (!isCurrentLinkInPosition) { this._clearCurrentLink(); this._askForLink(position, true); } } private _askForLink(position: IBufferCellPosition, useLineCache: boolean): void { if (!this._activeProviderReplies || !useLineCache) { this._activeProviderReplies?.forEach(reply => { reply?.forEach(linkWithState => { if (linkWithState.link.dispose) { linkWithState.link.dispose(); } }); }); this._activeProviderReplies = new Map(); this._activeLine = position.y; } let linkProvided = false; // There is no link cached, so ask for one this._linkProviders.forEach((linkProvider, i) => { if (useLineCache) { const existingReply = this._activeProviderReplies?.get(i); // If there isn't a reply, the provider hasn't responded yet. // TODO: If there isn't a reply yet it means that the provider is still resolving. Ensuring // provideLinks isn't triggered again saves ILink.hover firing twice though. This probably // needs promises to get fixed if (existingReply) { linkProvided = this._checkLinkProviderResult(i, position, linkProvided); } } else { linkProvider.provideLinks(position.y, (links: ILink[] | undefined) => { if (this._isMouseOut) { return; } const linksWithState: ILinkWithState[] | undefined = links?.map(link => ({ link })); this._activeProviderReplies?.set(i, linksWithState); linkProvided = this._checkLinkProviderResult(i, position, linkProvided); // If all providers have responded, remove lower priority links that intersect ranges of // higher priority links if (this._activeProviderReplies?.size === this._linkProviders.length) { this._removeIntersectingLinks(position.y, this._activeProviderReplies); } }); } }); } private _removeIntersectingLinks(y: number, replies: Map<Number, ILinkWithState[] | undefined>): void { const occupiedCells = new Set<number>(); for (let i = 0; i < replies.size; i++) { const providerReply = replies.get(i); if (!providerReply) { continue; } for (let i = 0; i < providerReply.length; i++) { const linkWithState = providerReply[i]; const startX = linkWithState.link.range.start.y < y ? 0 : linkWithState.link.range.start.x; const endX = linkWithState.link.range.end.y > y ? this._bufferService.cols : linkWithState.link.range.end.x; for (let x = startX; x <= endX; x++) { if (occupiedCells.has(x)) { providerReply.splice(i--, 1); break; } occupiedCells.add(x); } } } } private _checkLinkProviderResult(index: number, position: IBufferCellPosition, linkProvided: boolean): boolean { if (!this._activeProviderReplies) { return linkProvided; } const links = this._activeProviderReplies.get(index); // Check if every provider before this one has come back undefined let hasLinkBefore = false; for (let j = 0; j < index; j++) { if (!this._activeProviderReplies.has(j) || this._activeProviderReplies.get(j)) { hasLinkBefore = true; } } // If all providers with higher priority came back undefined, then this provider's link for // the position should be used if (!hasLinkBefore && links) { const linkAtPosition = links.find(link => this._linkAtPosition(link.link, position)); if (linkAtPosition) { linkProvided = true; this._handleNewLink(linkAtPosition); } } // Check if all the providers have responded if (this._activeProviderReplies.size === this._linkProviders.length && !linkProvided) { // Respect the order of the link providers for (let j = 0; j < this._activeProviderReplies.size; j++) { const currentLink = this._activeProviderReplies.get(j)?.find(link => this._linkAtPosition(link.link, position)); if (currentLink) { linkProvided = true; this._handleNewLink(currentLink); break; } } } return linkProvided; } private _onClick(event: MouseEvent): void { if (!this._element || !this._mouseService || !this._currentLink) { return; } const position = this._positionFromMouseEvent(event, this._element, this._mouseService); if (!position) { return; } if (this._linkAtPosition(this._currentLink.link, position)) { this._currentLink.link.activate(event, this._currentLink.link.text); } } private _clearCurrentLink(startRow?: number, endRow?: number): void { if (!this._element || !this._currentLink || !this._lastMouseEvent) { return; } // If we have a start and end row, check that the link is within it if (!startRow || !endRow || (this._currentLink.link.range.start.y >= startRow && this._currentLink.link.range.end.y <= endRow)) { this._linkLeave(this._element, this._currentLink.link, this._lastMouseEvent); this._currentLink = undefined; disposeArray(this._linkCacheDisposables); } } private _handleNewLink(linkWithState: ILinkWithState): void { if (!this._element || !this._lastMouseEvent || !this._mouseService) { return; } const position = this._positionFromMouseEvent(this._lastMouseEvent, this._element, this._mouseService); if (!position) { return; } // Trigger hover if the we have a link at the position if (this._linkAtPosition(linkWithState.link, position)) { this._currentLink = linkWithState; this._currentLink.state = { decorations: { underline: linkWithState.link.decorations === undefined ? true : linkWithState.link.decorations.underline, pointerCursor: linkWithState.link.decorations === undefined ? true : linkWithState.link.decorations.pointerCursor }, isHovered: true }; this._linkHover(this._element, linkWithState.link, this._lastMouseEvent); // Add listener for tracking decorations changes linkWithState.link.decorations = {} as ILinkDecorations; Object.defineProperties(linkWithState.link.decorations, { pointerCursor: { get: () => this._currentLink?.state?.decorations.pointerCursor, set: v => { if (this._currentLink?.state && this._currentLink.state.decorations.pointerCursor !== v) { this._currentLink.state.decorations.pointerCursor = v; if (this._currentLink.state.isHovered) { this._element?.classList.toggle('xterm-cursor-pointer', v); } } } }, underline: { get: () => this._currentLink?.state?.decorations.underline, set: v => { if (this._currentLink?.state && this._currentLink?.state?.decorations.underline !== v) { this._currentLink.state.decorations.underline = v; if (this._currentLink.state.isHovered) { this._fireUnderlineEvent(linkWithState.link, v); } } } } }); // Add listener for rerendering if (this._renderService) { this._linkCacheDisposables.push(this._renderService.onRenderedBufferChange(e => { // When start is 0 a scroll most likely occurred, make sure links above the fold also get // cleared. const start = e.start === 0 ? 0 : e.start + 1 + this._bufferService.buffer.ydisp; this._clearCurrentLink(start, e.end + 1 + this._bufferService.buffer.ydisp); })); } } } protected _linkHover(element: HTMLElement, link: ILink, event: MouseEvent): void { if (this._currentLink?.state) { this._currentLink.state.isHovered = true; if (this._currentLink.state.decorations.underline) { this._fireUnderlineEvent(link, true); } if (this._currentLink.state.decorations.pointerCursor) { element.classList.add('xterm-cursor-pointer'); } } if (link.hover) { link.hover(event, link.text); } } private _fireUnderlineEvent(link: ILink, showEvent: boolean): void { const range = link.range; const scrollOffset = this._bufferService.buffer.ydisp; const event = this._createLinkUnderlineEvent(range.start.x - 1, range.start.y - scrollOffset - 1, range.end.x, range.end.y - scrollOffset - 1, undefined); const emitter = showEvent ? this._onShowLinkUnderline : this._onHideLinkUnderline; emitter.fire(event); } protected _linkLeave(element: HTMLElement, link: ILink, event: MouseEvent): void { if (this._currentLink?.state) { this._currentLink.state.isHovered = false; if (this._currentLink.state.decorations.underline) { this._fireUnderlineEvent(link, false); } if (this._currentLink.state.decorations.pointerCursor) { element.classList.remove('xterm-cursor-pointer'); } } if (link.leave) { link.leave(event, link.text); } } /** * Check if the buffer position is within the link * @param link * @param position */ private _linkAtPosition(link: ILink, position: IBufferCellPosition): boolean { const sameLine = link.range.start.y === link.range.end.y; const wrappedFromLeft = link.range.start.y < position.y; const wrappedToRight = link.range.end.y > position.y; // If the start and end have the same y, then the position must be between start and end x // If not, then handle each case seperately, depending on which way it wraps return ((sameLine && link.range.start.x <= position.x && link.range.end.x >= position.x) || (wrappedFromLeft && link.range.end.x >= position.x) || (wrappedToRight && link.range.start.x <= position.x) || (wrappedFromLeft && wrappedToRight)) && link.range.start.y <= position.y && link.range.end.y >= position.y; } /** * Get the buffer position from a mouse event * @param event */ private _positionFromMouseEvent(event: MouseEvent, element: HTMLElement, mouseService: IMouseService): IBufferCellPosition | undefined { const coords = mouseService.getCoords(event, element, this._bufferService.cols, this._bufferService.rows); if (!coords) { return; } return { x: coords[0], y: coords[1] + this._bufferService.buffer.ydisp }; } private _createLinkUnderlineEvent(x1: number, y1: number, x2: number, y2: number, fg: number | undefined): ILinkifierEvent { return { x1, y1, x2, y2, cols: this._bufferService.cols, fg }; } }
the_stack
import Consts from "../Consts"; import { Suggestion } from "../models/Suggestion"; import xmldom = require('xmldom') import { IefSchema } from "../models/IefSchema"; const DOMParser = require('xmldom').DOMParser; export default class XsdHelper { static staticXsdDod = null; static staticIefSchema: Array<IefSchema>; static GetXpahElement(xpath, xsdDoc, parentElemnt, parentElemntName: string, parentElemntType: string, iefSchema, select) { let element: IefSchema = new IefSchema(); if (parentElemntName === 'BuildingBlocks') { console.log('BuildingBlocks'); } // if (parentElemnt === undefined) { console.log("Return"); return; } // Get the element path element.Type = 'e'; element.Name = parentElemntName; element.parentXpath = xpath; element.xpath = xpath + '/' + element.Name; // Check whether element has content element.HasContent = (parentElemntType.startsWith('xs:') || parentElemnt.nodeName === 'xs:simpleType'); // Get the element description let documentation = select("./xs:annotation/xs:documentation", parentElemnt); if (documentation.length > 0) { element.Description = documentation[0].textContent.replace(/\s{2,}/g, ''); } // Get attributes var attributes if (parentElemnt.nodeName === 'xs:element') attributes = select("./xs:complexType/xs:attribute", parentElemnt); else attributes = select("./xs:attribute|./xs:simpleContent/xs:extension/xs:attribute", parentElemnt); for (var i = 0; i < attributes.length; i++) { let attribute: IefSchema = new IefSchema(); attribute.Type = 'a'; attribute.Name = attributes[i].getAttribute("name"); attribute.parentXpath = element.xpath; attribute.xpath = element.xpath + '/' + attribute.Name; iefSchema.push(attribute); // Get attribute restrictions if (attributes[i].getAttribute("type").startsWith("tfp:")) { var restrictions = select("//xs:schema/xs:simpleType[@name='" + attributes[i].getAttribute("type").substring(4) + "']/xs:restriction/xs:enumeration", xsdDoc); for (var r = 0; r < restrictions.length; r++) { let attribute: IefSchema = new IefSchema(); attribute.Type = 'av'; attribute.Name = restrictions[r].getAttribute("value"); attribute.parentXpath = element.xpath; attribute.xpath = element.xpath + '/' + attribute.Name; let documentation = select("./xs:annotation/xs:documentation", restrictions[r]); if (documentation.length > 0) { element.Description = documentation[0].textContent.replace(/\s{2,}/g, ''); } iefSchema.push(attribute); } } else if(attributes[i].getAttribute("type") === 'xs:boolean') { let attribute1: IefSchema = new IefSchema(); attribute1.Type = 'av'; attribute1.Name = 'false'; attribute1.parentXpath = element.xpath; attribute1.xpath = element.xpath + '/' + attribute.Name; iefSchema.push(attribute1); let attribute2: IefSchema = new IefSchema(); attribute2.Type = 'av'; attribute2.Name = 'true'; attribute2.parentXpath = element.xpath; attribute2.xpath = element.xpath + '/' + attribute.Name; iefSchema.push(attribute2); } } // Get attribute restrictions if (parentElemnt.nodeName === 'xs:simpleType') { var restrictions = select("./xs:restriction/xs:enumeration", parentElemnt); for (var i = 0; i < restrictions.length; i++) { let attribute: IefSchema = new IefSchema(); attribute.Type = 'av'; attribute.Name = restrictions[i].getAttribute("value"); attribute.parentXpath = element.xpath; attribute.xpath = element.xpath + '/' + attribute.Name; let documentation = select("./xs:annotation/xs:documentation", restrictions[i]); if (documentation.length > 0) { element.Description = documentation[0].textContent.replace(/\s{2,}/g, ''); } iefSchema.push(attribute); } } // Get parent element's children var children if (parentElemnt.nodeName === 'xs:element') children = select("./xs:complexType/xs:sequence/xs:element|./xs:complexType/xs:choice/xs:element", parentElemnt); else children = select("./xs:sequence/xs:element|./xs:choice/xs:element", parentElemnt); for (var i = 0; i < children.length; i++) { if (children[i].getAttribute("type").startsWith("tfp:")) { // Get the complex type var realElement = select("//xs:schema/xs:complexType[@name='" + children[i].getAttribute("type").substring(4) + "']", xsdDoc); if (realElement.length > 0) XsdHelper.GetXpahElement(element.xpath, xsdDoc, realElement[0], children[i].getAttribute("name"), children[i].getAttribute("type"), iefSchema, select) else { // If not found get the simple type realElement = select("//xs:schema/xs:simpleType[@name='" + children[i].getAttribute("type").substring(4) + "']", xsdDoc); if (realElement.length > 0) XsdHelper.GetXpahElement(element.xpath, xsdDoc, realElement[0], children[i].getAttribute("name"), children[i].getAttribute("type"), iefSchema, select) } } else { XsdHelper.GetXpahElement(element.xpath, xsdDoc, children[i], children[i].getAttribute("name"), children[i].getAttribute("type"), iefSchema, select) } } iefSchema.push(element); return null; } static GetSubElements(xPathArray: string[]): Suggestion[] | any { if ((!xPathArray) || xPathArray.length == 0) { return; } let xPathString = ''; for (let i = 0; i < xPathArray.length; i++) { xPathString += '/' + xPathArray[i]; } let suggestions: Suggestion[] = []; let IefSchema: Array<IefSchema> = XsdHelper.getIefSchema(); let selectedElements = IefSchema.filter((iefSchema: IefSchema) => iefSchema.Type === 'e' && iefSchema.parentXpath === xPathString) for (var i = 0; i < selectedElements.length; i++) { let suggestion: Suggestion = new Suggestion(); suggestion.InsertText = selectedElements[i].Name; suggestion.Help = selectedElements[i].Description; suggestion.HasChildren = (IefSchema.filter((iefSchema: IefSchema) => iefSchema.Type === 'e' && iefSchema.parentXpath === selectedElements[i].xpath).length > 0) && selectedElements[i].Name != "InputClaim" && selectedElements[i].Name != "OutputClaim"; suggestion.HasContent = selectedElements[i].HasContent; suggestions.push(suggestion) } return suggestions; } static GetAttributes(xPathArray: string[]): Suggestion[] | any { if ((!xPathArray) || xPathArray.length == 0) { return; } let xPathString = ''; for (let i = 0; i < xPathArray.length; i++) { xPathString += '/' + xPathArray[i]; } let suggestions: Suggestion[] = []; let IefSchema: Array<IefSchema> = XsdHelper.getIefSchema(); let selectedElements = IefSchema.filter((iefSchema: IefSchema) => iefSchema.Type === 'a' && iefSchema.parentXpath === xPathString) for (var i = 0; i < selectedElements.length; i++) { let suggestion: Suggestion = new Suggestion(); suggestion.InsertText = selectedElements[i].Name; suggestion.Help = selectedElements[i].Description; suggestions.push(suggestion) } return suggestions; } public static GetAttributeValues(xPathArray: string[], attributeName: string): Suggestion[] | any { if ((!xPathArray) || xPathArray.length == 0) { return; } let xPathString = ''; for (let i = 0; i < xPathArray.length; i++) { xPathString += '/' + xPathArray[i]; } let suggestions: Suggestion[] = []; let IefSchema: Array<IefSchema> = XsdHelper.getIefSchema(); let selectedElements = IefSchema.filter((iefSchema: IefSchema) => iefSchema.Type === 'av' && iefSchema.parentXpath === xPathString) for (var i = 0; i < selectedElements.length; i++) { let suggestion: Suggestion = new Suggestion(); suggestion.InsertText = selectedElements[i].Name; suggestion.Help = selectedElements[i].Description; suggestions.push(suggestion) } return suggestions; } public static getXsdDocument(): xmldom.Document { if (!XsdHelper.staticXsdDod) { var c = new DOMParser().parseFromString(Consts.IEF_Schema); XsdHelper.staticXsdDod = c } return XsdHelper.staticXsdDod; } public static getIefSchema(): Array<IefSchema> { if ((!XsdHelper.staticIefSchema) || XsdHelper.staticIefSchema.length == 0) { // Load the XML file var xsdDoc = XsdHelper.getXsdDocument(); let xpath = require('xpath') let select = xpath.useNamespaces({ "xs": "http://www.w3.org/2001/XMLSchema" }); let TrustFrameworkPolicy = select("//xs:schema/xs:element[@name='TrustFrameworkPolicy']", xsdDoc)[0]; XsdHelper.staticIefSchema = new Array<IefSchema>(); XsdHelper.GetXpahElement('', xsdDoc, TrustFrameworkPolicy, TrustFrameworkPolicy.getAttribute("name"), TrustFrameworkPolicy.getAttribute("type"), XsdHelper.staticIefSchema, select); } return XsdHelper.staticIefSchema; } }
the_stack
/*! * Copyright (c) 2020 Ron Buckton (rbuckton@chronicles.org) * * This file is licensed to you under the terms of the MIT License, found in the LICENSE file * in the root of this repository or package. */ import { binarySearch, compareStrings, compare } from "./core"; import { Range, Position } from "./types"; import { CharacterCodes, SyntaxKind, tokenToString } from "./tokens"; import { Node, SourceFile } from "./nodes"; import { LineOffsetMap } from "./lineOffsetMap"; /** {@docCategory Check} */ export interface Diagnostic { code: number; message: string; warning?: boolean; } import { Diagnostics } from "./diagnostics.generated"; export { Diagnostics } from "./diagnostics.generated"; /** {@docCategory Check} */ export interface DiagnosticInfo { diagnosticIndex: number; code: number; message: string; messageArguments: any[] | undefined; warning: boolean; range: Range | undefined; sourceFile: SourceFile | undefined; filename: string | undefined; node: Node | undefined; pos: number; formattedMessage?: string; } /** {@docCategory Check} */ export class DiagnosticMessages { private diagnostics: Diagnostic[] | undefined; private diagnosticsArguments: any[][] | undefined; private diagnosticsPos: number[] | undefined; private diagnosticsLength: number[] | undefined; private diagnosticsNode: Node[] | undefined; private detailedDiagnosticMessages: Map<number, string> | undefined; private simpleDiagnosticMessages: Map<number, string> | undefined; private sourceFiles: SourceFile[] | undefined; private sourceFilesDiagnosticOffset: number[] | undefined; private sortedAndDeduplicatedDiagnosticIndices: number[] | undefined; private lineOffsetMap: LineOffsetMap | undefined; constructor(lineOffsetMap?: LineOffsetMap) { this.lineOffsetMap = lineOffsetMap; } public get size() { return this.diagnostics?.length ?? 0; } public copyFrom(other: DiagnosticMessages) { if (other === this || !(other.diagnostics || other.sourceFiles)) { return; } if (!this.diagnostics && !this.sourceFiles && !this.lineOffsetMap) { this.diagnostics = other.diagnostics?.slice(); this.diagnosticsArguments = other.diagnosticsArguments?.slice(); this.diagnosticsPos = other.diagnosticsPos?.slice(); this.diagnosticsLength = other.diagnosticsLength?.slice(); this.diagnosticsNode = other.diagnosticsNode?.slice(); this.sourceFiles = other.sourceFiles?.slice(); this.sourceFilesDiagnosticOffset = other.sourceFilesDiagnosticOffset?.slice(); if (other.lineOffsetMap) { this.lineOffsetMap = new LineOffsetMap(); this.lineOffsetMap.copyFrom(other.lineOffsetMap); } this.sortedAndDeduplicatedDiagnosticIndices = other.sortedAndDeduplicatedDiagnosticIndices?.slice(); this.detailedDiagnosticMessages = other.detailedDiagnosticMessages && new Map(other.detailedDiagnosticMessages); this.simpleDiagnosticMessages = other.simpleDiagnosticMessages && new Map(other.simpleDiagnosticMessages); return; } // copy source files if (other.sourceFiles && other.sourceFilesDiagnosticOffset) { this.sourceFiles ??= []; this.sourceFilesDiagnosticOffset ??= []; const diagnosticOffset = this.size; const sourceFileOffset = this.sourceFiles.length; const continueFromExistingFile = sourceFileOffset > 0 && other.sourceFiles[0] === this.sourceFiles[sourceFileOffset - 1]; for (let i = continueFromExistingFile ? 1 : 0; i < other.sourceFiles.length; i++) { this.sourceFiles[sourceFileOffset + i] = other.sourceFiles[i]; this.sourceFilesDiagnosticOffset[sourceFileOffset + i] = other.sourceFilesDiagnosticOffset[i] + diagnosticOffset; } } // copy line offsets if (other.lineOffsetMap) { this.lineOffsetMap ??= new LineOffsetMap(); this.lineOffsetMap.copyFrom(other.lineOffsetMap); } // copy diagnostics if (other.diagnostics) { for (let i = 0; i < other.diagnostics.length; i++) { this.reportDiagnostic( other.diagnostics[i], other.diagnosticsArguments && other.diagnosticsArguments[i], other.diagnosticsPos && other.diagnosticsPos[i], other.diagnosticsLength && other.diagnosticsLength[i], other.diagnosticsNode && other.diagnosticsNode[i] ); } } } public setSourceFile(sourceFile: SourceFile): void { this.sourceFiles ??= []; this.sourceFilesDiagnosticOffset ??= []; const sourceFileIndex = this.sourceFiles.length; if (sourceFileIndex > 0 && this.sourceFiles[sourceFileIndex - 1] === sourceFile) { return; } const diagnosticOffset = this.size; this.sourceFiles[sourceFileIndex] = sourceFile; this.sourceFilesDiagnosticOffset[sourceFileIndex] = diagnosticOffset; } public report(pos: number, message: Diagnostic, ...args: any[]): void { this.reportDiagnostic(message, args, pos); } public reportNode(sourceFile: SourceFile | undefined, node: Node, message: Diagnostic, ...args: any[]): void { let pos: number | undefined; let length: number | undefined; if (node) { pos = node.getStart(sourceFile); length = node.getWidth(sourceFile); } this.reportDiagnostic(message, args, pos, length, node); } public count(): number { return this.diagnostics?.length ?? 0; } public getMessage(diagnosticIndex: number, options: { detailed?: boolean; raw?: boolean; } = { detailed: true }): string { const diagnostic = this.diagnostics?.[diagnosticIndex]; if (diagnostic) { const { detailed = true } = options; const diagnosticMessages = detailed ? this.detailedDiagnosticMessages ??= new Map() : this.simpleDiagnosticMessages ??= new Map(); const diagnosticMessage = diagnosticMessages.get(diagnosticIndex); if (diagnosticMessage !== undefined) { return diagnosticMessage; } const diagnosticArguments = this.diagnosticsArguments?.[diagnosticIndex]; let text = ""; if (detailed) { const sourceFile = this.getDiagnosticSourceFile(diagnosticIndex); const filename = this.getDiagnosticFilename(diagnosticIndex, options.raw); const position = this.getDiagnosticPosition(diagnosticIndex, options.raw) text += filename ?? (sourceFile ? sourceFile.filename : ""); if (position) { text += `(${position.line + 1},${position.character + 1})`; } else if (this.diagnosticsPos && diagnosticIndex in this.diagnosticsPos) { const diagnosticPos = this.diagnosticsPos[diagnosticIndex]; if (sourceFile && sourceFile.lineMap) { text += `(${sourceFile.lineMap.formatOffset(diagnosticPos)})`; } else { text += `(${diagnosticPos})`; } } text += ": "; text += diagnostic.warning ? "warning" : "error"; text += " GM" + String(diagnostic.code) + ": "; } let message = diagnostic.message; if (diagnosticArguments) { message = formatString(message, diagnosticArguments); } text += message; diagnosticMessages.set(diagnosticIndex, text); return text; } return ""; } public getDiagnostic(diagnosticIndex: number): Diagnostic | undefined { return this.diagnostics?.[diagnosticIndex]; } public getDiagnosticInfos(options?: { formatMessage?: boolean; detailedMessage?: boolean; raw?: boolean; }): DiagnosticInfo[] { const result: DiagnosticInfo[] = []; if (this.diagnostics) { for (const diagnosticIndex of this.getSortedAndDeduplicatedDiagnosticIndices()) { const diagnosticInfo = this.getDiagnosticInfo(diagnosticIndex, options); if (diagnosticInfo) { result.push(diagnosticInfo); } } } return result; } public getDiagnosticInfosForSourceFile(sourceFile: SourceFile, options?: { formatMessage?: boolean; detailedMessage?: boolean; raw?: boolean; }): DiagnosticInfo[] { const result: DiagnosticInfo[] = []; if (this.diagnostics) { for (const diagnosticIndex of this.getSortedAndDeduplicatedDiagnosticIndices()) { if (this.getDiagnosticSourceFile(diagnosticIndex) === sourceFile) { const diagnosticInfo = this.getDiagnosticInfo(diagnosticIndex, options); if (diagnosticInfo) { result.push(diagnosticInfo); } } } } return result; } public getDiagnosticInfo(diagnosticIndex: number, options: { formatMessage?: boolean; detailedMessage?: boolean; raw?: boolean; } = {}): DiagnosticInfo | undefined { const diagnostic = this.getDiagnostic(diagnosticIndex); if (diagnostic) { const info: DiagnosticInfo = { diagnosticIndex, code: diagnostic.code, warning: diagnostic.warning || false, message: diagnostic.message, messageArguments: this.getDiagnosticArguments(diagnosticIndex), range: this.getDiagnosticRange(diagnosticIndex, options.raw), sourceFile: this.getDiagnosticSourceFile(diagnosticIndex), filename: this.getDiagnosticFilename(diagnosticIndex, options.raw), node: this.getDiagnosticNode(diagnosticIndex), pos: this.getDiagnosticPos(diagnosticIndex) }; if (options.formatMessage) { info.formattedMessage = this.getMessage(diagnosticIndex, { detailed: options.detailedMessage }); } return info; } return undefined; } public getDiagnosticArguments(diagnosticIndex: number): any[] | undefined { return this.diagnosticsArguments?.[diagnosticIndex]; } public getDiagnosticRange(diagnosticIndex: number, raw?: boolean) { const diagnostic = this.getDiagnostic(diagnosticIndex); const sourceFile = this.getDiagnosticSourceFile(diagnosticIndex); const node = this.getDiagnosticNode(diagnosticIndex); const pos = this.getDiagnosticPos(diagnosticIndex); if (diagnostic && node || pos > -1) { const range = getDiagnosticRange(node, pos, sourceFile); if (!raw && sourceFile && this.lineOffsetMap) { return this.lineOffsetMap.getEffectiveRange(sourceFile, range); } return range; } return undefined; } public getDiagnosticPosition(diagnosticIndex: number, raw?: boolean) { const diagnostic = this.getDiagnostic(diagnosticIndex); const sourceFile = this.getDiagnosticSourceFile(diagnosticIndex); const node = this.getDiagnosticNode(diagnosticIndex); const pos = this.getDiagnosticPos(diagnosticIndex); if (diagnostic && node || pos > -1) { const position = positionOfStart(node, pos, sourceFile); if (!raw && sourceFile && this.lineOffsetMap) { return this.lineOffsetMap.getEffectivePosition(sourceFile, position); } return position; } return undefined; } public getDiagnosticNode(diagnosticIndex: number): Node | undefined { return this.diagnosticsNode?.[diagnosticIndex]; } public getDiagnosticSourceFile(diagnosticIndex: number): SourceFile | undefined { if (this.sourceFiles && this.sourceFilesDiagnosticOffset) { let offset = binarySearch(this.sourceFilesDiagnosticOffset, diagnosticIndex); if (offset < 0) { offset = (~offset) - 1; } while (offset + 1 < this.sourceFiles.length && this.sourceFilesDiagnosticOffset[offset + 1] === diagnosticIndex) { offset++; } return this.sourceFiles[offset]; } return undefined; } public getDiagnosticFilename(diagnosticIndex: number, raw?: boolean): string | undefined { const sourceFile = this.getDiagnosticSourceFile(diagnosticIndex); if (sourceFile) { if (!raw && this.lineOffsetMap) { const pos = this.getDiagnosticPos(diagnosticIndex); if (pos > -1) { return this.lineOffsetMap.getEffectiveFilenameAtPosition(sourceFile, sourceFile.lineMap.positionAt(pos)); } } return sourceFile.filename; } return undefined; } public forEach(callback: (message: string, diagnosticIndex: number) => void): void { if (this.diagnostics) { for (const diagnosticIndex of this.getSortedAndDeduplicatedDiagnosticIndices()) { callback(this.getMessage(diagnosticIndex, { detailed: true }), diagnosticIndex); } } } public * values() { for (let i = 0; i < this.size; i++) { yield this.getDiagnosticInfo(i); } } public [Symbol.iterator]() { return this.values(); } private getSortedAndDeduplicatedDiagnosticIndices() { if (!this.sortedAndDeduplicatedDiagnosticIndices) { let indices: number[] = []; if (this.diagnostics) { for (let diagnosticIndex = 0, l = this.diagnostics.length; diagnosticIndex < l; diagnosticIndex++) { indices[diagnosticIndex] = diagnosticIndex; } } indices = this.sortDiagnostics(indices); indices = this.deduplicateDiagnostics(indices); this.sortedAndDeduplicatedDiagnosticIndices = indices; } return this.sortedAndDeduplicatedDiagnosticIndices; } private sortDiagnostics(indices: number[]) { return indices.sort((left, right) => this.compareDiagnostics(left, right)); } private compareDiagnostics(diagnosticIndex1: number, diagnosticIndex2: number) { const file1 = this.getDiagnosticSourceFile(diagnosticIndex1); const file2 = this.getDiagnosticSourceFile(diagnosticIndex2); return compareStrings(file1 && file1.filename, file2 && file2.filename) || compare(this.getDiagnosticPos(diagnosticIndex1), this.getDiagnosticPos(diagnosticIndex2)) || compare(this.getDiagnosticLength(diagnosticIndex1), this.getDiagnosticLength(diagnosticIndex2)) || compare(this.getDiagnosticErrorLevel(diagnosticIndex1), this.getDiagnosticErrorLevel(diagnosticIndex2)) || compare(this.getDiagnosticCode(diagnosticIndex1), this.getDiagnosticCode(diagnosticIndex2)) || compareStrings(this.getMessage(diagnosticIndex1), this.getMessage(diagnosticIndex2), /*ignoreCase*/ true); } private deduplicateDiagnostics(indices: number[]) { if (indices.length <= 1) { return indices; } const firstDiagnosticIndex = indices[0]; const newIndices: number[] = [firstDiagnosticIndex]; let previousDiagnosticIndex = firstDiagnosticIndex; for (let i = 1; i < indices.length; i++) { const diagnosticIndex = indices[i]; if (this.compareDiagnostics(previousDiagnosticIndex, diagnosticIndex)) { newIndices.push(diagnosticIndex); previousDiagnosticIndex = diagnosticIndex; } } return newIndices; } private getDiagnosticPos(diagnosticIndex: number): number { return this.diagnosticsPos?.[diagnosticIndex] ?? -1; } private getDiagnosticLength(diagnosticIndex: number): number { return this.diagnosticsLength?.[diagnosticIndex] ?? 0; } private getDiagnosticCode(diagnosticIndex: number): number { return this.getDiagnostic(diagnosticIndex)?.code ?? 0; } private getDiagnosticErrorLevel(diagnosticIndex: number): number { return this.getDiagnostic(diagnosticIndex)?.warning ? 0 : 1; } private reportDiagnostic(message: Diagnostic, args: any[] | undefined, pos?: number, length?: number, node?: Node): void { this.sortedAndDeduplicatedDiagnosticIndices = undefined; this.diagnostics ??= []; const diagnosticIndex = this.diagnostics.length; this.diagnostics[diagnosticIndex] = message; if (args && args.length > 0) { this.diagnosticsArguments ??= []; this.diagnosticsArguments[diagnosticIndex] = args; } if (pos !== undefined) { this.diagnosticsPos ??= []; this.diagnosticsPos[diagnosticIndex] = pos; } if (length !== undefined) { this.diagnosticsLength ??= []; this.diagnosticsLength[diagnosticIndex] = length; } if (node !== undefined) { this.diagnosticsNode ??= []; this.diagnosticsNode[diagnosticIndex] = node; } } } /** {@docCategory Check} */ export class NullDiagnosticMessages extends DiagnosticMessages { private static _instance: NullDiagnosticMessages; public static get instance() { return this._instance ??= new NullDiagnosticMessages(); } get size() { return 0; } public copyFrom(other: DiagnosticMessages): void { } public setSourceFile(sourceFile: SourceFile): void { } public report(pos: number, message: Diagnostic, ...args: any[]): void { } public reportNode(sourceFile: SourceFile | undefined, node: Node, message: Diagnostic, ...args: any[]): void { } } /** {@docCategory Check} */ export class LineMap { private text: string; private lineStarts!: number[]; constructor(text: string) { this.text = text; } public get lineCount() { this.computeLineStarts(); return this.lineStarts.length; } public formatOffset(pos: number): string { this.computeLineStarts(); var lineNumber = binarySearch(this.lineStarts, pos); if (lineNumber < 0) { // If the actual position was not found, // the binary search returns the negative value of the next line start // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20 // then the search will return -2 lineNumber = (~lineNumber) - 1; } return `${lineNumber + 1},${pos - this.lineStarts[lineNumber] + 1}`; } public offsetAt(position: Position) { this.computeLineStarts(); if (position.line < 0) return 0; if (position.line >= this.lineStarts.length) return this.text.length; const linePos = this.lineStarts[position.line]; const pos = linePos + position.character; const lineEnd = position.line + 1 < this.lineStarts.length ? this.lineStarts[position.line + 1] : this.text.length; return pos < linePos ? linePos : pos > lineEnd ? lineEnd : pos; } public positionAt(offset: number): Position { this.computeLineStarts(); let lineNumber = binarySearch(this.lineStarts, offset); if (lineNumber < 0) { // If the actual position was not found, // the binary search returns the negative value of the next line start // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20 // then the search will return -2 lineNumber = (~lineNumber) - 1; } return { line: lineNumber, character: offset - this.lineStarts[lineNumber] }; } private computeLineStarts() { if (this.lineStarts) { return; } const lineStarts: number[] = []; let lineStart = 0; for (var pos = 0; pos < this.text.length;) { var ch = this.text.charCodeAt(pos++); switch (ch) { case CharacterCodes.CarriageReturn: if (this.text.charCodeAt(pos) === CharacterCodes.LineFeed) { pos++; } case CharacterCodes.LineFeed: case CharacterCodes.LineSeparator: case CharacterCodes.ParagraphSeparator: case CharacterCodes.NextLine: lineStarts.push(lineStart); lineStart = pos; break; } } lineStarts.push(lineStart); this.lineStarts = lineStarts; } } function getDiagnosticRange(diagnosticNode: Node | undefined, diagnosticPos: number, sourceFile: SourceFile | undefined): Range { return { start: positionOfStart(diagnosticNode, diagnosticPos, sourceFile), end: positionOfEnd(diagnosticNode, diagnosticPos, sourceFile) } } function positionOfStart(diagnosticNode: Node | undefined, diagnosticPos: number, sourceFile: SourceFile | undefined) { return positionAt(diagnosticNode ? diagnosticNode.getStart(sourceFile) : diagnosticPos, sourceFile); } function positionOfEnd(diagnosticNode: Node | undefined, diagnosticPos: number, sourceFile: SourceFile | undefined) { return positionAt(diagnosticNode ? diagnosticNode.getEnd() : diagnosticPos, sourceFile); } function positionAt(diagnosticPos: number, sourceFile: SourceFile | undefined) { return sourceFile?.lineMap ? sourceFile.lineMap.positionAt(diagnosticPos) : { line: 0, character: diagnosticPos }; } export function formatString(format: string, args?: any[]): string; export function formatString(format: string, ...args: any[]): string; export function formatString(format: string): string { let args = <any[]>Array.prototype.slice.call(arguments, 1); if (args.length === 1 && args[0] instanceof Array) { args = args[0]; } return format.replace(/{(\d+)}/g, (_, index) => args[index]); } export function formatList(tokens: (SyntaxKind | string)[]): string { if (tokens.length <= 0) { return ""; } else if (tokens.length === 1) { return tokenToString(tokens[0], /*quoted*/ true); } else if (tokens.length === 2) { return formatString( Diagnostics._0_or_1_.message, tokenToString(tokens[0], /*quoted*/ true), tokenToString(tokens[1], /*quoted*/ true)); } else { let text = ""; for (var i = 0; i < tokens.length - 1; i++) { if (i > 0) { text += " "; } text += tokenToString(tokens[i], /*quoted*/ true); text += ","; } return formatString(Diagnostics._0_or_1_.message, text, tokenToString(tokens[tokens.length - 1], /*quoted*/ true)); } }
the_stack
import { JSONSchema7, JSONSchema7Definition, JSONSchema7TypeName } from 'json-schema' import { inspect } from 'util' import { defaultValuesByType } from './defaults' import { Property, LensSource, ConvertValue, LensOp, HeadProperty, WrapProperty, LensIn, } from './lens-ops' export const emptySchema = { $schema: 'http://json-schema.org/draft-07/schema', type: 'object' as const, additionalProperties: false, } function deepInspect(object: any) { return inspect(object, false, null, true) } // add a property to a schema // note: property names are in json pointer with leading / // (because that's how our Property types work for now) // mutates the schema that is passed in // (should switch to a more functional style) function addProperty(schema: JSONSchema7, property: Property): JSONSchema7 { const { properties: origProperties = {}, required: origRequired = [] } = schema const { name, items, required: isPropertyRequired } = property let { type } = property if (!name || !type) { throw new Error(`Missing property name in addProperty.\nFound:\n${JSON.stringify(property)}`) } if (Array.isArray(type)) { type = type.map((t) => (t === null ? 'null' : t)) } const arraylessPropertyDefinition = { type, default: property.default || defaultValuesByType(type), // default is a reserved keyword } // this is kludgey but you should see the crazy syntax for the alternative const propertyDefinition = type === 'array' && items ? { ...arraylessPropertyDefinition, items: { type: items.type, default: items.default || defaultValuesByType(items.type) }, } : arraylessPropertyDefinition const properties = { ...origProperties, [name]: propertyDefinition } const shouldAdd = isPropertyRequired !== false && !origRequired.includes(name) const required = [...origRequired, ...(shouldAdd ? [name] : [])] return { ...schema, properties, required, } } function withNullable(schema: JSONSchema7, fn: (s: JSONSchema7) => JSONSchema7): JSONSchema7 { if (schema.anyOf) { if (schema.anyOf.length !== 2) { throw new Error('We only support this operation on schemas with one type or a nullable type') } return { ...schema, anyOf: schema.anyOf.map(db).map((s) => (s.type === 'null' ? s : fn(s))) } } else { return fn(schema) } } function renameProperty(_schema: JSONSchema7, from: string, to: string): JSONSchema7 { return withNullable(_schema, (schema) => { if (typeof schema !== 'object' || typeof schema.properties !== 'object') { throw new Error(`expected schema object, got ${JSON.stringify(schema)}`) } if (!from) { throw new Error("Rename property requires a 'source' to rename.") } if (!schema.properties[from]) { throw new Error( `Cannot rename property '${from}' because it does not exist among ${Object.keys( schema.properties )}.` ) } if (!to) { throw new Error(`Need a 'destination' to rename ${from} to.`) } const { properties = {}, required = [] } = schema // extract properties with default of empty const { [from]: propDetails, ...rest } = properties // pull out the old value if (propDetails === undefined) { throw new Error(`Rename error: missing expected property ${from}`) } return { ...schema, properties: { [to]: propDetails, ...rest }, required: [...required.filter((r) => r !== from), to], } // assign it to the new one }) } // remove a property from a schema // property name is _not_ in JSON Pointer, no leading slash here. // (yes, that's inconsistent with addPropertyToSchema, which is bad) function removeProperty(schema: JSONSchema7, removedPointer: string): JSONSchema7 { const { properties = {}, required = [] } = schema const removed = removedPointer // we don't care about the `discarded` variable... // eslint-disable-next-line @typescript-eslint/no-unused-vars if (!(removed in properties)) { throw new Error(`Attempting to remove nonexistent property: ${removed}`) } // no way to discard the // eslint-disable-next-line @typescript-eslint/no-unused-vars const { [removed]: discarded, ...rest } = properties return { ...schema, properties: rest, required: required.filter((e) => e !== removed), } } function schemaSupportsType( typeValue: JSONSchema7TypeName | JSONSchema7TypeName[] | undefined, type: JSONSchema7TypeName ): boolean { if (!typeValue) { return false } if (!Array.isArray(typeValue)) { typeValue = [typeValue] } return typeValue.includes(type) } /** db * removes the horrible, obnoxious, and annoying case where JSON schemas can just be * "true" or "false" meaning the below definitions and screwing up my type checker */ function db(s: JSONSchema7Definition): JSONSchema7 { if (s === true) { return {} } if (s === false) { return { not: {} } } return s } function supportsNull(schema: JSONSchema7): boolean { return ( schemaSupportsType(schema.type, 'null') || !!schema.anyOf?.some((subSchema) => schemaSupportsType(db(subSchema).type, 'null')) ) } function findHost(schema: JSONSchema7, name: string): JSONSchema7 { if (schema.anyOf) { const maybeSchema = schema.anyOf?.find((t) => typeof t === 'object' && t.properties) if (typeof maybeSchema === 'object' && typeof maybeSchema.properties === 'object') { const maybeHost = maybeSchema.properties[name] if (maybeHost !== false && maybeHost !== true) { return maybeHost } } } else if (schema.properties && schema.properties[name]) { const maybeHost = schema.properties[name] if (maybeHost !== false && maybeHost !== true) { return maybeHost } } throw new Error("Coudln't find the host for this data.") } function inSchema(schema: JSONSchema7, op: LensIn): JSONSchema7 { const properties: JSONSchema7 = schema.properties ? schema.properties : (schema.anyOf?.find((t) => typeof t === 'object' && t.properties) as any).properties if (!properties) { throw new Error("Cannot look 'in' an object that doesn't have properties.") } const { name, lens } = op if (!name) { throw new Error(`Expected to find property ${name} in ${Object.keys(op || {})}`) } const host = findHost(schema, name) if (host === undefined) { throw new Error(`Expected to find property ${name} in ${Object.keys(properties || {})}`) } const newProperties: JSONSchema7 = { ...properties, [name]: updateSchema(host, lens), } return { ...schema, properties: newProperties, } as JSONSchema7 } type JSONSchema7Items = boolean | JSONSchema7 | JSONSchema7Definition[] | undefined function validateSchemaItems(items: JSONSchema7Items) { if (Array.isArray(items)) { throw new Error('Cambria only supports consistent types for arrays.') } if (!items || items === true) { throw new Error(`Cambria requires a specific items definition, found ${items}.`) } return items } function mapSchema(schema: JSONSchema7, lens: LensSource) { if (!lens) { throw new Error('Map requires a `lens` to map over the array.') } if (!schema.items) { throw new Error(`Map requires a schema with items to map over, ${deepInspect(schema)}`) } return { ...schema, items: updateSchema(validateSchemaItems(schema.items), lens) } } function filterScalarOrArray<T>(v: T | T[], cb: (t: T) => boolean) { if (!Array.isArray(v)) { v = [v] } v = v.filter(cb) if (v.length === 1) { return v[0] } return v } // XXX: THIS SHOULD REMOVE DEFAULT: NULL function removeNullSupport(prop: JSONSchema7): JSONSchema7 | null { if (!supportsNull(prop)) { return prop } if (prop.type) { if (prop.type === 'null') { return null } prop = { ...prop, type: filterScalarOrArray(prop.type, (t) => t !== 'null') } if (prop.default === null) { prop.default = defaultValuesByType(prop.type!) // the above always assigns a legal type } } if (prop.anyOf) { const newAnyOf = prop.anyOf.reduce((acc: JSONSchema7[], s) => { const clean = removeNullSupport(db(s)) return clean ? [...acc, clean] : acc }, []) if (newAnyOf.length === 1) { return newAnyOf[0] } prop = { ...prop, anyOf: newAnyOf } } return prop } function wrapProperty(schema: JSONSchema7, op: WrapProperty): JSONSchema7 { if (!op.name) { throw new Error('Wrap property requires a `name` to identify what to wrap.') } if (!schema.properties) { throw new Error('Cannot wrap a property here. There are no properties.') } const prop = db(schema.properties[op.name]) if (!prop) { throw new Error(`Cannot wrap property '${op.name}' because it does not exist.`) } if (!supportsNull(prop)) { throw new Error( `Cannot wrap property '${op.name}' because it does not allow nulls, found ${deepInspect( schema )}` ) } return { ...schema, properties: { ...schema.properties, [op.name]: { type: 'array', default: [], items: removeNullSupport(prop) || { not: {} }, }, }, } } function headProperty(schema, op: HeadProperty) { if (!op.name) { throw new Error('Head requires a `name` to identify what to take head from.') } if (!schema.properties[op.name]) { throw new Error(`Cannot head property '${op.name}' because it does not exist.`) } return { ...schema, properties: { ...schema.properties, [op.name]: { anyOf: [{ type: 'null' }, schema.properties[op.name].items] }, }, } } function hoistProperty(_schema: JSONSchema7, host: string, name: string): JSONSchema7 { return withNullable(_schema, (schema) => { if (schema.properties === undefined) { throw new Error(`Can't hoist when root schema isn't an object`) } if (!host) { throw new Error(`Need a \`host\` property to hoist from.`) } if (!name) { throw new Error(`Need to provide a \`name\` to hoist up`) } const { properties } = schema if (!(host in properties)) { throw new Error( `Can't hoist anything from ${host}, it does not exist here. (Found properties ${Object.keys( properties )})` ) } const hoistedPropertySchema = withNullable(db(properties[host]), (hostSchema) => { const hostProperties = hostSchema.properties const hostRequired = hostSchema.required || [] if (!hostProperties) { throw new Error( `There are no properties to hoist out of ${host}, found ${Object.keys(hostSchema)}` ) } if (!(name in hostProperties)) { throw new Error( `Can't hoist anything from ${host}, it does not exist here. (Found properties ${Object.keys( properties )})` ) } const { [name]: target, ...remainingProperties } = hostProperties return { ...hostSchema, properties: remainingProperties, required: hostRequired.filter((e) => e !== name), } }) const childObject = withNullable(db(properties[host]), (hostSchema) => { const hostProperties = hostSchema.properties! const { [name]: target } = hostProperties return db(target) }) return { ...schema, properties: { ...schema.properties, [host]: hoistedPropertySchema, [name]: childObject, }, required: [...(schema.required || []), name], } }) } function plungeProperty(schema: JSONSchema7, host: string, name: string) { // XXXX what should we do for missing child properties? error? const { properties = {} } = schema if (!host) { throw new Error(`Need a \`host\` property to plunge into`) } if (!name) { throw new Error(`Need to provide a \`name\` to plunge`) } const destinationTypeProperties = properties[name] if (!destinationTypeProperties) { throw new Error(`Could not find a property called ${name} among ${Object.keys(properties)}`) } // we can throw an error here if things are missing? if (destinationTypeProperties === true) { // errrr... complain? return schema } // add the property to the root schema schema = inSchema(schema, { op: 'in', name: host, lens: [ { op: 'add', ...(destinationTypeProperties as Property), name, }, ], }) // remove it from its current parent // PS: ugh schema = removeProperty(schema, name) return schema } function convertValue(schema: JSONSchema7, lensOp: ConvertValue) { const { name, destinationType, mapping } = lensOp if (!destinationType) { return schema } if (!name) { throw new Error(`Missing property name in 'convert'.\nFound:\n${JSON.stringify(lensOp)}`) } if (!mapping) { throw new Error(`Missing mapping for 'convert'.\nFound:\n${JSON.stringify(lensOp)}`) } return { ...schema, properties: { ...schema.properties, [name]: { type: destinationType, default: defaultValuesByType(destinationType), }, }, } } function assertNever(x: never): never { throw new Error(`Unexpected object: ${x}`) } function applyLensOperation(schema: JSONSchema7, op: LensOp) { switch (op.op) { case 'add': return addProperty(schema, op) case 'remove': return removeProperty(schema, op.name || '') case 'rename': return renameProperty(schema, op.source, op.destination) case 'in': return inSchema(schema, op) case 'map': return mapSchema(schema, op.lens) case 'wrap': return wrapProperty(schema, op) case 'head': return headProperty(schema, op) case 'hoist': return hoistProperty(schema, op.host, op.name) case 'plunge': return plungeProperty(schema, op.host, op.name) case 'convert': return convertValue(schema, op) default: assertNever(op) // exhaustiveness check return null } } export function updateSchema(schema: JSONSchema7, lens: LensSource): JSONSchema7 { return lens.reduce<JSONSchema7>((schema: JSONSchema7, op: LensOp) => { if (schema === undefined) throw new Error("Can't update undefined schema") return applyLensOperation(schema, op) }, schema as JSONSchema7) } export function schemaForLens(lens: LensSource): JSONSchema7 { const emptySchema = { $schema: 'http://json-schema.org/draft-07/schema', type: 'object' as const, additionalProperties: false, } return updateSchema(emptySchema, lens) }
the_stack
import '../../../../../__mocks__/_extendJest' import { setupDefaultStudioEnvironment, DefaultEnvironment, setupDefaultRundownPlaylist, } from '../../../../../__mocks__/helpers/database' import { DBRundown, RundownId, Rundowns } from '../../../../../lib/collections/Rundowns' import { RundownPlaylist, RundownPlaylistId, RundownPlaylists } from '../../../../../lib/collections/RundownPlaylists' import { getCurrentTime, getRandomId, protectString } from '../../../../../lib/lib' import { SegmentId } from '../../../../../lib/collections/Segments' import { DBPart, Part, PartId, Parts } from '../../../../../lib/collections/Parts' import { Piece } from '../../../../../lib/collections/Pieces' import { LookaheadMode, TSR } from '@sofie-automation/blueprints-integration' import { MappingsExt, Studios } from '../../../../../lib/collections/Studios' import { OnGenerateTimelineObjExt, TimelineObjRundown } from '../../../../../lib/collections/Timeline' import { PartInstanceAndPieceInstances } from '../util' import { getLookeaheadObjects } from '..' import { SelectedPartInstancesTimelineInfo } from '../../timeline' import { testInFiber } from '../../../../../__mocks__/helpers/jest' import { PlayoutLockFunctionPriority, runPlayoutOperationWithCache } from '../../lockFunction' jest.mock('../findForLayer') type TfindLookaheadForLayer = jest.MockedFunction<typeof findLookaheadForLayer> const findLookaheadForLayerMock = findLookaheadForLayer as TfindLookaheadForLayer import { findLookaheadForLayer } from '../findForLayer' jest.mock('../util') type TgetOrderedPartsAfterPlayhead = jest.MockedFunction<typeof getOrderedPartsAfterPlayhead> const getOrderedPartsAfterPlayheadMock = getOrderedPartsAfterPlayhead as TgetOrderedPartsAfterPlayhead import { getOrderedPartsAfterPlayhead } from '../util' import { LOOKAHEAD_DEFAULT_SEARCH_DISTANCE } from '../../../../../lib/constants' describe('Lookahead', () => { let env: DefaultEnvironment let playlistId: RundownPlaylistId let rundownId: RundownId // let segmentId: SegmentId let partIds: PartId[] beforeEach(() => { findLookaheadForLayerMock.mockReset().mockReturnValue({ timed: [], future: [] }) // Default mock getOrderedPartsAfterPlayheadMock.mockReset().mockReturnValue([]) env = setupDefaultStudioEnvironment() const mappings: MappingsExt = {} for (const k of Object.keys(LookaheadMode)) { if (isNaN(parseInt(k))) { mappings[k] = { device: TSR.DeviceType.ABSTRACT, deviceId: protectString('fake0'), lookahead: LookaheadMode[k], // lookaheadDepth: 0, // lookaheadMaxSearchDistance: 0, } } } Studios.update(env.studio._id, { $set: { mappings } }) env.studio.mappings = mappings ;({ playlistId, rundownId } = setupDefaultRundownPlaylist( env, undefined, (env: DefaultEnvironment, playlistId: RundownPlaylistId, rundownId: RundownId) => { const rundown: DBRundown = { peripheralDeviceId: env.ingestDevice._id, organizationId: null, studioId: env.studio._id, showStyleBaseId: env.showStyleBase._id, showStyleVariantId: env.showStyleVariant._id, playlistId: playlistId, _rank: 0, _id: rundownId, externalId: 'MOCK_RUNDOWN', name: 'Default Rundown', created: getCurrentTime(), modified: getCurrentTime(), importVersions: { studio: '', showStyleBase: '', showStyleVariant: '', blueprint: '', core: '', }, externalNRCSName: 'mock', } Rundowns.insert(rundown) function createMockPart(index: number, segId: SegmentId): DBPart { return { _id: protectString(rundownId + '_part' + index), segmentId: segId, rundownId: rundown._id, _rank: index, externalId: 'MOCK_PART_' + index, title: 'Part ' + index, } } const segmentId0: SegmentId = getRandomId() const segmentId1: SegmentId = getRandomId() const segmentId2: SegmentId = getRandomId() partIds = [ Parts.insert(createMockPart(0, segmentId0)), Parts.insert(createMockPart(1, segmentId0)), Parts.insert(createMockPart(2, segmentId0)), Parts.insert(createMockPart(3, segmentId0)), Parts.insert(createMockPart(4, segmentId0)), Parts.insert(createMockPart(10, segmentId1)), Parts.insert(createMockPart(11, segmentId1)), Parts.insert(createMockPart(12, segmentId1)), Parts.insert(createMockPart(20, segmentId2)), Parts.insert(createMockPart(21, segmentId2)), Parts.insert(createMockPart(22, segmentId2)), ] return rundownId } )) }) function expectLookaheadForLayerMock( playlistId0: RundownPlaylistId, partInstances: PartInstanceAndPieceInstances[], previous: PartInstanceAndPieceInstances | undefined, orderedPartsFollowingPlayhead: Part[], piecesByPart: Map<PartId, Piece[]> ) { const playlist = RundownPlaylists.findOne(playlistId0) as RundownPlaylist expect(playlist).toBeTruthy() expect(findLookaheadForLayerMock).toHaveBeenCalledTimes(2) expect(findLookaheadForLayerMock).toHaveBeenNthCalledWith( 1, playlist.currentPartInstanceId, partInstances, previous, orderedPartsFollowingPlayhead, piecesByPart, 'PRELOAD', 1, LOOKAHEAD_DEFAULT_SEARCH_DISTANCE ) expect(findLookaheadForLayerMock).toHaveBeenNthCalledWith( 2, playlist.currentPartInstanceId, partInstances, previous, orderedPartsFollowingPlayhead, piecesByPart, 'WHEN_CLEAR', 1, LOOKAHEAD_DEFAULT_SEARCH_DISTANCE ) findLookaheadForLayerMock.mockClear() } testInFiber('No pieces', () => { const playlist = RundownPlaylists.findOne(playlistId) as RundownPlaylist expect(playlist).toBeTruthy() const partInstancesInfo: SelectedPartInstancesTimelineInfo = {} const fakeParts = partIds.map((p) => ({ _id: p })) as Part[] getOrderedPartsAfterPlayheadMock.mockReturnValueOnce(fakeParts) const res = runPlayoutOperationWithCache( null, 'test', playlistId, PlayoutLockFunctionPriority.USER_PLAYOUT, null, (cache) => getLookeaheadObjects(cache, partInstancesInfo) ) expect(res).toHaveLength(0) expect(getOrderedPartsAfterPlayheadMock).toHaveBeenCalledTimes(1) expect(getOrderedPartsAfterPlayheadMock).toHaveBeenCalledWith(expect.anything(), 10) // default distance expectLookaheadForLayerMock(playlistId, [], undefined, fakeParts, new Map()) }) function fakeResultObj(id: string, pieceId: string, layer: string): TimelineObjRundown & OnGenerateTimelineObjExt { return { id: id, pieceInstanceId: pieceId, layer: layer, content: { id }, } as any } testInFiber('got some objects', () => { const partInstancesInfo: SelectedPartInstancesTimelineInfo = {} const fakeParts = partIds.map((p) => ({ _id: p })) as Part[] getOrderedPartsAfterPlayheadMock.mockReturnValueOnce(fakeParts) findLookaheadForLayerMock .mockImplementationOnce((_id, _parts, _prev, _parts2, _pieces, layer) => ({ timed: [fakeResultObj('obj0', 'piece0', layer), fakeResultObj('obj1', 'piece1', layer)], future: [ fakeResultObj('obj2', 'piece0', layer), fakeResultObj('obj3', 'piece0', layer), fakeResultObj('obj4', 'piece0', layer), ], })) .mockImplementationOnce((_id, _parts, _prev, _parts2, _pieces, layer) => ({ timed: [fakeResultObj('obj5', 'piece1', layer), fakeResultObj('obj6', 'piece0', layer)], future: [ fakeResultObj('obj7', 'piece1', layer), fakeResultObj('obj8', 'piece1', layer), fakeResultObj('obj9', 'piece0', layer), ], })) const res = runPlayoutOperationWithCache( null, 'test', playlistId, PlayoutLockFunctionPriority.USER_PLAYOUT, null, (cache) => getLookeaheadObjects(cache, partInstancesInfo) ) expect(res).toMatchSnapshot() expect(getOrderedPartsAfterPlayheadMock).toHaveBeenCalledTimes(1) expect(getOrderedPartsAfterPlayheadMock).toHaveBeenCalledWith(expect.anything(), 10) // default distance expectLookaheadForLayerMock(playlistId, [], undefined, fakeParts, new Map()) }) testInFiber('Different max distances', () => { const partInstancesInfo: SelectedPartInstancesTimelineInfo = {} // Set really low env.studio.mappings['WHEN_CLEAR'].lookaheadMaxSearchDistance = 0 env.studio.mappings['PRELOAD'].lookaheadMaxSearchDistance = 0 runPlayoutOperationWithCache( null, 'test', playlistId, PlayoutLockFunctionPriority.USER_PLAYOUT, null, (cache) => getLookeaheadObjects(cache, partInstancesInfo) ) expect(getOrderedPartsAfterPlayheadMock).toHaveBeenCalledTimes(1) expect(getOrderedPartsAfterPlayheadMock).toHaveBeenCalledWith(expect.anything(), 0) // really high getOrderedPartsAfterPlayheadMock.mockClear() env.studio.mappings['WHEN_CLEAR'].lookaheadMaxSearchDistance = -1 env.studio.mappings['PRELOAD'].lookaheadMaxSearchDistance = 2000 runPlayoutOperationWithCache( null, 'test', playlistId, PlayoutLockFunctionPriority.USER_PLAYOUT, null, (cache) => getLookeaheadObjects(cache, partInstancesInfo) ) expect(getOrderedPartsAfterPlayheadMock).toHaveBeenCalledTimes(1) expect(getOrderedPartsAfterPlayheadMock).toHaveBeenCalledWith(expect.anything(), 2000) // unset getOrderedPartsAfterPlayheadMock.mockClear() env.studio.mappings['WHEN_CLEAR'].lookaheadMaxSearchDistance = undefined env.studio.mappings['PRELOAD'].lookaheadMaxSearchDistance = -1 runPlayoutOperationWithCache( null, 'test', playlistId, PlayoutLockFunctionPriority.USER_PLAYOUT, null, (cache) => getLookeaheadObjects(cache, partInstancesInfo) ) expect(getOrderedPartsAfterPlayheadMock).toHaveBeenCalledTimes(1) expect(getOrderedPartsAfterPlayheadMock).toHaveBeenCalledWith(expect.anything(), 10) }) testInFiber('PartInstances translation', () => { const fakeParts = partIds.map((p) => ({ _id: p })) as Part[] getOrderedPartsAfterPlayheadMock.mockReturnValue(fakeParts) const partInstancesInfo: SelectedPartInstancesTimelineInfo = { previous: { partInstance: 'abc' as any, nowInPart: 987, pieceInstances: ['1', '2'] as any, }, } const expectedPrevious = { part: partInstancesInfo.previous!.partInstance, onTimeline: true, nowInPart: partInstancesInfo.previous!.nowInPart, allPieces: partInstancesInfo.previous!.pieceInstances, } // With a previous runPlayoutOperationWithCache( null, 'test', playlistId, PlayoutLockFunctionPriority.USER_PLAYOUT, null, (cache) => getLookeaheadObjects(cache, partInstancesInfo) ) expectLookaheadForLayerMock(playlistId, [], expectedPrevious, fakeParts, new Map()) // Add a current partInstancesInfo.current = { partInstance: { _id: 'curr', part: {} } as any, nowInPart: 56, pieceInstances: ['3', '4'] as any, } const expectedCurrent = { part: partInstancesInfo.current!.partInstance, onTimeline: true, nowInPart: partInstancesInfo.current!.nowInPart, allPieces: partInstancesInfo.current!.pieceInstances, } runPlayoutOperationWithCache( null, 'test', playlistId, PlayoutLockFunctionPriority.USER_PLAYOUT, null, (cache) => getLookeaheadObjects(cache, partInstancesInfo) ) expectLookaheadForLayerMock(playlistId, [expectedCurrent], expectedPrevious, fakeParts, new Map()) // Add a next partInstancesInfo.next = { partInstance: 'nxt' as any, nowInPart: -85, pieceInstances: ['5'] as any, } const expectedNext = { part: partInstancesInfo.next!.partInstance, onTimeline: false, nowInPart: partInstancesInfo.next!.nowInPart, allPieces: partInstancesInfo.next!.pieceInstances, } runPlayoutOperationWithCache( null, 'test', playlistId, PlayoutLockFunctionPriority.USER_PLAYOUT, null, (cache) => getLookeaheadObjects(cache, partInstancesInfo) ) expectLookaheadForLayerMock(playlistId, [expectedCurrent, expectedNext], expectedPrevious, fakeParts, new Map()) // current has autonext partInstancesInfo.current.partInstance.part.autoNext = true expectedNext.onTimeline = true runPlayoutOperationWithCache( null, 'test', playlistId, PlayoutLockFunctionPriority.USER_PLAYOUT, null, (cache) => getLookeaheadObjects(cache, partInstancesInfo) ) expectLookaheadForLayerMock(playlistId, [expectedCurrent, expectedNext], expectedPrevious, fakeParts, new Map()) }) // testInFiber('Pieces', () => { // const fakeParts = partIds.map((p) => ({ _id: p })) as Part[] // getOrderedPartsAfterPlayheadMock.mockReturnValue(fakeParts) // const partInstancesInfo: SelectedPartInstancesTimelineInfo = {} // const pieceMap = new Map<PartId, Piece[]>() // partIds.forEach((id, i) => { // const pieces: Piece[] = [] // const target = (i + 2) % 3 // for (let o = 0; o <= target; o++) { // const piece: Piece = { // _id: `piece_${i}_${o}`, // startPartId: id, // startRundownId: rundownId, // invalid: target === 2 && i % 2 === 1, // Some 'randomness' // } as any // Pieces.insert(piece) // if (!piece.invalid) { // pieces.push(piece) // } // } // if (pieces.length > 0) { // pieceMap.set(id, pieces) // } // }) // // Add a couple of pieces which are incorrectly owned // Pieces.insert({ // _id: `piece_a`, // startPartId: partIds[0], // startRundownId: rundownId + '9', // } as any) // Pieces.insert({ // _id: `piece_b`, // startPartId: 'not-real', // startRundownId: rundownId, // } as any) // // pieceMap should have come through valid // ;( // wrapWithCacheForRundownPlaylist(playlist, async (cache) => { // await getLookeaheadObjects(cache, env.studio, playlist, partInstancesInfo) // expect(cache.Pieces.initialized).toBeFalsy() // }) // ) // expectLookaheadForLayerMock(playlist, [], undefined, fakeParts, pieceMap) // // Use the modified cache values // const removedIds: PieceId[] = protectStringArray(['piece_1_0', 'piece_4_0']) // ;( // wrapWithCacheForRundownPlaylist(playlist, async (cache) => { // expect( // cache.Pieces.update(removedIds[0], { // $set: { // invalid: true, // }, // }) // ).toEqual(1) // cache.Pieces.remove(removedIds[1]) // expect(cache.Pieces.initialized).toBeTruthy() // await getLookeaheadObjects(cache, env.studio, playlist, partInstancesInfo) // }) // ) // const pieceMap2 = new Map<PartId, Piece[]>() // for (const [id, pieces] of pieceMap) { // const pieces2 = pieces.filter((p) => !removedIds.includes(p._id)) // if (pieces2.length) pieceMap2.set(id, pieces2) // } // expectLookaheadForLayerMock(playlist, [], undefined, fakeParts, pieceMap2) // }) })
the_stack
import {Dictionary, PointXY, Rotations, Size, extend, isNumber, isString, uuid, map} from "@jsplumb/util" import { Connection } from "../connector/connection-impl" import { Endpoint } from "../endpoint/endpoint" import { JsPlumbInstance } from "../core" import {AnchorLocations, AnchorSpec, FullAnchorSpec, PerimeterAnchorShapes} from "@jsplumb/common" export type AnchorOrientationHint = -1 | 0 | 1 export type Orientation = [ number, number ] export type Face = "top" | "right" | "bottom" | "left" export type Axis = [ Face, Face ] export const X_AXIS_FACES:Axis = ["left", "right"] export const Y_AXIS_FACES:Axis = ["top", "bottom"] /** * @internal */ export type AnchorComputeParams = { xy?: PointXY wh?: Size txy?:PointXY twh?:Size element?:Endpoint timestamp?: string index?:number tElement?:Endpoint connection?:Connection elementId?:string rotation?:Rotations tRotation?:Rotations } /** * @internal */ export interface AnchorRecord { x:number y:number ox:AnchorOrientationHint oy:AnchorOrientationHint offx:number offy:number iox:AnchorOrientationHint ioy:AnchorOrientationHint cls:string } /** * @internal */ export interface ComputedPosition {curX:number,curY:number,ox:number,oy:number,x:number,y:number} export interface LightweightAnchor { locations:Array<AnchorRecord> currentLocation:number locked:boolean id:string cssClass:string isContinuous:boolean isFloating:boolean isDynamic:boolean timestamp:string type:string computedPosition?:ComputedPosition } export interface LightweightPerimeterAnchor extends LightweightAnchor { shape:PerimeterAnchorShapes } export interface LightweightContinuousAnchor extends LightweightAnchor { faces:Array<Face> lockedFace:Face isContinuous:true isDynamic:false currentFace:Face lockedAxis:Axis clockwise:boolean } export class LightweightFloatingAnchor implements LightweightAnchor { isFloating = true isContinuous:false isDynamic:false locations = [ {x:0, y:0, ox:0, oy:0, offx:0, offy:0, iox:0, ioy:0, cls:''} as any] currentLocation = 0 locked = false cssClass = '' timestamp:string = null type = "Floating" id = uuid() orientation:Orientation = [0,0] size:Size constructor(public instance:JsPlumbInstance, public element:any) { this.size = instance.getSize(element) } /** * notification the endpoint associated with this anchor is hovering * over another anchor; we want to assume that anchor's orientation * for the duration of the hover. */ over (endpoint:Endpoint) { this.orientation = this.instance.router.getEndpointOrientation(endpoint) this.locations[0].ox = this.orientation[0] this.locations[0].oy = this.orientation[1] } /** * notification the endpoint associated with this anchor is no * longer hovering over another anchor; we should resume calculating * orientation as we normally do. */ out ():void { this.orientation = null this.locations[0].ox = this.locations[0].iox this.locations[0].oy = this.locations[0].ioy } } const opposites:Dictionary<Face> = {"top": "bottom", "right": "left", "left": "right", "bottom": "top"} const clockwiseOptions:Dictionary<Face> = {"top": "right", "right": "bottom", "left": "top", "bottom": "left"} const antiClockwiseOptions:Dictionary<Face> = {"top": "left", "right": "top", "left": "bottom", "bottom": "right"} /** * * @param a * @internal */ export function getDefaultFace(a:LightweightContinuousAnchor):Face { return a.faces.length === 0 ? "top" : a.faces[0] } function _isFaceAvailable(a:LightweightContinuousAnchor, face:Face):boolean { return a.faces.indexOf(face) !== -1 } function _secondBest(a:LightweightContinuousAnchor, edge:Face):Face { return (a.clockwise ? clockwiseOptions : antiClockwiseOptions)[edge] } function _lastChoice(a:LightweightContinuousAnchor, edge:Face):Face { return (a.clockwise ? antiClockwiseOptions : clockwiseOptions)[edge] } /** * * @param a * @param edge * @internal */ export function isEdgeSupported (a:LightweightContinuousAnchor, edge:Face):boolean { return a.lockedAxis == null ? (a.lockedFace == null ? _isFaceAvailable(a, edge) === true : a.lockedFace === edge) : a.lockedAxis.indexOf(edge) !== -1 } // if the given edge is supported, returns it. otherwise looks for a substitute that _is_ // supported. if none supported we also return the request edge. function verifyFace (a:LightweightContinuousAnchor, edge:Face):Face { //const availableFaces:Array<Face> = _getAvailableFaces(a) if (_isFaceAvailable(a, edge)) { return edge } else if (_isFaceAvailable(a, opposites[edge])) { return opposites[edge] } else { const secondBest = _secondBest(a, edge) if (_isFaceAvailable(a, secondBest)) { return secondBest } else { const lastChoice = _lastChoice(a, edge) if (_isFaceAvailable(a, lastChoice)) { return lastChoice } } } return edge // we have to give them something. } export const TOP = "top" export const BOTTOM = "bottom" export const LEFT = "left" export const RIGHT = "right" const _top = {x:0.5, y:0, ox:0, oy:-1, offx:0, offy:0 }, _bottom = {x:0.5, y:1, ox:0, oy:1, offx:0, offy:0 }, _left = {x:0, y:0.5, ox:-1, oy:0, offx:0, offy:0 }, _right = {x:1, y:0.5, ox:1, oy:0, offx:0, offy:0 }, _topLeft = {x:0, y:0, ox:0, oy:-1, offx:0, offy:0 }, _topRight = {x:1, y:0, ox:1, oy:-1, offx:0, offy:0 }, _bottomLeft = {x:0, y:1, ox:0, oy:1, offx:0, offy:0 }, _bottomRight = {x:1, y:1, ox:0, oy:1, offx:0, offy:0 }, _center = {x:0.5, y:0.5, ox:0, oy:0, offx:0, offy:0 } const namedValues = { "Top":[_top], "Bottom":[_bottom], "Left":[_left], "Right":[_right], "TopLeft":[_topLeft], "TopRight":[_topRight], "BottomLeft":[_bottomLeft], "BottomRight":[_bottomRight], "Center":[_center], "AutoDefault":[_top, _left, _bottom, _right] } const namedContinuousValues = { "Continuous":{faces:[TOP, LEFT, BOTTOM, RIGHT]}, "ContinuousTop":{faces:[TOP]}, "ContinuousRight":{faces:[RIGHT]}, "ContinuousBottom":{faces:[BOTTOM]}, "ContinuousLeft":{faces:[LEFT]}, "ContinuousLeftRight":{faces:[LEFT, RIGHT]}, "ContinuousTopBottom":{faces:[TOP, BOTTOM]} } function getNamedAnchor(name:string, params?:Record<string, any>):LightweightAnchor { params = params || {} if (name === AnchorLocations.Perimeter) { return _createPerimeterAnchor(params) } let a = namedValues[name] if (a != null) { return _createAnchor(name, map(a, (_a:any) => extend({iox:_a.ox, ioy:_a.oy}, _a)), params) } a = namedContinuousValues[name] if (a != null) { return _createContinuousAnchor(name, a.faces, params) } throw {message:"jsPlumb: unknown anchor type '" + name + "'"} } function _createAnchor(type:string, locations:Array<AnchorRecord>, params:Record<string, any>):LightweightAnchor { return { type:type, locations:locations, currentLocation:0, locked:false, id:uuid(), isFloating:false, isContinuous:false, isDynamic:locations.length > 1, timestamp:null, cssClass:params.cssClass || "" } } export function createFloatingAnchor(instance:JsPlumbInstance, element:any):LightweightFloatingAnchor { return new LightweightFloatingAnchor(instance, element) } const PROPERTY_CURRENT_FACE = "currentFace" function _createContinuousAnchor(type:string, faces:Array<Face>, params:Record<string, any>):LightweightContinuousAnchor { const ca:any = { type:type, locations:[], currentLocation:0, locked:false, id:uuid(), cssClass:params.cssClass || "", isFloating:false, isContinuous:true, timestamp:null, faces:params.faces || faces, lockedFace:null, lockedAxis:null, clockwise:!(params.clockwise === false), __currentFace:null } Object.defineProperty(ca, PROPERTY_CURRENT_FACE, { get() { return this.__currentFace }, set(f:Face) { this.__currentFace = verifyFace(this, f) } }) return ca as LightweightContinuousAnchor } function isPrimitiveAnchorSpec(sa:Array<any>):boolean { return sa.length < 7 && sa.every(isNumber) || sa.length === 7 && sa.slice(0, 5).every(isNumber) && isString(sa[6]) } export function makeLightweightAnchorFromSpec(spec:AnchorSpec|Array<AnchorSpec>):LightweightAnchor { // if a string, its just a named anchor if (isString(spec)){ return getNamedAnchor(spec as string, null) } else if (Array.isArray(spec)) { // // if its an array then it can be either: // // - a DynamicAnchor, which is a series of Anchor specs // // - a set of values for a low level Anchor create // // // if all values are numbers (or all numbers and an optional css class as the 7th arg) its a low level create if(isPrimitiveAnchorSpec(spec as Array<AnchorSpec>)) { const _spec = spec as Array<any> return _createAnchor(null, [{ x:_spec[0], y:_spec[1], ox:_spec[2] as AnchorOrientationHint, oy:_spec[3] as AnchorOrientationHint, offx:_spec[4] == null ? 0 : _spec[4], offy:_spec[5] == null ? 0 : _spec[5], iox:_spec[2] as AnchorOrientationHint, ioy:_spec[3] as AnchorOrientationHint, cls:_spec[6] || "" }], {cssClass:_spec[6] || ""}) } else { const locations:Array<AnchorRecord> = map(spec as Array<AnchorSpec>, (aSpec:AnchorSpec) => { if (isString(aSpec)) { let a = namedValues[aSpec as string] // note here we get the 0th location from the named anchor, making the assumption that it has only one (and that 'AutoDefault' has not been // used as an arg for a multiple location anchor) return a != null ? extend({iox:0, ioy:0, cls:""}, a[0]) : null } else if (isPrimitiveAnchorSpec(aSpec as Array<any>)) { return { x:aSpec[0], y:aSpec[1], ox:aSpec[2], oy:aSpec[3], offx:aSpec[4] == null ? 0 : aSpec[4], offy:aSpec[5] == null ? 0 : aSpec[5], iox:aSpec[2], ioy:aSpec[3], cls:aSpec[6] || "" } } }).filter(ar => ar != null) return _createAnchor("Dynamic", locations, {}) } } else { // // if not an array or string, then it's a named Anchor with constructor args const sa = spec as FullAnchorSpec return getNamedAnchor(sa.type, sa.options) } } // --------------- perimeter anchors ---------------------- function circleGenerator(anchorCount:number):Array<AnchorRecord> { const r = 0.5, step = Math.PI * 2 / anchorCount, a:Array<AnchorRecord> = [] let current = 0 for (let i = 0; i < anchorCount; i++) { const x = r + (r * Math.sin(current)), y = r + (r * Math.cos(current)) a.push({ x, y, ox:0, oy:0, offx:0, offy:0, iox:0, ioy:0, cls:'' }) current += step } return a } function _path (segments:Array<any>, anchorCount:number):Array<AnchorRecord> { let anchorsPerFace = anchorCount / segments.length, a:Array<AnchorRecord> = [], _computeFace = (x1:number, y1:number, x2:number, y2:number, fractionalLength:number, ox:AnchorOrientationHint, oy:AnchorOrientationHint) => { anchorsPerFace = anchorCount * fractionalLength; const dx = (x2 - x1) / anchorsPerFace, dy = (y2 - y1) / anchorsPerFace; for (let i = 0; i < anchorsPerFace; i++) { a.push({ x:x1 +(dx * i), y:y1 +(dy * i), ox:ox == null ? 0 : ox, oy:oy == null ? 0 : oy, offx:0, offy:0, iox:0, ioy:0, cls:'' }) } }; for (let i = 0; i < segments.length; i++) { _computeFace.apply(null, segments[i]) } return a; } function shapeGenerator(faces:Array<any>, anchorCount:number):Array<AnchorRecord> { const s:Array<any> = [] for (let i = 0; i < faces.length; i++) { s.push([faces[i][0], faces[i][1], faces[i][2], faces[i][3], 1 / faces.length, faces[i][4], faces[i][5]]) } return _path(s, anchorCount) } function rectangleGenerator(anchorCount:number):Array<AnchorRecord> { return shapeGenerator([ [ 0, 0, 1, 0, 0, -1 ], [ 1, 0, 1, 1, 1, 0 ], [ 1, 1, 0, 1, 0, 1 ], [ 0, 1, 0, 0, -1, 0 ] ], anchorCount); } function diamondGenerator(anchorCount:number):Array<AnchorRecord> { return shapeGenerator([ [ 0.5, 0, 1, 0.5 ], [ 1, 0.5, 0.5, 1 ], [ 0.5, 1, 0, 0.5 ], [ 0, 0.5, 0.5, 0 ] ], anchorCount) } function triangleGenerator(anchorCount:number):Array<AnchorRecord> { return shapeGenerator([ [ 0.5, 0, 1, 1 ], [ 1, 1, 0, 1 ], [ 0, 1, 0.5, 0] ], anchorCount) } function rotate (points:Array<AnchorRecord>, amountInDegrees:number):Array<AnchorRecord> { const o:Array<AnchorRecord> = [], theta = amountInDegrees / 180 * Math.PI for (let i = 0; i < points.length; i++) { const _x = points[i].x - 0.5, _y = points[i].y - 0.5 o.push({ x:0.5 + ((_x * Math.cos(theta)) - (_y * Math.sin(theta))), y:0.5 + ((_x * Math.sin(theta)) + (_y * Math.cos(theta))), ox:points[i].ox, oy:points[i].oy, offx:0, offy:0, iox:0, ioy:0, cls:'' }) } return o } const anchorGenerators:Map<PerimeterAnchorShapes, (anchorCount:number)=>Array<AnchorRecord>> = new Map() anchorGenerators.set(PerimeterAnchorShapes.Circle, circleGenerator) anchorGenerators.set(PerimeterAnchorShapes.Ellipse, circleGenerator) anchorGenerators.set(PerimeterAnchorShapes.Rectangle, rectangleGenerator) anchorGenerators.set(PerimeterAnchorShapes.Square, rectangleGenerator) anchorGenerators.set(PerimeterAnchorShapes.Diamond, diamondGenerator) anchorGenerators.set(PerimeterAnchorShapes.Triangle, triangleGenerator) export function _createPerimeterAnchor(params:Record<string, any>):LightweightPerimeterAnchor { params = params || {} const anchorCount = params.anchorCount || 60, shape:PerimeterAnchorShapes = params.shape if (!shape) { throw new Error("no shape supplied to Perimeter Anchor type"); } if (!anchorGenerators.has(shape)) { throw new Error("Shape [" + shape + "] is unknown by Perimeter Anchor type"); } let da = anchorGenerators.get(shape)(anchorCount) if (params.rotation) { da = rotate(da, params.rotation) } const a = _createAnchor(AnchorLocations.Perimeter, da, params) const aa = extend(a as any, { shape }) as LightweightPerimeterAnchor return aa }
the_stack
import { DebugElement } from '@angular/core'; import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { MatButtonModule, MatCardModule, MatIconModule, MatInputModule, MatPaginatorModule, MatSelectModule, MatToolbarModule } from '@angular/material'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { ActivatedRoute } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { provideMockActions } from '@ngrx/effects/testing'; import { Action, Store, StoreModule } from '@ngrx/store'; import { cold, hot } from 'jasmine-marbles'; import { Observable } from 'rxjs/Observable'; import { of } from 'rxjs/observable/of'; import { OpenSideNavAction } from '../app.actions'; import { Direction, Item, Page, Status } from '../shared/entity'; import { ItemService } from '../shared/service/item/item.service'; import { ToolbarModule } from '../shared/toolbar/toolbar.module'; import { Search, SearchActions, SearchSuccess } from './search.actions'; import { SearchComponent, StatusesViewValue } from './search.component'; import { SearchEffects } from './search.effects'; import * as fromSearch from './search.reducer'; import { searchRequest, searchResults } from './search.reducer'; import { TruncateModule } from 'ng2-truncate'; import { AppState } from '#app/app.reducer'; import { ComponentTester } from 'ngx-speculoos'; class SearchComponentTester extends ComponentTester<SearchComponent> { constructor() { super(SearchComponent); } get results() { return this.elements('.search__results mat-card'); } get q() { return this.input('input[name="q"]'); } get tags() { return this.input('input[name="tags"]'); } get status() { return this.element('mat-select[name="status"]') .debugElement.componentInstance; } get property() { return this.element('mat-select[name="property"]') .debugElement.componentInstance; } get direction() { return this.element('mat-select[name="direction"]') .debugElement.componentInstance; } get topPaginator() { return this.elements('mat-paginator')[0]; } } const searchResult = { content: [ { id: '33c98205-51dd-4245-a86b-6c725121684d', cover: { id: 'c1faeff7-72e5-4c4e-b394-acbc6399a377', url: '/', width: 1280, height: 720 }, title: 'Net Neutrality Update: Last Week Tonight with John Oliver (Web Exclusive)', url: 'https: //www.youtube.com/watch?v=qI5y-_sqJT0', mimeType: 'video/mp4', status: 'FINISH', creationDate: '2017-05-15T05: 01: 23.372+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/85366aef-5cfe-4716-9891-347d3f70150b/items/33c98205-51dd-4245-a86b-6c725121684d/download.mp4', podcast: { id: '85366aef-5cfe-4716-9891-347d3f70150b' } }, { id: 'fdf9d570-9386-483b-8d78-e8e0657c9feb', cover: { id: '22f2c6b6-1230-46c9-84be-9f3f6e2b2d03', url: '/', width: 200, height: 200 }, title: "RMC : 14/05 - L'Afterfoot - 23h-0h", url: 'http: //podcast.rmc.fr/channel59/20170514_afterfoot_9.mp3', mimeType: 'audio/mpeg', status: 'FINISH', creationDate: '2017-05-15T01: 01: 38.141+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/8e99045e-c685-4757-9f93-d67d6d125332/items/fdf9d570-9386-483b-8d78-e8e0657c9feb/download.mp3', podcast: { id: '8e99045e-c685-4757-9f93-d67d6d125332' } }, { id: '124e8f13-29cb-4c96-9423-2988a4d335d4', cover: { id: '111cf8d9-e1e3-40f3-84e4-35e93eba0120', url: '/', width: 200, height: 200 }, title: 'RMC : 14/05 - Intégrale Foot - 22h-23h', url: 'http: //podcast.rmc.fr/channel245/20170514_integrale_foot_2.mp3', mimeType: 'audio/mpeg', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.921+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/9c8e10ea-e61c-4985-9944-95697a6c0c97/items/124e8f13-29cb-4c96-9423-2988a4d335d4/download.mp3', podcast: { id: '9c8e10ea-e61c-4985-9944-95697a6c0c97' } }, { id: '78cfdb14-31bc-4c8d-bb63-a2c1740aa2fb', cover: { id: '4f3cc31a-2991-40de-a9fe-b6f0f6e8da1f', url: '/', width: 200, height: 200 }, title: 'RMC : 14/05 - Intégrale Foot - 22h-23h', url: 'http: //podcast.rmc.fr/channel245/20170514_integrale_foot_2.mp3', mimeType: 'audio/mpeg', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.61+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/299ffb9c-45c5-4568-bc55-703befdc6562/items/78cfdb14-31bc-4c8d-bb63-a2c1740aa2fb/download.mp3', podcast: { id: '299ffb9c-45c5-4568-bc55-703befdc6562' } }, { id: '4fd34d58-9f4d-417b-a2d1-f5e3a5b25219', cover: { id: '111cf8d9-e1e3-40f3-84e4-35e93eba0120', url: '/', width: 200, height: 200 }, title: 'RMC : 14/05 - Intégrale Foot - 21h-22h', url: 'http: //podcast.rmc.fr/channel245/20170514_integrale_foot_1.mp3', mimeType: 'audio/mpeg', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.92+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/9c8e10ea-e61c-4985-9944-95697a6c0c97/items/4fd34d58-9f4d-417b-a2d1-f5e3a5b25219/download.mp3', podcast: { id: '9c8e10ea-e61c-4985-9944-95697a6c0c97' } }, { id: 'f2ced3ce-13de-44b0-9ec2-faf8200c5282', cover: { id: '4f3cc31a-2991-40de-a9fe-b6f0f6e8da1f', url: '/', width: 200, height: 200 }, title: 'RMC : 14/05 - Intégrale Foot - 21h-22h', url: 'http: //podcast.rmc.fr/channel245/20170514_integrale_foot_1.mp3', mimeType: 'audio/mpeg', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.61+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/299ffb9c-45c5-4568-bc55-703befdc6562/items/f2ced3ce-13de-44b0-9ec2-faf8200c5282/download.mp3', podcast: { id: '299ffb9c-45c5-4568-bc55-703befdc6562' } }, { id: '403ad0b2-da32-4c62-beba-c5fa955ac75a', cover: { id: '4f3cc31a-2991-40de-a9fe-b6f0f6e8da1f', url: '/', width: 200, height: 200 }, title: 'RMC : 14/05 - Intégrale Foot - 20h-21h', url: 'http: //podcast.rmc.fr/channel245/20170514_integrale_foot_0.mp3', mimeType: 'audio/mpeg', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.609+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/299ffb9c-45c5-4568-bc55-703befdc6562/items/403ad0b2-da32-4c62-beba-c5fa955ac75a/download.mp3', podcast: { id: '299ffb9c-45c5-4568-bc55-703befdc6562' } }, { id: '667dcaa4-c945-4a04-baf8-a3b16924e9cb', cover: { id: '111cf8d9-e1e3-40f3-84e4-35e93eba0120', url: '/', width: 200, height: 200 }, title: 'RMC : 14/05 - Intégrale Foot - 20h-21h', url: 'http: //podcast.rmc.fr/channel245/20170514_integrale_foot_0.mp3', mimeType: 'audio/mpeg', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.916+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/9c8e10ea-e61c-4985-9944-95697a6c0c97/items/667dcaa4-c945-4a04-baf8-a3b16924e9cb/download.mp3', podcast: { id: '9c8e10ea-e61c-4985-9944-95697a6c0c97' } }, { id: '00b2310f-4a42-4959-a515-1e5b21defc4e', cover: { id: 'fc571904-0d60-4f40-b561-351e568acef0', url: '/', width: 600, height: 1 }, title: 'Les épisodes de la semaine du 08 mai', url: 'http: //www.6play.fr/le-message-de-madenian-et-vdb-p_6730/les-episodes-de-la-semaine-du-08-mai-c_11686278', mimeType: 'video/mp4', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.68+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/624831fb-722c-49e6-ba44-256c194c8f66/items/00b2310f-4a42-4959-a515-1e5b21defc4e/download.mp4', podcast: { id: '624831fb-722c-49e6-ba44-256c194c8f66' } }, { id: '7b1d8095-6d0b-427f-a842-f74e0f935633', cover: { id: 'fa9f8213-6d44-405f-823d-cf9747007f0f', url: '/', width: 1400, height: 1400 }, title: 'WannaCry', url: 'https: //www.nolimitsecu.fr/wp-content/uploads/NoLimitSecu-WannaCry.mp3', mimeType: 'audio/mpeg', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.595+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/102c6319-1b46-40ae-8cca-bc4fd8ba0789/items/7b1d8095-6d0b-427f-a842-f74e0f935633/download.mp3', podcast: { id: '102c6319-1b46-40ae-8cca-bc4fd8ba0789' } }, { id: 'ab3d517d-b484-4207-9300-726a4a872a3f', cover: { id: '9218eef8-c4e6-4d41-acf2-00cb7537f958', url: '/', width: 640, height: 480 }, title: "King's Quest Chapitre V - 01 - 'la part du gâteux' [4K60fps]", url: 'https: //www.youtube.com/watch?v=sohRCKdg1O0', mimeType: 'video/mp4', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.942+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/daf66f11-835c-48ac-9713-98b6d2a0cef3/items/ab3d517d-b484-4207-9300-726a4a872a3f/download.mp4', podcast: { id: 'daf66f11-835c-48ac-9713-98b6d2a0cef3' } }, { id: '01bc6166-a690-4372-9889-bbb69b83a87d', cover: { id: '866762c9-fd92-4277-bbb7-17c67b593ef5', url: '/', width: 200, height: 200 }, title: 'Yet Another Podcast #170 – Windows Template Studio', url: 'http: //jesseliberty.com/wp-content/media/Show170.mp3', mimeType: 'audio/mpeg', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.353+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/040731fe-1c0f-45a0-8672-1bd85fdef0c4/items/01bc6166-a690-4372-9889-bbb69b83a87d/download.mp3', podcast: { id: '040731fe-1c0f-45a0-8672-1bd85fdef0c4' } } ], totalPages: 259, totalElements: 3108, last: false, numberOfElements: 12, sort: [ { direction: 'DESC', property: 'pubDate', ignoreCase: false, nullHandling: 'NATIVE', descending: true, ascending: false } ], first: true, size: 12, number: 0 }; const request = { q: '', page: 0, size: 12, status: [], tags: [], sort: [{ property: 'pubDate', direction: Direction.DESC }] }; xdescribe('SearchFeature', () => { describe('"SearchEffects', () => { let effects: SearchEffects; let actions: Observable<Action>; let itemService: ItemService; const PAGE: Page<Item> = { content: [ { id: '33c98205-51dd-4245-a86b-6c725121684d', cover: { id: 'c1faeff7-72e5-4c4e-b394-acbc6399a377', url: '/api/podcasts/85366aef-5cfe-4716-9891-347d3f70150b/items/33c98205-51dd-4245-a86b-6c725121684d/cover.jpg', width: 1280, height: 720 }, title: 'Net Neutrality Update: Last Week Tonight with John Oliver (Web Exclusive)', url: 'https: //www.youtube.com/watch?v=qI5y-_sqJT0', mimeType: 'video/mp4', status: 'FINISH', creationDate: '2017-05-15T05: 01: 23.372+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/85366aef-5cfe-4716-9891-347d3f70150b/items/33c98205-51dd-4245-a86b-6c725121684d/download.mp4', podcast: { id: '85366aef-5cfe-4716-9891-347d3f70150b' } }, { id: 'fdf9d570-9386-483b-8d78-e8e0657c9feb', cover: { id: '22f2c6b6-1230-46c9-84be-9f3f6e2b2d03', url: '/api/podcasts/8e99045e-c685-4757-9f93-d67d6d125332/cover.jpg', width: 200, height: 200 }, title: "RMC : 14/05 - L'Afterfoot - 23h-0h", url: 'http: //podcast.rmc.fr/channel59/20170514_afterfoot_9.mp3', mimeType: 'audio/mpeg', status: 'FINISH', creationDate: '2017-05-15T01: 01: 38.141+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/8e99045e-c685-4757-9f93-d67d6d125332/items/fdf9d570-9386-483b-8d78-e8e0657c9feb/download.mp3', podcast: { id: '8e99045e-c685-4757-9f93-d67d6d125332' } }, { id: '124e8f13-29cb-4c96-9423-2988a4d335d4', cover: { id: '111cf8d9-e1e3-40f3-84e4-35e93eba0120', url: '/api/podcasts/9c8e10ea-e61c-4985-9944-95697a6c0c97/cover.jpeg', width: 200, height: 200 }, title: 'RMC : 14/05 - Intégrale Foot - 22h-23h', url: 'http: //podcast.rmc.fr/channel245/20170514_integrale_foot_2.mp3', mimeType: 'audio/mpeg', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.921+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/9c8e10ea-e61c-4985-9944-95697a6c0c97/items/124e8f13-29cb-4c96-9423-2988a4d335d4/download.mp3', podcast: { id: '9c8e10ea-e61c-4985-9944-95697a6c0c97' } }, { id: '78cfdb14-31bc-4c8d-bb63-a2c1740aa2fb', cover: { id: '4f3cc31a-2991-40de-a9fe-b6f0f6e8da1f', url: '/api/podcasts/299ffb9c-45c5-4568-bc55-703befdc6562/cover.jpeg', width: 200, height: 200 }, title: 'RMC : 14/05 - Intégrale Foot - 22h-23h', url: 'http://podcast.rmc.fr/channel245/20170514_integrale_foot_2.mp3', mimeType: 'audio/mpeg', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.61+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/299ffb9c-45c5-4568-bc55-703befdc6562/items/78cfdb14-31bc-4c8d-bb63-a2c1740aa2fb/download.mp3', podcast: { id: '299ffb9c-45c5-4568-bc55-703befdc6562' } }, { id: '4fd34d58-9f4d-417b-a2d1-f5e3a5b25219', cover: { id: '111cf8d9-e1e3-40f3-84e4-35e93eba0120', url: '/api/podcasts/9c8e10ea-e61c-4985-9944-95697a6c0c97/cover.jpeg', width: 200, height: 200 }, title: 'RMC : 14/05 - Intégrale Foot - 21h-22h', url: 'http: //podcast.rmc.fr/channel245/20170514_integrale_foot_1.mp3', mimeType: 'audio/mpeg', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.92+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/9c8e10ea-e61c-4985-9944-95697a6c0c97/items/4fd34d58-9f4d-417b-a2d1-f5e3a5b25219/download.mp3', podcast: { id: '9c8e10ea-e61c-4985-9944-95697a6c0c97' } }, { id: 'f2ced3ce-13de-44b0-9ec2-faf8200c5282', cover: { id: '4f3cc31a-2991-40de-a9fe-b6f0f6e8da1f', url: '/api/podcasts/299ffb9c-45c5-4568-bc55-703befdc6562/cover.jpeg', width: 200, height: 200 }, title: 'RMC : 14/05 - Intégrale Foot - 21h-22h', url: 'http: //podcast.rmc.fr/channel245/20170514_integrale_foot_1.mp3', mimeType: 'audio/mpeg', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.61+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/299ffb9c-45c5-4568-bc55-703befdc6562/items/f2ced3ce-13de-44b0-9ec2-faf8200c5282/download.mp3', podcast: { id: '299ffb9c-45c5-4568-bc55-703befdc6562' } }, { id: '403ad0b2-da32-4c62-beba-c5fa955ac75a', cover: { id: '4f3cc31a-2991-40de-a9fe-b6f0f6e8da1f', url: '/api/podcasts/299ffb9c-45c5-4568-bc55-703befdc6562/cover.jpeg', width: 200, height: 200 }, title: 'RMC : 14/05 - Intégrale Foot - 20h-21h', url: 'http: //podcast.rmc.fr/channel245/20170514_integrale_foot_0.mp3', mimeType: 'audio/mpeg', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.609+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/299ffb9c-45c5-4568-bc55-703befdc6562/items/403ad0b2-da32-4c62-beba-c5fa955ac75a/download.mp3', podcast: { id: '299ffb9c-45c5-4568-bc55-703befdc6562' } }, { id: '667dcaa4-c945-4a04-baf8-a3b16924e9cb', cover: { id: '111cf8d9-e1e3-40f3-84e4-35e93eba0120', url: '/api/podcasts/9c8e10ea-e61c-4985-9944-95697a6c0c97/cover.jpeg', width: 200, height: 200 }, title: 'RMC : 14/05 - Intégrale Foot - 20h-21h', url: 'http: //podcast.rmc.fr/channel245/20170514_integrale_foot_0.mp3', mimeType: 'audio/mpeg', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.916+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/9c8e10ea-e61c-4985-9944-95697a6c0c97/items/667dcaa4-c945-4a04-baf8-a3b16924e9cb/download.mp3', podcast: { id: '9c8e10ea-e61c-4985-9944-95697a6c0c97' } }, { id: '00b2310f-4a42-4959-a515-1e5b21defc4e', cover: { id: 'fc571904-0d60-4f40-b561-351e568acef0', url: '/api/podcasts/624831fb-722c-49e6-ba44-256c194c8f66/items/00b2310f-4a42-4959-a515-1e5b21defc4e/cover.', width: 600, height: 1 }, title: 'Les épisodes de la semaine du 08 mai', url: 'http: //www.6play.fr/le-message-de-madenian-et-vdb-p_6730/les-episodes-de-la-semaine-du-08-mai-c_11686278', mimeType: 'video/mp4', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.68+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/624831fb-722c-49e6-ba44-256c194c8f66/items/00b2310f-4a42-4959-a515-1e5b21defc4e/download.mp4', podcast: { id: '624831fb-722c-49e6-ba44-256c194c8f66' } }, { id: '7b1d8095-6d0b-427f-a842-f74e0f935633', cover: { id: 'fa9f8213-6d44-405f-823d-cf9747007f0f', url: '/api/podcasts/102c6319-1b46-40ae-8cca-bc4fd8ba0789/cover.png', width: 1400, height: 1400 }, title: 'WannaCry', url: 'https: //www.nolimitsecu.fr/wp-content/uploads/NoLimitSecu-WannaCry.mp3', mimeType: 'audio/mpeg', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.595+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/102c6319-1b46-40ae-8cca-bc4fd8ba0789/items/7b1d8095-6d0b-427f-a842-f74e0f935633/download.mp3', podcast: { id: '102c6319-1b46-40ae-8cca-bc4fd8ba0789' } }, { id: 'ab3d517d-b484-4207-9300-726a4a872a3f', cover: { id: '9218eef8-c4e6-4d41-acf2-00cb7537f958', url: '/api/podcasts/daf66f11-835c-48ac-9713-98b6d2a0cef3/items/ab3d517d-b484-4207-9300-726a4a872a3f/cover.jpg', width: 640, height: 480 }, title: "King's Quest Chapitre V - 01 - 'la part du gâteux' [4K60fps]", url: 'https: //www.youtube.com/watch?v=sohRCKdg1O0', mimeType: 'video/mp4', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.942+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/daf66f11-835c-48ac-9713-98b6d2a0cef3/items/ab3d517d-b484-4207-9300-726a4a872a3f/download.mp4', podcast: { id: 'daf66f11-835c-48ac-9713-98b6d2a0cef3' } }, { id: '01bc6166-a690-4372-9889-bbb69b83a87d', cover: { id: '866762c9-fd92-4277-bbb7-17c67b593ef5', url: '/api/podcasts/040731fe-1c0f-45a0-8672-1bd85fdef0c4/cover.png', width: 200, height: 200 }, title: 'Yet Another Podcast #170 – Windows Template Studio', url: 'http: //jesseliberty.com/wp-content/media/Show170.mp3', mimeType: 'audio/mpeg', status: 'FINISH', creationDate: '2017-05-14T23: 33: 56.353+02: 00', isDownloaded: true, proxyURL: '/api/podcasts/040731fe-1c0f-45a0-8672-1bd85fdef0c4/items/01bc6166-a690-4372-9889-bbb69b83a87d/download.mp3', podcast: { id: '040731fe-1c0f-45a0-8672-1bd85fdef0c4' } } ], totalPages: 259, totalElements: 3108, last: false, numberOfElements: 12, sort: [ { direction: 'DESC', property: 'pubDate', ignoreCase: false, nullHandling: 'NATIVE', descending: true, ascending: false } ], first: true, size: 12, number: 0 }; const request = { q: '', page: 0, size: 12, status: [], tags: [], sort: [{ property: 'pubDate', direction: Direction.DESC }] }; beforeEach(() => { // @ts-ignore itemService = { search: jest.fn() }; (itemService.search as jest.Mock<Page<Item>>).mockReturnValue(of(PAGE)); }); beforeEach(() => { TestBed.configureTestingModule({ providers: [SearchEffects, provideMockActions(() => actions), { provide: ItemService, useValue: itemService }] }); effects = TestBed.get(SearchEffects); }); describe('search$', () => { it( 'should trigger search', async(() => { /* Given */ actions = hot('--a-', { a: new Search(request) }); const expected = cold('--b', { b: new SearchSuccess(PAGE) }); expect(effects.search$).toBeObservable(expected); expect(itemService.search).toHaveBeenCalledWith(request); }) ); }); }); }); describe('SearchModule', () => { let tester: SearchComponentTester; let store: Store<AppState>; beforeEach(async(() => { // @ts-ignore TestBed.configureTestingModule({ declarations: [SearchComponent], imports: [ ReactiveFormsModule, RouterTestingModule, NoopAnimationsModule, MatCardModule, MatButtonModule, MatIconModule, MatInputModule, MatSelectModule, MatPaginatorModule, MatToolbarModule, ToolbarModule, TruncateModule, StoreModule.forRoot([]), StoreModule.forFeature('search', fromSearch.search) ] }).compileComponents(); })); beforeEach(() => { store = TestBed.get(Store); spyOn(store, 'dispatch').and.callThrough(); }); beforeEach(async(() => { tester = new SearchComponentTester(); tester.detectChanges(); })); it('should create', async(() => { expect(tester.componentInstance).toBeTruthy(); })); it('should display elements on this page', async(() => { /* Given */ /* When */ store.dispatch(new SearchSuccess(searchResult)); tester.detectChanges(); /* Then */ expect(tester.results.length).toEqual(12); })); it('should have default value for search form', async(() => { /* Given */ /* When */ store.dispatch(new Search(request)); tester.detectChanges(); /* Then */ expect(tester.q.value).toEqual(''); expect(tester.tags.value).toEqual(''); expect(tester.status.selected.value).toBe(StatusesViewValue.ALL); expect(tester.property.selected.value).toBe('pubDate') expect(tester.direction.selected.value).toBe(Direction.DESC); })); it('should be initialized with tags list', async(() => { /* Given */ const tagRequest = {...request, tags: [{ name: 'Foo' }, { name: 'Bar' }]} /* When */ store.dispatch(new Search(tagRequest)); tester.detectChanges(); /* Then */ expect(tester.tags.value).toBe('Foo, Bar'); })); it('should be initialized with FINISH status', async(() => { /* Given */ const statusRequest = { ...request, status: [Status.FINISH]}; /* When */ store.dispatch(new Search(statusRequest)); tester.detectChanges(); /* Then */ expect(tester.status.selected.value).toBe(StatusesViewValue.DOWNLOADED); })); it('should be initialized with NOT_DOWNLOADED status', async(() => { /* Given */ const statusRequest = { ...request, status: [Status.NOT_DOWNLOADED]}; /* When */ store.dispatch(new Search(statusRequest)); tester.detectChanges(); /* Then */ expect(tester.status.selected.value).toBe(StatusesViewValue.NOT_DOWNLOADED); })); it('should be initialized with ALL status', async(() => { /* Given */ const statusRequest = { ...request, status: []}; /* When */ store.dispatch(new Search(statusRequest)); tester.detectChanges(); /* Then */ expect(tester.status.selected.value).toBe(StatusesViewValue.ALL); })); it('should init pager', () => { /* Given */ const topPaginator = tester.topPaginator; /* When */ console.log(topPaginator.debugElement); /* Then */ }); });
the_stack
* @author Richard <richardo2016@gmail.com> * */ /// <reference path="Buffer.d.ts" /> /// <reference path="BufferedStream.d.ts" /> /// <reference path="Chain.d.ts" /> /// <reference path="Cipher.d.ts" /> /// <reference path="Condition.d.ts" /> /// <reference path="DbConnection.d.ts" /> /// <reference path="DgramSocket.d.ts" /> /// <reference path="Digest.d.ts" /> /// <reference path="Event.d.ts" /> /// <reference path="EventEmitter.d.ts" /> /// <reference path="EventInfo.d.ts" /> /// <reference path="Fiber.d.ts" /> /// <reference path="File.d.ts" /> /// <reference path="Handler.d.ts" /> /// <reference path="HandlerEx.d.ts" /> /// <reference path="HeapGraphEdge.d.ts" /> /// <reference path="HeapGraphNode.d.ts" /> /// <reference path="HeapSnapshot.d.ts" /> /// <reference path="HttpClient.d.ts" /> /// <reference path="HttpCollection.d.ts" /> /// <reference path="HttpCookie.d.ts" /> /// <reference path="HttpHandler.d.ts" /> /// <reference path="HttpMessage.d.ts" /> /// <reference path="HttpRequest.d.ts" /> /// <reference path="HttpResponse.d.ts" /> /// <reference path="HttpServer.d.ts" /> /// <reference path="HttpUploadData.d.ts" /> /// <reference path="HttpsServer.d.ts" /> /// <reference path="Image.d.ts" /> /// <reference path="Int64.d.ts" /> /// <reference path="LevelDB.d.ts" /> /// <reference path="Lock.d.ts" /> /// <reference path="LruCache.d.ts" /> /// <reference path="MSSQL.d.ts" /> /// <reference path="MemoryStream.d.ts" /> /// <reference path="Message.d.ts" /> /// <reference path="MongoCollection.d.ts" /> /// <reference path="MongoCursor.d.ts" /> /// <reference path="MongoDB.d.ts" /> /// <reference path="MongoID.d.ts" /> /// <reference path="MySQL.d.ts" /> /// <reference path="PKey.d.ts" /> /// <reference path="Redis.d.ts" /> /// <reference path="RedisHash.d.ts" /> /// <reference path="RedisList.d.ts" /> /// <reference path="RedisSet.d.ts" /> /// <reference path="RedisSortedSet.d.ts" /> /// <reference path="Routing.d.ts" /> /// <reference path="SQLite.d.ts" /> /// <reference path="SandBox.d.ts" /> /// <reference path="SeekableStream.d.ts" /> /// <reference path="Semaphore.d.ts" /> /// <reference path="Service.d.ts" /> /// <reference path="Smtp.d.ts" /> /// <reference path="Socket.d.ts" /> /// <reference path="SslHandler.d.ts" /> /// <reference path="SslServer.d.ts" /> /// <reference path="SslSocket.d.ts" /> /// <reference path="Stat.d.ts" /> /// <reference path="Stats.d.ts" /> /// <reference path="Stream.d.ts" /> /// <reference path="StringDecoder.d.ts" /> /// <reference path="SubProcess.d.ts" /> /// <reference path="TcpServer.d.ts" /> /// <reference path="Timer.d.ts" /> /// <reference path="UrlObject.d.ts" /> /// <reference path="WebSocket.d.ts" /> /// <reference path="WebSocketMessage.d.ts" /> /// <reference path="WebView.d.ts" /> /// <reference path="Worker.d.ts" /> /// <reference path="X509Cert.d.ts" /> /// <reference path="X509Crl.d.ts" /> /// <reference path="X509Req.d.ts" /> /// <reference path="XmlAttr.d.ts" /> /// <reference path="XmlCDATASection.d.ts" /> /// <reference path="XmlCharacterData.d.ts" /> /// <reference path="XmlComment.d.ts" /> /// <reference path="XmlDocument.d.ts" /> /// <reference path="XmlDocumentType.d.ts" /> /// <reference path="XmlElement.d.ts" /> /// <reference path="XmlNamedNodeMap.d.ts" /> /// <reference path="XmlNode.d.ts" /> /// <reference path="XmlNodeList.d.ts" /> /// <reference path="XmlProcessingInstruction.d.ts" /> /// <reference path="XmlText.d.ts" /> /// <reference path="ZipFile.d.ts" /> /// <reference path="ZmqSocket.d.ts" /> /// <reference path="object.d.ts" /> /** module Or Internal Object */ /** * @brief 文件系统处理模块 * @detail 使用方法:,```JavaScript,var fs = require('fs');,``` */ declare module "fs" { module fs { /** * * @brief seek 方式常量,移动到绝对位置 * * */ export const SEEK_SET = 0; /** * * @brief seek 方式常量,移动到当前位置的相对位置 * * */ export const SEEK_CUR = 1; /** * * @brief seek 方式常量,移动到文件结尾的相对位置 * * */ export const SEEK_END = 2; /** * * ! fs模块的常量对象 * * */ export const constants: Object; /** * * @brief 查询指定的文件或目录是否存在 * @param path 指定要查询的路径 * @return 返回 True 表示文件或目录存在 * * * @async */ export function exists(path: string): boolean; /** * * @brief 查询用户对指定的文件的权限 * @param path 指定要查询的路径 * @param mode 指定查询的权限,默认为文件是否存在 * * * @async */ export function access(path: string, mode?: number/** = 0*/): void; /** * * @brief 创建硬链接文件, windows 下不支持此方法 * @param oldPath 源文件 * @param newPath 将要被创建的文件 * * * @async */ export function link(oldPath: string, newPath: string): void; /** * * @brief 删除指定的文件 * @param path 指定要删除的路径 * * * @async */ export function unlink(path: string): void; /** * * @brief 创建一个目录 * @param path 指定要创建的目录名 * @param mode 指定文件权限,Windows 忽略此参数 * * * @async */ export function mkdir(path: string, mode?: number/** = 0777*/): void; /** * * @brief 删除一个目录 * @param path 指定要删除的目录名 * * * @async */ export function rmdir(path: string): void; /** * * @brief 重新命名一个文件 * @param from 指定更名的文件 * @param to 指定要修改的新文件名 * * * @async */ export function rename(from: string, to: string): void; /** * * @brief 复制一个文件 * @param from 指定更名的文件 * @param to 指定要修改的新文件名 * * * @async */ export function copy(from: string, to: string): void; /** * * @brief 设置指定文件的访问权限,Windows 不支持此方法 * @param path 指定操作的文件 * @param mode 指定设定的访问权限 * * * @async */ export function chmod(path: string, mode: number): void; /** * * @brief 设置指定文件的访问权限,若文件是软连接则不改变指向文件的权限,只在macOS、BSD 系列平台上可用 * @param path 指定操作的文件 * @param mode 指定设定的访问权限 * * * @async */ export function lchmod(path: string, mode: number): void; /** * * @brief 设置指定文件的拥有者,Windows 不支持此方法 * @param path 指定设置的文件 * @param uid 文件拥有者用户id * @param gid 文件拥有者组id * * * @async */ export function chown(path: string, uid: number, gid: number): void; /** * * @brief 设置指定文件的拥有者,如果指定的文件是软连接则不会改变其指向文件的拥有者,Windows 不支持此方法 * @param path 指定设置的文件 * @param uid 文件拥有者用户id * @param gid 文件拥有者组id * * * @async */ export function lchown(path: string, uid: number, gid: number): void; /** * * @brief 查询指定文件的基础信息 * @param path 指定查询的文件 * @return 返回文件的基础信息 * * * @async */ export function stat(path: string): Class_Stat; /** * * @brief 查询指定文件的基础信息, 和stat不同的是, 当path是一个软连接的时候,返回的将是这个软连接的信息而不是指向的文件的信息 * @param path 指定查询的文件 * @return 返回文件的基础信息 * * * @async */ export function lstat(path: string): Class_Stat; /** * * @brief 读取指定的软连接文件, windows 下不支持此方法 * @param path 指定读取的软连接文件 * @return 返回软连接指向的文件名 * * * @async */ export function readlink(path: string): string; /** * * @brief 返回指定路径的绝对路径,如果指定路径中包含相对路径也会被展开 * @param path 指定读取的路径 * @return 返回处理后的绝对路径 * * * @async */ export function realpath(path: string): string; /** * * @brief 创建软连接文件 * @param target 目标文件,可以是文件、目录、或不存在的路径 * @param linkpath 将被创建的软连接文件 * @param type 创建的软连接类型, 可选类型为'file', 'dir', 'junction', 默认为'file', 该参数只在windows上有效,当为'junction'的时候将要创建的目标路径linkpath必须为绝对路径, 而target则会被自动转化为绝对路径。 * * * @async */ export function symlink(target: string, linkpath: string, type?: string/** = "file"*/): void; /** * * @brief 修改文件尺寸,如果指定的长度大于源文件大小则用'\0'填充,否则多于的文件内容将丢失 * @param path 指定被修改文件的路径 * @param len 指定修改后文件的大小 * * * @async */ export function truncate(path: string, len: number): void; /** * * @brief 根据文件描述符,读取文件内容 * @param fd 文件描述符 * @param buffer 读取结果写入的 Buffer 对象 * @param offset Buffer 写入偏移量, 默认为 0 * @param length 文件读取字节数,默认为 0 * @param position 文件读取位置,默认为当前文件位置 * @return 实际读取的字节数 * * * @async */ export function read(fd: number, buffer: Class_Buffer, offset?: number/** = 0*/, length?: number/** = 0*/, position?: number/** = -1*/): number; /** * * @brief 根据文件描述符,改变文件模式。只在 POSIX 系统有效。 * @param fd 文件描述符 * @param mode 文件的模式 * * * @async */ export function fchmod(fd: number, mode: number): void; /** * * @brief 根据文件描述符,改变所有者。只在 POSIX 系统有效。 * @param fd 文件描述符 * @param uid 用户id * @param gid 组id * * * @async */ export function fchown(fd: number, uid: number, gid: number): void; /** * * @brief 根据文件描述符,同步数据到磁盘 * @param fd 文件描述符 * * * @async */ export function fdatasync(fd: number): void; /** * * @brief 根据文件描述符,同步数据到磁盘 * @param fd 文件描述符 * * * @async */ export function fsync(fd: number): void; /** * * @brief 读取指定目录的文件信息 * @param path 指定查询的目录 * @return 返回目录的文件信息数组 * * * @async */ export function readdir(path: string): any[]; /** * * @brief 打开文件,用于读取,写入,或者同时读写 * * 参数 flags 支持的方式如下: * - 'r' 只读方式,文件不存在则抛出错误。 * - 'r+' 读写方式,文件不存在则抛出错误。 * - 'w' 只写方式,文件不存在则自动创建,存在则将被清空。 * - 'w+' 读写方式,文件不存在则自动创建。 * - 'a' 只写添加方式,文件不存在则自动创建。 * - 'a+' 读写添加方式,文件不存在则自动创建。 * @param fname 指定文件名 * @param flags 指定文件打开方式,缺省为 "r",只读方式 * @return 返回打开的文件对象 * * * @async */ export function openFile(fname: string, flags?: string/** = "r"*/): Class_SeekableStream; /** * * @brief 打开文件描述符 * * 参数 flags 支持的方式如下: * - 'r' 只读方式,文件不存在则抛出错误。 * - 'r+' 读写方式,文件不存在则抛出错误。 * - 'w' 只写方式,文件不存在则自动创建,存在则将被清空。 * - 'w+' 读写方式,文件不存在则自动创建。 * - 'a' 只写添加方式,文件不存在则自动创建。 * - 'a+' 读写添加方式,文件不存在则自动创建。 * @param fname 指定文件名 * @param flags 指定文件打开方式,缺省为 "r",只读方式 * @param mode 当创建文件的时候,指定文件的模式,默认 0666 * @return 返回打开的文件描述符 * * * @async */ export function open(fname: string, flags?: string/** = "r"*/, mode?: number/** = 0666*/): number; /** * * @brief 关闭文件描述符 * @param fd 文件描述符 * * * @async */ export function close(fd: number): void; /** * * @brief 打开文本文件,用于读取,写入,或者同时读写 * * 参数 flags 支持的方式如下: * - 'r' 只读方式,文件不存在则抛出错误。 * - 'r+' 读写方式,文件不存在则抛出错误。 * - 'w' 只写方式,文件不存在则自动创建,存在则将被清空。 * - 'w+' 读写方式,文件不存在则自动创建。 * - 'a' 只写添加方式,文件不存在则自动创建。 * - 'a+' 读写添加方式,文件不存在则自动创建。 * @param fname 指定文件名 * @param flags 指定文件打开方式,缺省为 "r",只读方式 * @return 返回打开的文件对象 * * * @async */ export function openTextStream(fname: string, flags?: string/** = "r"*/): Class_BufferedStream; /** * * @brief 打开文本文件,并读取内容 * @param fname 指定文件名 * @return 返回文件文本内容 * * * @async */ export function readTextFile(fname: string): string; /** * * @brief 打开二进制文件,并读取内容 * @param fname 指定文件名 * @param encoding 指定解码方式,缺省不解码 * @return 返回文件文本内容 * * * @async */ export function readFile(fname: string, encoding?: string/** = ""*/): any; /** * * @brief 打开文件,以数组方式读取一组文本行,行结尾标识基于 EOL 属性的设置,缺省时,posix:"\n";windows:"\r\n" * @param fname 指定文件名 * @param maxlines 指定此次读取的最大行数,缺省读取全部文本行 * @return 返回读取的文本行数组,若无数据可读,或者连接中断,空数组 * * * */ export function readLines(fname: string, maxlines?: number/** = -1*/): any[]; /** * * @brief 创建文本文件,并写入内容 * @param fname 指定文件名 * @param txt 指定要写入的字符串 * * * @async */ export function writeTextFile(fname: string, txt: string): void; /** * * @brief 创建二进制文件,并写入内容 * @param fname 指定文件名 * @param data 指定要写入的二进制数据 * * * @async */ export function writeFile(fname: string, data: Class_Buffer): void; /** * * @brief 创建二进制文件,并写入内容 * @param fname 指定文件名 * @param data 指定要写入的二进制数据 * * * @async */ export function appendFile(fname: string, data: Class_Buffer): void; /** * * @brief 设置 zip 虚拟文件映射 * @param fname 指定映射路径 * @param data 指定映射的 zip 文件数据 * * * */ export function setZipFS(fname: string, data: Class_Buffer): void; /** * * @brief 清除 zip 虚拟文件映射 * @param fname 指定映射路径,缺省清除全部缓存 * * * */ export function clearZipFS(fname?: string/** = ""*/): void; } /** end of `module fs` */ export = fs } /** endof `module Or Internal Object` */
the_stack
import * as browser_utils from './utils/browser'; import * as errors from '../../shared/utils/errors'; import EventEmitter from './utils/eventEmitter'; import logger from '../../shared/utils/logger'; import { ClientStore } from './datastore'; import { SynchronousInMemory } from '../../shared/data_backend'; import * as mutations from './mutations'; import Cursor from './cursor'; import Register from './register'; import Path from './path'; import Document, { InMemoryDocument } from './document'; import Mutation from './mutations'; import Menu from './menu'; import * as Modes from './modes'; import { ModeId, CursorOptions, Row, Col, Chars, SerializedBlock } from './types'; type SessionOptions = { initialMode?: ModeId, viewRoot?: Path, cursorPath?: Path, showMessage?: (message: string, options?: any) => void, toggleBindingsDiv?: () => void, getLinesPerPage?: () => number, }; type ViewState = { cursor: Cursor, viewRoot: Path, }; type HistoryLogEntry = { index: number, after?: ViewState, before?: ViewState, }; type JumpLogEntry = { viewRoot: Path, cursor_before: Cursor, cursor_after?: Cursor, }; type DelCharsOptions = { yank?: boolean, }; type DelBlockOptions = { noSave?: boolean, addNew?: boolean, noNew?: boolean, }; /* a Session represents a session with a vimflowy document It holds a Cursor, a Document object It exposes methods for manipulation of the document, and movement of the cursor Currently, the separation between the Session and Document classes is not very good. (see document.ts) Ideally, session shouldn't do much more than handle cursors and history */ export default class Session extends EventEmitter { public mode: ModeId; public clientStore: ClientStore; public document: Document; public register: Register; public cursor: Cursor; private _anchor: Cursor | null; public viewRoot: Path; public menu: Menu | null = null; private mutations: Array<Mutation> = []; private history: Array<HistoryLogEntry> = []; private historyIndex: number = 0; public jumpHistory: Array<JumpLogEntry> = []; public jumpIndex: number = 0; private getLinesPerPage: () => number; public showMessage: (message: string, options?: any) => void; public toggleBindingsDiv: () => void; private static swapCase(chars: Chars) { return chars.map(function(chr) { return chr.toLowerCase() === chr ? chr.toUpperCase() : chr.toLowerCase(); }); } constructor(clientStore: ClientStore, doc: Document, options: SessionOptions = {}) { super(); this.clientStore = clientStore; this.document = doc; this.showMessage = options.showMessage || ((message) => { logger.info(`Showing message: ${message}`); }); this.toggleBindingsDiv = options.toggleBindingsDiv || (() => null); this.getLinesPerPage = options.getLinesPerPage || (() => 10); this.register = new Register(this); this.menu = null; this.viewRoot = options.viewRoot || Path.root(); this.cursor = new Cursor(this, options.cursorPath || this.viewRoot, 0); this._anchor = null; this.reset_history(); this.reset_jump_history(); const mode = options.initialMode || 'NORMAL'; // NOTE: this is fire and forget // this.setMode(mode); this.mode = mode; return this; } public async exit() { await this.emitAsync('exit'); } public async setMode(newmode: ModeId) { if (newmode === this.mode) { return; } const oldmode = this.mode; if (oldmode) { await Modes.getMode(oldmode).exit(this, newmode); } this.mode = newmode; await Modes.getMode(this.mode).enter(this, oldmode); this.emit('modeChange', oldmode, newmode); } //////////////////////////////// // import/export //////////////////////////////// private parseJson(content: string) { let root; try { root = JSON.parse(content); } catch (error) { this.showMessage('The uploaded file is not valid JSON', {text_class: 'error'}); return false; } const verify = function(node: any) { if (node.clone) { return true; } if (!node.text && node.text !== '') { return false; } if (node.children) { for (let i = 0; i < node.children.length; i++) { const child = node.children[i]; if (!verify(child)) { return false; } } } return true; }; if (!verify(root)) { this.showMessage('The uploaded file is not in a valid vimflowy format', {text_class: 'error'}); return false; } return root; } private parsePlaintext(content: string) { // Step 1: parse into (int, string) pairs of indentation amounts. let lines: Array<{ indent: number, line: string, annotation?: boolean, }> = []; const whitespace = /^\s*/; const content_lines = content.split('\n'); content_lines.forEach((line) => { const matches = line.match(whitespace); const indent = matches ? matches[0].length : 0; if (line.match(/^\s*".*"$/)) { // Flag workflowy annotations as special cases lines.push({ indent, line: line.replace(/^\s*"(.*)"$/, '$1'), annotation: true, }); } else { // TODO: record whether COMPLETE and strikethrough line if so? lines.push({ indent, line: line.replace(whitespace, '').replace(/^(?:-\s*)?(?:\[COMPLETE\] )?/, ''), }); } }); while (lines[lines.length - 1].line === '') { // Strip trailing blank line(s) lines = lines.splice(0, lines.length - 1); } // Step 2: convert a list of (int, string, annotation?) into a forest format const parseAllChildren = function(parentIndentation: number, lineNumber: number) { const children: Array<any> = []; if (lineNumber < lines.length && lines[lineNumber].annotation) { // Each node can have an annotation immediately follow it children.push({ text: lines[lineNumber].line, }); lineNumber = lineNumber + 1; } while (lineNumber < lines.length && lines[lineNumber].indent > parentIndentation) { // For [the first line of] each child const child: any = { text: lines[lineNumber].line }; const result = parseAllChildren(lines[lineNumber].indent, lineNumber + 1); ({ lineNumber } = result); if (result.children !== null) { child.children = result.children; child.collapsed = result.children.length > 0; } children.push(child); } return { children, lineNumber }; }; const forest = (parseAllChildren(-1, 0)).children; const root = { text: '', children: forest, collapsed: forest.length > 0, }; return root; } private parseContent(content: string, mimetype: string) { if (mimetype === 'application/json') { return this.parseJson(content); } else if (mimetype === 'text/plain' || mimetype === 'Text') { return this.parsePlaintext(content); } else { return null; } } // TODO: make this use replace_empty = true? public async importContent(content: string, mimetype: string) { content = content.replace(/(?:\r)/g, ''); // Remove \r (Carriage Return) from each line const root = this.parseContent(content, mimetype); if (!root) { return false; } const { path } = this.cursor; if (root.text === '' && root.children) { // Complete export, not one node await this.addBlocks(path, 0, root.children); } else { await this.addBlocks(path, 0, [root]); } this.save(); this.emit('importFinished'); return true; } public async exportContent(mimetype: string) { const jsonContent = await this.document.serialize(); if (mimetype === 'application/json') { return JSON.stringify(jsonContent, undefined, 2); } else if (mimetype === 'text/plain') { // Workflowy compatible plaintext export // Ignores 'collapsed' and viewRoot const indent = ' '; const exportLines = function(node: any) { if (typeof(node) === 'string') { return [`- ${node}`]; } const lines: Array<string> = []; lines.push(`- ${node.text}`); const children = node.children || []; children.forEach((child: any) => { if (child.clone) { return; } exportLines(child).forEach((line) => { lines.push(`${indent}${line}`); }); }); return lines; }; return (exportLines(jsonContent)).join('\n'); } else { throw new errors.UnexpectedValue('mimetype', mimetype); } } public async exportFile(type = 'json') { this.showMessage('Exporting...', { time: 0 }); const filename = this.document.name === '' ? `vimflowy.${type}` : `${this.document.name}.${type}` ; // Infer mimetype from file extension const mimetype = browser_utils.mimetypeLookup(filename); if (!mimetype) { throw new Error('Invalid export type'); } const content = await this.exportContent(mimetype); browser_utils.downloadFile(filename, content, mimetype); this.showMessage(`Exported to ${filename}!`, {text_class: 'success'}); } //////////////////////////////// // MUTATIONS //////////////////////////////// public reset_history() { this.mutations = []; // full mutation history this.history = [{ index: 0, }]; this.historyIndex = 0; // index into indices } public save() { if (this.historyIndex !== this.history.length - 1) { // haven't acted, otherwise would've sliced return; } if (this.history[this.historyIndex].index === this.mutations.length) { // haven't acted, otherwise there would be more mutations return; } const state = this.history[this.historyIndex]; state.after = { cursor: this.cursor.clone(), viewRoot: this.viewRoot, }; this.historyIndex += 1; this.history.push({ index: this.mutations.length, }); } private async _restoreViewState(state: ViewState) { await this.cursor.from(state.cursor); await this.fixCursorForMode(); await this.changeView(state.viewRoot); } public async undo() { if (this.historyIndex > 0) { const oldState = this.history[this.historyIndex]; this.historyIndex -= 1; const newState = this.history[this.historyIndex]; logger.debug('UNDOING <'); for (let j = oldState.index - 1; j > newState.index - 1; j--) { const mutation = this.mutations[j]; logger.debug(` Undoing mutation ${mutation.constructor.name}(${mutation.str()})`); const undo_mutations = await mutation.rewind(this); for (let k = 0; k < undo_mutations.length; k++) { const undo_mutation = undo_mutations[k]; logger.debug(` Undo mutation ${undo_mutation.constructor.name}(${undo_mutation.str()})`); await undo_mutation.mutate(this); await undo_mutation.moveCursor(this.cursor); } } logger.debug('> END UNDO'); if (!newState.before) { throw new Error('No previous cursor state found while undoing'); } await this._restoreViewState(newState.before); } } public async redo() { if (this.historyIndex < this.history.length - 1) { const oldState = this.history[this.historyIndex]; this.historyIndex += 1; const newState = this.history[this.historyIndex]; logger.debug('REDOING <'); for (let j = oldState.index; j < newState.index; j++) { const mutation = this.mutations[j]; if (!await mutation.validate(this)) { // this should not happen, since the state should be the same as before throw new errors.GenericError(`Failed to redo mutation: ${mutation.str()}`); } logger.debug(` Redoing mutation ${mutation.constructor.name}(${mutation.str()})`); await mutation.remutate(this); await mutation.moveCursor(this.cursor); } logger.debug('> END REDO'); if (!oldState.after) { throw new Error('No after cursor state found while redoing'); } await this._restoreViewState(oldState.after); } } public async do(mutation: Mutation) { if (!this.history) { // NOTE: we let mutations through since some plugins may apply mutations on load // these mutations won't be undoable, which is desired logger.warn(`Tried mutation ${mutation} before init!`); await mutation.mutate(this); return true; } if (!await mutation.validate(this)) { return false; } if (this.historyIndex !== this.history.length - 1) { this.history = this.history.slice(0, this.historyIndex + 1); this.mutations = this.mutations.slice(0, this.history[this.historyIndex].index); } const state = this.history[this.historyIndex]; if (this.mutations.length === state.index) { state.before = { cursor: this.cursor.clone(), viewRoot: this.viewRoot, }; } logger.debug(`Applying mutation ${mutation.constructor.name}(${mutation.str()})`); await mutation.mutate(this); await mutation.moveCursor(this.cursor); await this.fixCursorForMode(); this.mutations.push(mutation); return true; } // TODO: do this in the mode private async fixCursorForMode() { if (!Modes.getMode(this.mode).metadata.cursorBetween) { await this.cursor.backIfNeeded(); } } //////////////////////////////// // viewability //////////////////////////////// // whether contents are currently viewable (i.e. subtree is visible) public async viewable(path: Path) { return path.is(this.viewRoot) || ( path.isDescendant(this.viewRoot) && (!await this.document.collapsed(path.row)) ); } // whether a given path is visible public async isVisible(path: Path) { const visibleAncestor = await this.youngestVisibleAncestor(path); return (visibleAncestor !== null) && path.is(visibleAncestor); } public async nextVisible(path: Path) { if (await this.viewable(path)) { const children = await this.document.getChildren(path); if (children.length > 0) { return children[0]; } } if (path.is(this.viewRoot)) { return null; } while (true) { const nextsib = await this.document.getSiblingAfter(path); if (nextsib !== null) { return nextsib; } if (path.parent == null) { throw new Error('Did not encounter view root on way to root'); } path = path.parent; if (path.is(this.viewRoot)) { return null; } } } // last thing visible nested within id public async lastVisible(path: Path = this.viewRoot): Promise<Path> { if (!(await this.viewable(path))) { return path; } const children = await this.document.getChildren(path); if (children.length > 0) { return await this.lastVisible(children[children.length - 1]); } return path; } public async prevVisible(path: Path) { if (path.parent == null) { return null; } if (path.is(this.viewRoot)) { return null; } const prevsib = await this.document.getSiblingBefore(path); if (prevsib !== null) { return await this.lastVisible(prevsib); } if (path.parent.is(this.viewRoot)) { if (path.parent.is(this.document.root)) { return null; } else { return this.viewRoot; } } return path.parent; } // finds oldest ancestor that is visible *besides viewRoot* // returns null if there is no visible ancestor (i.e. path is not under viewroot) public async oldestVisibleAncestor(path: Path) { let last = path; while (true) { if (last.parent == null) { return null; } const cur = last.parent; if (cur.is(this.viewRoot)) { return last; } last = cur; } } // finds closest ancestor that is visible // returns null if there is no visible ancestor (i.e. path is not under viewroot) public async youngestVisibleAncestor(path: Path) { let answer = path; let cur = path; while (true) { if (cur.is(this.viewRoot)) { return answer; } if (cur.parent == null) { return null; } if (await this.document.collapsed(cur.row)) { answer = cur; } cur = cur.parent; } } //////////////////////////////// // View root //////////////////////////////// public async changeViewRoot(path: Path) { this.viewRoot = path; this.emit('changeViewRoot', path); } public reset_jump_history() { this.jumpHistory = [{ viewRoot: this.viewRoot, cursor_before: this.cursor.clone(), }]; this.jumpIndex = 0; // index into jump history } // jump_fn is just some function that changes // viewRoot and cursor private async _addToJumpHistory(jump_fn: () => Promise<void>) { const jump = this.jumpHistory[this.jumpIndex]; jump.cursor_after = this.cursor.clone(); this.jumpHistory = this.jumpHistory.slice(0, this.jumpIndex + 1); await jump_fn(); this.jumpHistory.push({ viewRoot: this.viewRoot, cursor_before: this.cursor.clone(), }); this.jumpIndex += 1; } // try going to jump, return true if succeeds private async tryJump(jump: JumpLogEntry) { if (jump.viewRoot.row === this.viewRoot.row) { return false; // not moving, don't jump } if (!await this.document.isAttached(jump.viewRoot.row)) { return false; // invalid location } const children = await this.document.getChildren(jump.viewRoot); await this.changeViewRoot(jump.viewRoot); if (children.length) { await this.cursor.setPath(children[0]); } else { await this.cursor.setPath(jump.viewRoot); } if (!jump.cursor_after) { throw new Error('Jump should have had cursor_after'); } if (await this.document.isAttached(jump.cursor_after.row)) { // if the row is attached and under the view root, switch to it const cursor_path = await this.youngestVisibleAncestor(jump.cursor_after.path); if (cursor_path !== null) { await this.cursor.setPath(cursor_path); } } return true; } public async jumpPrevious() { let jumpIndex = this.jumpIndex; const jump = this.jumpHistory[jumpIndex]; jump.cursor_after = this.cursor.clone(); while (true) { if (jumpIndex === 0) { return false; } jumpIndex -= 1; const oldjump = this.jumpHistory[jumpIndex]; if (await this.tryJump(oldjump)) { this.jumpIndex = jumpIndex; return true; } } } public async jumpNext() { let jumpIndex = this.jumpIndex; const jump = this.jumpHistory[jumpIndex]; jump.cursor_after = this.cursor.clone(); while (true) { if (jumpIndex === this.jumpHistory.length - 1) { return false; } jumpIndex += 1; const newjump = this.jumpHistory[jumpIndex]; if (await this.tryJump(newjump)) { this.jumpIndex = jumpIndex; return true; } } } // try to change the view root to row // fails if there is no child // records in jump history private async changeView(path: Path) { if (path.is(this.viewRoot)) { return; // not moving, do nothing } await this._addToJumpHistory(async () => { await this.changeViewRoot(path); }); } // try to zoom into newroot, updating the cursor public async zoomInto(newroot: Path) { await this.changeView(newroot); let newpath = await this.youngestVisibleAncestor(this.cursor.path); if (newpath === null) { // not visible, need to reset cursor newpath = newroot; } await this.cursor.setPath(newpath); } public async zoomOut() { if (this.viewRoot.parent != null) { await this.zoomInto(this.viewRoot.parent); } } public async zoomIn() { if (this.cursor.path.is(this.viewRoot)) { return; } const newroot = await this.oldestVisibleAncestor(this.cursor.path); if (newroot == null) { throw new Error('Got error zooming in to cursor'); } await this.zoomInto(newroot); } public async zoomDown() { const sib = await this.document.getSiblingAfter(this.viewRoot); if (sib === null) { this.showMessage('No next sibling to zoom down to', {text_class: 'error'}); return; } await this.zoomInto(sib); } public async zoomUp() { const sib = await this.document.getSiblingBefore(this.viewRoot); if (sib === null) { this.showMessage('No previous sibling to zoom up to', {text_class: 'error'}); return; } await this.zoomInto(sib); } //////////////////////////////// // Text //////////////////////////////// public async curLine() { return await this.document.getLine(this.cursor.row); } public async curText() { return await this.document.getText(this.cursor.row); } public async curLineLength() { return await this.document.getLength(this.cursor.row); } public async addChars(row: Row, col: Col, chars: Chars) { if (col < 0) { col = (await this.document.getLength(row)) + col + 1; } await this.do(new mutations.AddChars(row, col, chars)); } public async addCharsAtCursor(chars: Chars) { await this.addChars(this.cursor.row, this.cursor.col, chars); } public async addCharsAfterCursor(chars: Chars) { let col = this.cursor.col; if (col < (await this.document.getLength(this.cursor.row))) { col += 1; } await this.addChars(this.cursor.row, col, chars); } public async delChars(row: Row, col: Col, nchars: number, options: DelCharsOptions = {}) { const n = await this.document.getLength(row); let deleted: Chars = []; if (col < 0) { col = n + col; } if ((n > 0) && (nchars > 0) && (col < n)) { const mutation = new mutations.DelChars(row, col, nchars); await this.do(mutation); deleted = mutation.deletedChars; if (options.yank) { this.register.saveChars(deleted); } } return deleted; } public async delCharsBeforeCursor(nchars: number, options: DelCharsOptions = {}) { nchars = Math.min(this.cursor.col, nchars); return await this.delChars(this.cursor.path.row, this.cursor.col - nchars, nchars, options); } public async delCharsAfterCursor(nchars: number, options: DelCharsOptions = {}) { return await this.delChars(this.cursor.path.row, this.cursor.col, nchars, options); } private async changeChars(row: Row, col: Col, nchars: number, change_fn: (chars: Chars) => Chars) { const mutation = new mutations.ChangeChars(row, col, nchars, change_fn); await this.do(mutation); return mutation.ncharsDeleted; } public async swapCaseAtCursor() { await this.changeChars(this.cursor.row, this.cursor.col, 1, Session.swapCase); await this.cursor.right(); } public async swapCaseInVisual(cursor1: Cursor, cursor2: Cursor) { if (!(cursor2.path.is(cursor1.path))) { logger.warn('Not yet implemented'); return; } if (cursor2.col < cursor1.col) { [cursor1, cursor2] = [cursor2, cursor1]; } const nchars = cursor2.col - cursor1.col + 1; await this.changeChars(cursor1.row, cursor1.col, nchars, Session.swapCase); await this.cursor.from(cursor1); } public async swapCaseInVisualLine(rows: Array<Row>) { await Promise.all(rows.map(async row => await this.changeChars( row, 0, await this.document.getLength(row), Session.swapCase ))); } public async replaceCharsAfterCursor(char: string, nchars: number) { const ndeleted = await this.changeChars(this.cursor.row, this.cursor.col, nchars, (chars => chars.map(function(_chr) { return char; }) )); await this.cursor.setCol(this.cursor.col + ndeleted - 1); } public async clearRowAtCursor(options: {yank?: boolean}) { if (options.yank) { // yank as a row, not chars await this.yankRowAtCursor(); } return await this.delChars(this.cursor.path.row, 0, await this.curLineLength()); } public async yankChars(path: Path, col: Col, nchars: number) { const line = await this.document.getLine(path.row); if (line.length > 0) { this.register.saveChars(line.slice(col, col + nchars)); } } // options: // - includeEnd says whether to also delete cursor2 location public async yankBetween(cursor1: Cursor, cursor2: Cursor, options: {includeEnd?: boolean} = {}) { if (!cursor2.path.is(cursor1.path)) { logger.warn('Not yet implemented'); return; } if (cursor2.col < cursor1.col) { [cursor1, cursor2] = [cursor2, cursor1]; } const offset = options.includeEnd ? 1 : 0; await this.yankChars(cursor1.path, cursor1.col, cursor2.col - cursor1.col + offset); } public async yankRowAtCursor() { const serialized_row = await this.document.serializeRow(this.cursor.row); return this.register.saveSerializedRows([serialized_row]); } // options: // - includeEnd says whether to also delete cursor2 location public async deleteBetween(cursor1: Cursor, cursor2: Cursor, options: {includeEnd?: boolean, yank?: boolean} = {}) { if (!cursor2.path.is(cursor1.path)) { logger.warn('Not yet implemented'); return; } if (cursor2.col < cursor1.col) { [cursor1, cursor2] = [cursor2, cursor1]; } const offset = options.includeEnd ? 1 : 0; await this.delChars(cursor1.path.row, cursor1.col, cursor2.col - cursor1.col + offset, options); } public async newLineBelow( options: {setCursor?: string, cursorOptions?: CursorOptions} = {} ) { options.setCursor = 'first'; const [ collapsed, hasChildren ] = await Promise.all([ this.document.collapsed(this.cursor.row), this.document.hasChildren(this.cursor.row), ]); if (this.cursor.path.is(this.viewRoot)) { if (!hasChildren) { if (!collapsed) { await this.toggleBlockCollapsed(this.cursor.row); } } await this.addBlocks(this.cursor.path, 0, [''], options); } else if ((!collapsed) && hasChildren) { await this.addBlocks(this.cursor.path, 0, [''], options); } else { const parent = this.cursor.path.parent; if (parent == null) { throw new Error('Cursor was at viewroot?'); } const index = await this.document.indexInParent(this.cursor.path); await this.addBlocks(parent, index + 1, [''], options); } } public async newLineAbove() { if (this.cursor.path.is(this.viewRoot)) { return; } const parent = this.cursor.path.parent; if (parent == null) { throw new Error('Cursor was at viewroot?'); } const index = await this.document.indexInParent(this.cursor.path); await this.addBlocks(parent, index, [''], {setCursor: 'first'}); } // behavior of "enter", splitting a line // If enter is not at the end: // insert a new node before with the first half of the content // note that this will always preserve child-parent relationships // If enter is at the end: // insert a new node after // if the node has children, this is the new first child public async newLineAtCursor() { if (this.cursor.col === (await this.document.getLength(this.cursor.row))) { await this.newLineBelow({cursorOptions: {}}); } else { const mutation = new mutations.DelChars(this.cursor.row, 0, this.cursor.col); await this.do(mutation); const path = this.cursor.path; await this.newLineAbove(); // cursor now is at inserted path, add the characters await this.addCharsAfterCursor(mutation.deletedChars); // restore cursor await this.cursor.setPosition(path, 0, {}); } } // can only join if either: // - first is previous sibling of second, AND has no children // - second is first child of first, AND has no children // returns whether a join successfully happened private async _joinRows(first: Path, second: Path, options: {delimiter?: string} = {}) { if (first.parent == null) { throw new Error('Tried to join first as root?'); } if (second.parent == null) { throw new Error('Tried to join first as root?'); } let addDelimiter: string | null = null; const firstLine = await this.document.getLine(first.row); const secondLine = await this.document.getLine(second.row); if (options.delimiter) { if (firstLine.length && secondLine.length) { if (firstLine[firstLine.length - 1] !== options.delimiter) { if (secondLine[0] !== options.delimiter) { addDelimiter = options.delimiter; } } } } if (!await this.document.hasChildren(second.row)) { await this.cursor.setPosition(first, -1); await this.delBlock(second, { noNew: true, noSave: true }); if (addDelimiter != null) { await this.do(new mutations.AddChars( first.row, firstLine.length, [addDelimiter])); } await this.do(new mutations.AddChars( first.row, firstLine.length + (addDelimiter == null ? 0 : 1), secondLine)); await this.cursor.setPosition(first, firstLine.length); return true; } if (await this.document.hasChildren(first.row)) { this.showMessage('Cannot join when both rows have children', {text_class: 'error'}); return false; } if (second.parent.row !== first.parent.row) { this.showMessage('Cannot join with non sibling/child', {text_class: 'error'}); return false; } await this.cursor.setPosition(second, 0); await this.delBlock(first, {noNew: true, noSave: true}); if (addDelimiter != null) { await this.do(new mutations.AddChars(second.row, 0, [addDelimiter])); } await this.do(new mutations.AddChars(second.row, 0, firstLine)); if (addDelimiter != null) { await this.cursor.left(); } return true; } public async joinAtCursor() { const path = this.cursor.path; const sib = await this.nextVisible(path); if (sib === null) { return false; } return await this._joinRows(path, sib, {delimiter: ' '}); } // implements proper "backspace" behavior public async deleteAtCursor() { if (this.cursor.col > 0) { await this.delCharsBeforeCursor(1); return true; } const path = this.cursor.path; const sib = await this.prevVisible(path); if (sib === null) { return false; } if (await this._joinRows(sib, path)) { return true; } return false; } private async delBlock(path: Path, options: DelBlockOptions) { if (path.parent == null) { throw new Error('Cannot delete root'); } return await this.delBlocks(path.parent.row, await this.document.indexInParent(path), 1, options); } public async delBlocks( parent: Row, index: number, nrows: number, options: DelBlockOptions = {} ) { const mutation = new mutations.DetachBlocks(parent, index, nrows, options); await this.do(mutation); if (!options.noSave) { this.register.saveClonedRows(mutation.deleted); } if (!(await this.isVisible(this.cursor.path))) { // view root got deleted await this.zoomOut(); } } public async delBlocksAtCursor(nrows: number, options = {}) { const parent = this.cursor.path.parent; if (parent == null) { throw new Error('Cursor was at root?'); } const index = await this.document.indexInParent(this.cursor.path); return await this.delBlocks(parent.row, index, nrows, options); } public async addBlocks( parent: Path, index = -1, serialized_rows: Array<SerializedBlock>, options: {cursorOptions?: CursorOptions, setCursor?: string} = {} ) { const mutation = new mutations.AddBlocks(parent, index, serialized_rows); await this.do(mutation); if (options.setCursor === 'first') { await this.cursor.setPosition(mutation.added_rows[0], 0, options.cursorOptions); } else if (options.setCursor === 'last') { await this.cursor.setPosition(mutation.added_rows[mutation.added_rows.length - 1], 0, options.cursorOptions); } return mutation.added_rows; } public async yankBlocks(path: Path, nrows: number) { const siblings = await this.document.getSiblingRange(path, 0, nrows - 1); const serialized = await Promise.all(siblings.map( async (x) => await this.document.serialize(x.row) )); this.register.saveSerializedRows(serialized); } public async yankBlocksAtCursor(nrows: number) { await this.yankBlocks(this.cursor.path, nrows); } public async yankBlocksClone(path: Path, nrows: number) { const siblings = await this.document.getSiblingRange(path, 0, nrows - 1); this.register.saveClonedRows(siblings.map(sibling => sibling.row)); } public async yankBlocksCloneAtCursor(nrows: number) { await this.yankBlocksClone(this.cursor.path, nrows); } public async attachBlocks( parent: Path, ids: Array<Row>, index = -1, options: {setCursor?: string} = {} ) { const mutation = new mutations.AttachBlocks(parent.row, ids, index); const will_work = await mutation.validate(this); await this.do(mutation); // TODO: do this more elegantly if (will_work) { if (options.setCursor === 'first') { await this.cursor.setPosition(parent.child(ids[0]), 0); } else if (options.setCursor === 'last') { await this.cursor.setPosition(parent.child(ids[ids.length - 1]), 0); } } } private async moveBlock(path: Path, parent_path: Path, index = -1) { return await this.do(new mutations.MoveBlock(path, parent_path, index)); } public async indentBlocks(path: Path, numblocks = 1) { if (path.is(this.viewRoot)) { this.showMessage('Cannot indent view root', {text_class: 'error'}); return; } const newparent = await this.document.getSiblingBefore(path); if (newparent === null) { this.showMessage('Cannot indent without higher sibling', {text_class: 'error'}); return null; } if (await this.document.collapsed(newparent.row)) { await this.toggleBlockCollapsed(newparent.row); } const siblings = await this.document.getSiblingRange(path, 0, numblocks - 1); for (let i = 0; i < siblings.length; i++) { const sib = siblings[i]; await this.moveBlock(sib, newparent, -1); } return newparent; } public async unindentBlocks(path: Path, numblocks = 1) { if (path.row === this.viewRoot.row) { this.showMessage('Cannot unindent view root', {text_class: 'error'}); return null; } if (path.parent == null) { throw new Error('Tried to unindent root?'); } const parent = path.parent; if (parent.parent == null) { this.showMessage('Cannot unindent past root', {text_class: 'error'}); return; } const siblings = await this.document.getSiblingRange(path, 0, numblocks - 1); const newparent = parent.parent; let pp_i = await this.document.indexInParent(parent); for (let i = 0; i < siblings.length; i++) { const sib = siblings[i]; pp_i += 1; await this.moveBlock(sib, newparent, pp_i); } if (parent.is(this.viewRoot)) { await this.zoomInto(newparent); } return newparent; } public async indent(path: Path = this.cursor.path) { if (path.is(this.viewRoot)) { this.showMessage('Cannot indent view root', {text_class: 'error'}); return; } if (await this.document.collapsed(path.row)) { await this.indentBlocks(path); return ; } const sib = await this.document.getSiblingBefore(path); if (sib == null) { this.showMessage('Cannot indent without higher sibling', {text_class: 'error'}); return; } const newparent = await this.indentBlocks(path); if (newparent === null) { return; } const children = await this.document.getChildren(path); for (let i = 0; i < children.length; i++) { const child = children[i]; await this.moveBlock(child, sib, -1); } } public async unindent(path: Path = this.cursor.path) { if (path.is(this.viewRoot)) { this.showMessage('Cannot unindent view root', {text_class: 'error'}); return; } const parent = path.parent; if (parent == null) { throw new Error('Path was at root and yet not viewRoot?'); } if (await this.document.collapsed(path.row)) { await this.unindentBlocks(path); return; } if (await this.document.hasChildren(path.row)) { this.showMessage('Cannot unindent line with children', {text_class: 'error'}); return; } const p_i = await this.document.indexInParent(path); const newparent = await this.unindentBlocks(path); if (newparent === null) { return; } const later_siblings = (await this.document.getChildren(parent)).slice(p_i); for (let i = 0; i < later_siblings.length; i++) { const sib = later_siblings[i]; await this.moveBlock(sib, path, -1); } } public async swapDown(path: Path = this.cursor.path) { const next = await this.nextVisible(await this.lastVisible(path)); if (next === null) { return; } if (next.parent == null) { throw new Error('Next visible should never return root'); } if ((await this.document.hasChildren(next.row)) && (!await this.document.collapsed(next.row))) { // make it the first child return await this.moveBlock(path, next, 0); } else { // make it the next sibling const parent = next.parent; const p_i = await this.document.indexInParent(next); return await this.moveBlock(path, parent, p_i + 1); } } public async swapUp(path = this.cursor.path) { const prev = await this.prevVisible(path); if (prev === null) { return; } if (prev.parent == null) { throw new Error('Prev visible should never return root'); } if (prev.is(this.viewRoot)) { return; } // make it the previous sibling const parent = prev.parent; const p_i = await this.document.indexInParent(prev); await this.moveBlock(path, parent, p_i); } public async toggleCurBlockCollapsed() { await this.toggleBlockCollapsed(this.cursor.row); } public async toggleBlockCollapsed(row: Row) { await this.do(new mutations.ToggleBlock(row)); } public async setCurBlockCollapsed(collapsed: boolean) { await this.setBlockCollapsed(this.cursor.row, collapsed); } public async setBlockCollapsed(row: Row, collapsed: boolean) { if ((await this.document.collapsed(row)) !== collapsed) { await this.do(new mutations.ToggleBlock(row)); } } public async pasteBefore() { return await this.register.paste({before: true}); } public async pasteAfter() { return await this.register.paste({}); } public get anchor(): Cursor { if ((this.mode !== 'VISUAL_LINE') && (this.mode !== 'VISUAL')) { throw new Error('Wanted visual line selections but not in visual or visual line mode'); } if (this._anchor == null) { throw new Error(`No anchor found in ${this.mode} mode!`); } return this._anchor; } public startAnchor() { this._anchor = this.cursor.clone(); } public stopAnchor() { this._anchor = null; } // given an anchor and cursor, figures out the right blocks to be deleting // returns a parent, minindex, and maxindex public async getVisualLineSelections(): Promise<[Path, number, number]> { const anchor = this.anchor; const cursor = this.cursor; const [common, ancestors1, ancestors2] = await this.document.getCommonAncestor(cursor.path, anchor.path); if (ancestors1.length === 0) { if (common.parent == null) { throw new Error('Invalid state: cursor was at root?'); } // anchor is underneath cursor const parent = common.parent; const index = await this.document.indexInParent(cursor.path); return [parent, index, index]; } else if (ancestors2.length === 0) { if (common.parent == null) { throw new Error('Invalid state: anchor was at root?'); } // cursor is underneath anchor const parent = common.parent; const index = await this.document.indexInParent(anchor.path); return [parent, index, index]; } else { let index1 = await this.document.indexInParent(ancestors1[0] || cursor.path); let index2 = await this.document.indexInParent(ancestors2[0] || anchor.path); if (index2 < index1) { [index1, index2] = [index2, index1]; } return [common, index1, index2]; } } public async scroll(npages: number) { let numlines = Math.round(npages * this.getLinesPerPage()); numlines = Math.max(Math.min(numlines, 1000), -1000); // guard against craziness if (numlines > 0) { for (let j = 0; j < numlines; j++) { await this.cursor.down(); } } else { for (let j = 0; j < -numlines; j++) { await this.cursor.up(); } } this.emit('scroll', numlines); } public async getTextRecusive(path: Path): Promise<[null, Array<string>] | [string, null]> { let result: string[] = []; let err: string | null = null; if (await this.document.collapsed(path.row)) { return ['Some blocks are folded!', null]; } const text = await this.document.getText(path.row); result.push(text); if (await this.document.hasChildren(path.row)) { let children = await this.document.getChildren(path); const resultChildren = await Promise.all( children.map(async (childrenPath) => { return await this.getTextRecusive(childrenPath); }) ); for (let [childErr, childResult] of resultChildren) { if (childErr !== null) { err = childErr; } else { result.push(...(childResult as Array<string>)); } } } if (err === null) { return [null, result]; } else { return [err, null]; } } } export class InMemorySession extends Session { constructor(options: SessionOptions = {}) { const doc = new InMemoryDocument(); doc.loadEmpty(); // NOTE: should be async but is okay since in-memory super( new ClientStore(new SynchronousInMemory()), doc, options ); } }
the_stack
import { faFilter } from '@fortawesome/free-solid-svg-icons/faFilter'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { JSONSchema7 as JSONSchema } from 'json-schema'; import castArray from 'lodash/castArray'; import cloneDeep from 'lodash/cloneDeep'; import includes from 'lodash/includes'; import isEmpty from 'lodash/isEmpty'; import isEqual from 'lodash/isEqual'; import reject from 'lodash/reject'; import * as React from 'react'; import styled from 'styled-components'; import { Button, ButtonProps } from '../Button'; import { randomString } from '../../utils'; import { Box } from '../Box'; import { DropDownButtonProps } from '../DropDownButton'; import { Flex } from '../Flex'; import { Search } from '../Search'; import { FilterFieldCompareFn, FilterModal } from './FilterModal'; import * as SchemaSieve from './SchemaSieve'; import Summary from './Summary'; import ViewsMenu from './ViewsMenu'; const SearchWrapper = styled.div` flex-basis: 500px; `; const FilterWrapper = styled(Box)` position: relative; `; class BaseFilters extends React.Component<FiltersProps, FiltersState> { private searchElementRef = React.createRef<HTMLInputElement>(); constructor(props: FiltersProps) { super(props); const { filters = [], schema, views = [] } = this.props; const flatSchema = SchemaSieve.flattenSchema(schema); const flatViews = this.flattenViews(views); const flatFilters = filters.map((filter) => SchemaSieve.flattenSchema(filter), ); this.state = { showModal: false, searchString: '', editingFilter: null, filters: flatFilters, views: flatViews, schema: flatSchema, edit: [], }; this.state.edit.push(this.getCleanEditModel()); } public componentDidUpdate(prevProps: FiltersProps) { const newState: any = {}; // If the schema prop updates, also update the internal 'flat' schema if (!isEqual(prevProps.schema, this.props.schema)) { newState.schema = SchemaSieve.flattenSchema(this.props.schema); } if (!isEqual(prevProps.filters, this.props.filters)) { const filters = this.props.filters || []; newState.filters = filters.map((filter) => SchemaSieve.flattenSchema(filter), ); } if (!isEqual(prevProps.views, this.props.views)) { const views = this.props.views || []; newState.views = this.flattenViews(views); } if (!isEmpty(newState)) { this.setState(newState); } } public flattenViews(views: FiltersView[]) { return views.map(({ filters, ...view }) => ({ ...view, filters: filters.map((filter) => SchemaSieve.flattenSchema(filter)), })); } public emitViewsUpdate() { if (!this.props.onViewsUpdate) { return; } this.props.onViewsUpdate( this.state.views.map(({ filters, ...view }) => ({ ...view, filters: filters.map((filter) => SchemaSieve.unflattenSchema(filter)), })), ); } public getCleanEditModel(field?: string | null) { const schema = this.state.schema; if (!field) { field = Object.keys(schema.properties!).shift()!; } const fieldOperators = this.getOperators(field); if (!fieldOperators.length) { return { field, operator: '', value: '', }; } const operator = fieldOperators.shift()!.slug; let value: any = ''; const subschema = schema.properties![field]; if (typeof subschema !== 'boolean') { if (subschema.enum) { value = subschema.enum[0] || ''; } if (subschema.oneOf) { value = (subschema.oneOf[0] as JSONSchema).const || ''; } if (subschema.type === 'boolean') { value = true; } } return { field, operator, value, }; } public getOperators(field: string) { const schema = this.state.schema; return SchemaSieve.getOperators(schema, field); } public emitFilterUpdate() { if (!this.props.onFiltersUpdate) { return; } this.props.onFiltersUpdate( this.state.filters.map((filter) => SchemaSieve.unflattenSchema(filter)), ); } public addFilter(edit: EditModel[]) { const newFilter = SchemaSieve.createFilter(this.state.schema, edit); const currentFilters: JSONSchema[] = !!this.state.editingFilter ? this.state.filters.map((filter) => filter.$id === this.state.editingFilter ? newFilter : filter, ) : [...this.state.filters, newFilter]; this.setState( { filters: currentFilters, edit: [this.getCleanEditModel()], showModal: false, editingFilter: null, }, () => this.emitFilterUpdate(), ); } public editFilter(filter: JSONSchema) { if (filter.title === SchemaSieve.FULL_TEXT_SLUG) { this.searchElementRef.current?.focus(); return; } const { schema } = this.state; const signatures = SchemaSieve.decodeFilter(schema, filter); this.setState({ edit: signatures as EditModel[], editingFilter: filter.$id!, showModal: true, }); } public removeFilter({ $id, title }: JSONSchema) { this.setState( (prevState) => { const newState = { ...prevState, filters: reject(prevState.filters, { $id }), }; if (title === SchemaSieve.FULL_TEXT_SLUG) { newState.searchString = ''; } return newState; }, () => this.emitFilterUpdate(), ); } public setFilters(filters: JSONSchema[]) { this.setState({ filters }, () => this.emitFilterUpdate()); } public clearAllFilters = () => { this.setFilters([]); this.setState({ searchString: '', }); }; public saveView(name: string, scope: string | null) { const view: FiltersView = { id: randomString(), name, scope, filters: cloneDeep(this.state.filters), }; this.setState( (prevState) => ({ views: prevState.views.concat(view), }), () => this.props.onViewsUpdate && this.props.onViewsUpdate(this.state.views), ); } public deleteView({ id }: FiltersView) { this.setState( (prevState) => ({ views: reject(prevState.views, { id }), }), () => this.props.onViewsUpdate && this.props.onViewsUpdate(this.state.views), ); } public setSimpleSearch(term: string) { this.setState( (prevState) => { const newFilters = term ? SchemaSieve.upsertFullTextSearch( this.state.schema, prevState.filters, term, ) : SchemaSieve.removeFullTextSearch(prevState.filters); return { searchString: term, filters: newFilters, }; }, () => this.emitFilterUpdate(), ); } public shouldRenderComponent(mode: FilterRenderMode): boolean { // If a render mode is not specified, render all components if (!this.props.renderMode) { return true; } const allowedModes = castArray(this.props.renderMode); if (includes(allowedModes, 'all')) { return true; } return includes(allowedModes, mode); } public render() { const { filters } = this.state; return ( <FilterWrapper mb={3}> <Flex justifyContent="space-between"> {this.shouldRenderComponent('add') && ( <Button mr={30} disabled={this.props.disabled} primary icon={<FontAwesomeIcon icon={faFilter} />} onClick={() => this.setState({ showModal: true, editingFilter: null }) } label="Add filter" compact={this.props.compact} {...this.props.addFilterButtonProps} ></Button> )} {this.shouldRenderComponent('search') && ( <SearchWrapper> <Search dark={this.props.dark} disabled={this.props.disabled} value={this.state.searchString} onChange={(e: React.ChangeEvent<HTMLInputElement>) => this.setSimpleSearch(e.target.value) } ref={this.searchElementRef} /> </SearchWrapper> )} {this.shouldRenderComponent('views') && ( <ViewsMenu dark={this.props.dark} buttonProps={this.props.viewsMenuButtonProps} disabled={this.props.disabled} views={this.state.views || []} schema={this.props.schema} hasMultipleScopes={ this.props.viewScopes && this.props.viewScopes.length > 1 } setFilters={(filters) => this.setFilters(filters)} deleteView={(view) => this.deleteView(view)} renderMode={this.props.renderMode} compact={this.props.compact} /> )} {this.state.showModal && ( <FilterModal addFilter={(edit) => this.addFilter(edit)} onClose={() => this.setState({ showModal: false })} schema={this.state.schema} edit={this.state.edit} fieldCompareFn={this.props.filterFieldCompareFn} /> )} </Flex> {this.shouldRenderComponent('summary') && !!filters.length && !this.props.disabled && ( <Summary scopes={this.props.viewScopes} edit={(filter: JSONSchema) => this.editFilter(filter)} delete={(filter: JSONSchema) => this.removeFilter(filter)} saveView={(name, scope) => this.saveView(name, scope)} clearAllFilters={this.clearAllFilters} filters={filters} views={this.state.views || []} schema={this.state.schema} /> )} </FilterWrapper> ); } } export interface EditModel { field: string; operator: string; value: string | number | { [k: string]: string }; } export interface FilterInputProps { schema: JSONSchema; value: any; operator: string; onUpdate: (value: any) => void; } export interface ViewScope { slug: string; name: string; label?: string; } export interface FiltersView { id: string; name: string; scope?: string | null; filters: JSONSchema[]; } export interface FilterSignature { field: string; operator: string; value: string | number | boolean | { [k: string]: string }; } export type FilterRenderMode = 'all' | 'add' | 'search' | 'views' | 'summary'; export interface DataTypeModel { operators: { [key: string]: { getLabel: (schema: JSONSchema) => string; }; }; decodeFilter(filter: JSONSchema): null | FilterSignature; createFilter( field: string, operator: string, value: any, schema: JSONSchema, ): JSONSchema; Edit(props: DataTypeEditProps): JSX.Element; } export interface DataTypeEditProps { schema: JSONSchema; value?: any; onUpdate: (value: string | number | boolean) => void; operator: string; slim?: boolean; } export interface FiltersState { showModal: boolean; edit: EditModel[]; editingFilter: string | null; searchString: string; filters: JSONSchema[]; views: FiltersView[]; schema: JSONSchema; } export interface FiltersProps extends React.HTMLAttributes<HTMLElement> { /** If true, disable the entire `Filters` interface */ disabled?: boolean; /** An array of json schemas to be displayed as the currently selected filters, typically used when loading when loading filters from storage */ filters?: JSONSchema[]; /** An array of views, as described above, typically used when loading when loading views from storage */ views?: FiltersView[]; /** An array of view scopes, as described above */ viewScopes?: ViewScope[]; /** A function that is called when filters are updated */ onFiltersUpdate?: (filters: JSONSchema[]) => void; /** A function that is called when views are updated */ onViewsUpdate?: (views: FiltersView[]) => void; /** A json schema describing the shape of the objects you want to filter */ schema: JSONSchema; /** Properties that are passed to the "Add filter" button, these are the same props used for the [`Button`](#button) component */ addFilterButtonProps?: ButtonProps; /** Properties that are passed to the "Views" button, these are the same props used for the [DropDownButton](#dropdownbutton) component */ viewsMenuButtonProps?: DropDownButtonProps; /** Controls which parts of the Filters interface are displayed. One of `all`, `add`, `search`, `views`, `summary`, or an array containing any of these values */ renderMode?: FilterRenderMode | FilterRenderMode[]; /** If true, Set the `Filters` component against a dark background */ dark?: boolean; /** Accept a boolean for each rendition breakpoint. If true remove `Filters` labels */ compact?: boolean[]; /** An optional callback used to sort filter field options */ filterFieldCompareFn?: FilterFieldCompareFn; } /** * A component that can be used for generating filters in the form of [json schema](http://json-schema.org/) objects and saving sets of filters as "views". * The filters created by this component can be used to filter a collection of * objects using the `SchemaSieve` object. * * [View story source](https://github.com/balena-io-modules/rendition/blob/master/src/components/Filters/story.js) * * ## Schema * * The `Filters` component requires a `schema` property which should be a json * schema that defines the shape of the objects you want to filter. For example if * you want to filter on a collection that looks like this: * * ``` * [ * { * name: 'Bulbasaur', * caught: true, * }, * { * name: 'Pikachu', * caught: true, * }, * { * name: 'Dratini', * caught: false, * } * ] * ``` * * You would define a schema that looks like this: * * ``` * { * type: 'object', * properties: { * name: { * title: 'Name', * type: 'string' * }, * caught: { * title: 'Has been caught', * type: 'boolean' * } * } * } * ``` * * If you provide a `title` property, it will be used to label the field when * filtering, otherwise the field name will be used. * * ### Views * * Views represent a set of filters, along with an id and a name. This is a useful * feature for storing a set filters and loading it again at a later point. * A view can optionally have a `scope` property, which will correspond to the * `slug` of a view scope, if you have provided one in the `Filters` property * `viewScopes` property. Scopes allow you to easily add an extra layer of * granularity/grouping to views that are generated. If you provide view scopes, * the user can select a scope when creating a new view. * * A view scope has the following properties: * * | Name | Type | Description | * | ------------- | --------- | ---------------------------------------------------- | * | slug | `string` | A unique identifier for the scope | * | name | `string` | A descriptive name for the scope | * | label | `string` | An optional label to use for this scope when creating a view | * * A view has the following properties: * * | Name | Type | Description | * | ------------- | --------- | ---------------------------------------------------- | * | id | `string` | A unique identifier for the view | * | name | `string` | A descriptive name for the view | * | filters | `string` | An array of json schemas | * | scope | <code>string &#124; null</code> | The slug of a view scope, or `null` if now scopes are provided | */ export const Filters = BaseFilters;
the_stack
import type { Argument, InputOr, RegisterOr } from "."; import { commands as apiCommands, run as apiRun, command, Context, findMenu, keypress, Menu, prompt, showLockedMenu, showMenu, validateMenu } from "../api"; import type { Extension } from "../state/extension"; import type { Register } from "../state/registers"; import { ArgumentError, CancellationError, InputError } from "../utils/errors"; /** * Miscellaneous commands that don't deserve their own category. * * By default, Dance also exports the following keybindings for existing * commands: * * | Keybinding | Command | * | -------------- | ----------------------------------- | * | `s-;` (normal) | `["workbench.action.showCommands"]` | */ declare module "./misc"; /** * Cancel Dance operation. * * @keys `escape` (normal), `escape` (input) */ export function cancel(extension: Extension) { // Calling a new command resets pending operations, so we don't need to do // anything special here. extension.cancelLastOperation(CancellationError.Reason.PressedEscape); } /** * Ignore key. */ export function ignore() { // Used to intercept and ignore key presses in a given mode. } const runHistory: string[] = []; /** * Run code. * * There are two ways to invoke this command. The first one is to provide an * `input` string argument. This input must be a valid JavaScript string, and * will be executed with full access to the [Dance API](../api/README.md). For * instance, * * ```json * { * "command": "dance.run", * "args": { * "input": "Selections.set(Selections.filter(text => text.includes('foo')))", * }, * }, * ``` * * If no argument is provided, a prompt will be shown asking for an input. * Furthermore, an array of strings can be passed to make longer functions * easier to read: * * ```json * { * "command": "dance.run", * "args": { * "input": [ * "for (const selection of Selections.current) {", * " console.log(text(selection));", * "}", * ], * }, * }, * ``` * * The second way to use this command is with the `commands` argument. This * argument must be an array of "command-like" values. The simplest * "command-like" value is a string corresponding to the command itself: * * ```json * { * "command": "dance.run", * "args": { * "commands": [ * "dance.modes.set.normal", * ], * }, * }, * ``` * * But arguments can also be provided by passing an array: * * ```json * { * "command": "dance.run", * "args": { * "commands": [ * ["dance.modes.set", { "input": "normal" }], * ], * }, * }, * ``` * * Or by passing an object, like regular VS Code key bindings: * * ```json * { * "command": "dance.run", * "args": { * "commands": [ * { * "command": "dance.modes.set", * "args": { "input": "normal" }, * }, * ], * }, * }, * ``` * * These values can be mixed: * * ```json * { * "command": "dance.run", * "args": { * "commands": [ * ["dance.selections.saveText", { "register": "^" }], * { * "command": "dance.modes.set", * "args": { "input": "normal" }, * }, * "hideSuggestWidget", * ], * }, * }, * ``` * * If both `input` and `commands` are given, Dance will use `run` if arbitrary * command execution is enabled, or `commands` otherwise. */ export async function run( _: Context, input: string, inputOr: InputOr<string | readonly string[]>, count: number, repetitions: number, register: RegisterOr<"null">, commands?: Argument<command.Any[]>, ) { if (Array.isArray(commands)) { if (typeof input === "string" && apiRun.isEnabled()) { // Prefer "input" to the "commands" array. } else { return apiCommands(...commands); } } let code = await inputOr(() => prompt({ prompt: "Code to run", validateInput(value) { try { apiRun.compileFunction(value); return; } catch (e) { if (e instanceof SyntaxError) { return `invalid syntax: ${e.message}`; } return e?.message ?? `${e}`; } }, history: runHistory, }, _)); if (Array.isArray(code)) { code = code.join("\n"); } else if (typeof code !== "string") { return new InputError(`expected code to be a string or an array, but it was ${code}`); } return _.run(() => apiRun(code as string, { count, repetitions, register })); } /** * Select register for next command. * * When selecting a register, the next key press is used to determine what * register is selected. If this key is a `space` character, then a new key * press is awaited again and the returned register will be specific to the * current document. * * @keys `"` (normal) * @noreplay */ export async function selectRegister(_: Context, inputOr: InputOr<string | Register>) { const input = await inputOr(() => keypress.forRegister(_)); if (typeof input === "string") { if (input.length === 0) { return; } _.extension.currentRegister = _.extension.registers.getPossiblyScoped(input, _.document); } else { _.extension.currentRegister = input; } } let lastUpdateRegisterText: string | undefined; /** * Update the contents of a register. * * @noreplay */ export async function updateRegister( _: Context, register: RegisterOr<"dquote", Register.Flags.CanWrite>, copyFrom: Argument<Register | string | undefined>, inputOr: InputOr<string>, ) { if (copyFrom !== undefined) { const copyFromRegister: Register = typeof copyFrom === "string" ? _.extension.registers.getPossiblyScoped(copyFrom, _.document) : copyFrom; copyFromRegister.ensureCanRead(); await register.set(await copyFromRegister.get()); return; } const input = await inputOr(() => prompt({ prompt: "New register contents", value: lastUpdateRegisterText, validateInput(value) { lastUpdateRegisterText = value; return undefined; }, })); await register.set([input]); } /** * Update Dance count. * * Update the current counter used to repeat the next command. * * #### Additional keybindings * * | Title | Keybinding | Command | * | ------------------------------ | ------------ | ------------------------------------ | * | Add the digit 0 to the counter | `0` (normal) | `[".updateCount", { addDigits: 0 }]` | * | Add the digit 1 to the counter | `1` (normal) | `[".updateCount", { addDigits: 1 }]` | * | Add the digit 2 to the counter | `2` (normal) | `[".updateCount", { addDigits: 2 }]` | * | Add the digit 3 to the counter | `3` (normal) | `[".updateCount", { addDigits: 3 }]` | * | Add the digit 4 to the counter | `4` (normal) | `[".updateCount", { addDigits: 4 }]` | * | Add the digit 5 to the counter | `5` (normal) | `[".updateCount", { addDigits: 5 }]` | * | Add the digit 6 to the counter | `6` (normal) | `[".updateCount", { addDigits: 6 }]` | * | Add the digit 7 to the counter | `7` (normal) | `[".updateCount", { addDigits: 7 }]` | * | Add the digit 8 to the counter | `8` (normal) | `[".updateCount", { addDigits: 8 }]` | * | Add the digit 9 to the counter | `9` (normal) | `[".updateCount", { addDigits: 9 }]` | * * @noreplay */ export async function updateCount( _: Context, count: number, extension: Extension, inputOr: InputOr<number>, addDigits?: Argument<number>, ) { if (typeof addDigits === "number") { let nextPowerOfTen = 1; if (addDigits <= 0) { addDigits = 0; nextPowerOfTen = 10; } while (nextPowerOfTen <= addDigits) { nextPowerOfTen *= 10; } extension.currentCount = count * nextPowerOfTen + addDigits; return; } const input = +await inputOr(() => prompt.number({ integer: true, range: [0, 1_000_000] }, _)); InputError.validateInput(!isNaN(input), "value is not a number"); InputError.validateInput(input >= 0, "value is negative"); extension.currentCount = input; } const menuHistory: string[] = []; /** * Open menu. * * If no input is specified, a prompt will ask for the name of the menu to open. * * Alternatively, a `menu` can be inlined in the arguments. * * Pass a `prefix` argument to insert the prefix string followed by the typed * key if it does not match any menu entry. This can be used to implement chords * like `jj`. * * @noreplay */ export async function openMenu( _: Context.WithoutActiveEditor, inputOr: InputOr<string>, menu?: Argument<Menu>, prefix?: Argument<string>, pass: Argument<any[]> = [], locked: Argument<boolean> = false, delay: Argument<number> = 0, ) { if (typeof menu !== "object") { const menus = _.extension.menus; const input = await inputOr(() => prompt({ prompt: "Menu name", validateInput(value) { if (menus.has(value)) { return; } return `menu ${JSON.stringify(value)} does not exist`; }, placeHolder: [...menus.keys()].sort().join(", ") || "no menu defined", history: menuHistory, }, _)); menu = findMenu(input, _); } const errors = validateMenu(menu); if (errors.length > 0) { throw new Error(`invalid menu: ${errors.join(", ")}`); } if (locked) { return showLockedMenu(menu, pass); } if (delay > 0) { return showMenu.withDelay(delay, menu, pass, prefix); } return showMenu(menu, pass, prefix); } /** * Change current input. * * When showing some menus, Dance can navigate their history: * * | Keybinding | Command | * | --------------- | ------------------------------------------ | * | `up` (prompt) | `[".changeInput", { action: "previous" }]` | * | `down` (prompt) | `[".changeInput", { action: "next" }]` | * * @noreplay */ export function changeInput( action: Argument<Parameters<typeof prompt.notifyActionRequested>[0]>, ) { ArgumentError.validate( "action", ["clear", "previous", "next"].includes(action), `must be "previous" or "next"`, ); prompt.notifyActionRequested(action); }
the_stack
const Client = require('kubernetes-client').Client const { KubeConfig } = require('kubernetes-client') import * as fs from 'fs' import Request from './monkeypatch/client' import { Models } from './models' import { Readable } from 'stream' import Logger, { ILogger } from 'lib/logger' export enum KubernetesEventType { ALL, ADDED, MODIFIED, DELETED } export enum PatchType { MergePatch, JsonPatch } export interface IKubernetesWatchEvent<T extends Models.IExistingResource> { type: string object: T } interface IExecResult { stdout: string stderr: string error: string code: number } interface IWatchOptions { timeout: number qs: { resourceVersion?: string } } interface IGodaddyPostResult { messages: any[] } export interface IGodaddyClient { loadSpec() addCustomResourceDefinition(spec: Models.IExistingResource) apis: { [apiName: string]: { [version: string]: any } } api: { [version: string]: any } } export interface IGodaddyWatch { getObjectStream(options: { timeout?: number qs: { resourceVersion?: string } }): Promise<Readable> } export interface IGodaddyApi { get(options?: { qs: { labelSelector: string } }) delete() post(body: any) patch(data: any) watch: any namespaces(name: string) exec: { post(options: { qs: { command: any container: string stdout: boolean stderr: boolean } }): Promise<IGodaddyPostResult> } } export enum PodPhase { Pending, Running, Succeeded, Failed, Unknown } declare type ResourceCallback<T extends Models.IBaseResource> = ( resource: T & Models.IExistingResource, eventType: KubernetesEventType ) => void declare type EventCallback<T extends Models.IBaseResource> = ( event: IKubernetesWatchEvent<T & Models.IExistingResource> ) => void export interface IKubernetes { /** * Returns a single kubernetes resource * @param {string} api The Kubernetes API to target * @param {T['apiVersion']} apiVersion The version of that API * @param {T['kind']} kind The Kind of object to select * @param {string} namespace The namespace to go to * @param {string} name The name of the object * @returns {Promise<(T & Models.IExistingResource) | null>} The object, or undefined if not found */ get<T extends Models.IBaseResource>( apiVersion: T['apiVersion'], kind: T['kind'], namespace: string, name: string ): Promise<(T & Models.IExistingResource) | null> /** * Executes a command inside a pod, and returns the result * @param {string} namespace The namespace to go to * @param {string} name The name of the pod * @param {string} container The name of the container * @param {string[]} command The command to execute * @returns {Promise<IExecResult>} An object containing the stdout, stderr and exit codes */ exec( namespace: string, name: string, container: string, command: string[] ): Promise<IExecResult> /** * Returns a collection of kubernetes resources based on the selection criteria * @param {T['apiVersion']} apiVersion The version of that API * @param {T['kind']} kind The Kind of object to select * @param {string?} namespace (optional) The namespace to restrict to * @param {string?} labelSelector (optional) The label to select, eg app=your-app * @returns {Promise<(T & Models.IExistingResource)[]>} An array of Kubernetes resources */ select<T extends Models.IBaseResource>( apiVersion: T['apiVersion'], kind: T['kind'], namespace?: string | null | undefined, labelSelector?: string | null | undefined ): Promise<(T & Models.IExistingResource)[]> /** * Patch a kubernetes resource * @param {T['apiVersion']} apiVersion The version of that API * @param {T['kind']} kind The Kind of object to select * @param {string} namespace The namespace to go to * @param {string} name The name of the object * @param {PatchType} patchType The type of patch operation to run * @param {any} patch The patch to apply * @returns {Promise<void>} A promise to indicate if the request was successful or not */ patch<T extends Models.IBaseResource>( apiVersion: T['apiVersion'], kind: T['kind'], namespace: string, name: string, patchType: PatchType.MergePatch, patch: any ): Promise<void> patch<T extends Models.IBaseResource>( apiVersion: T['apiVersion'], kind: T['kind'], namespace: string, name: string, patchType: PatchType.JsonPatch, patch: jsonpatch.OpPatch[] ): Promise<void> /** * Patch a kubernetes resource * @param {T['apiVersion']} apiVersion The version of that API * @param {T['kind']} kind The Kind of object to select * @param {string} namespace The namespace to go to * @param {string} name The name of the object * @param {string} type The status name * @param {string} status The status value * @returns {Promise<void>} A promise to indicate if the request was successful or not */ addStatusCondition<T extends Models.IBaseResource>( apiVersion: T['apiVersion'], kind: T['kind'], namespace: string, name: string, type: string, status: string ): Promise<void> /** * Create a new kubernetes resource * @param {T & Models.INewResource} manifest The manifest to create * @returns {Promise<void>} A promise to indicate if the request was successful or not */ create<T extends Models.IBaseResource>( manifest: T & Models.INewResource ): Promise<void> /** * Removes a kubernetes resource from the cluster * @param {T['apiVersion']} apiVersion The version of that API * @param {T['kind']} kind The Kind of object to select * @param {string} namespace The namespace to go to * @param {string} name The name of the object * @returns {Promise<void>} A promise to indicate if the request was successful or not */ delete<T extends Models.IBaseResource>( apiVersion: T['apiVersion'], kind: T['kind'], namespace: string, name: string ): Promise<void> /** * Watch the kubernetes API for a given resource type * Will handle auto reconnection * @param {T['apiVersion']} apiVersion The version of that API * @param {T['kind']} kind The Kind of object to select * @param {ResourceCallback} handler The handler that will be invoked with the resource * @param {KubernetesEventType[]} eventType The types to watch for (default: MODIFIED, ADDED, DELETED) * @param {string?} namespace The namespace to restrict the watch to * @returns {Promise<void>} A promise to indicate if the watch was setup successfully or not */ watch<T extends Models.IBaseResource>( apiVersion: T['apiVersion'], kind: T['kind'], handler: ResourceCallback<T & Models.IExistingResource>, eventTypes?: KubernetesEventType[], namespace?: string | null ): Promise<void> /** * Starts all watch streams * @returns {Promise<void>} A promise which returns when all watch operations have started */ start() /** * Stops all watch streams * @returns {Promise<void>} A promise that returns when all watch operations have stopped */ stop() /** * Waits for a pod to enter a particular phase * @param {string} namespace The namespace to go to * @param {string} name The name of the object * @param {PodPhase?} phase The phase to wait for, defaults to Running * @param {number?} maxTime The maximum amount of time in milliseconds to wait * @returns {Promise<void>} A promise that returns when the desired state is met */ waitForPodPhase( namespace: string, name: string, phase?: PodPhase, maxTime?: number ): Promise<void> /** * Waits for something to rollout * @param {T['apiVersion']} apiVersion The version of that API * @param {T['kind']} kind The Kind of object to select * @param {string} namespace The namespace to go to * @param {string} name The name of the object * @param {number?} maxTime The maximum amount of time in milliseconds to wait * @returns {Promise<void>} A promise that returns when all replicas are up to date */ waitForRollout<T extends Models.Core.IDeployment>( apiVersion: T['apiVersion'], kind: T['kind'], namespace: string, name: string, maxTime?: number ): Promise<void> /** * Waits for a load balancer service to be assigned an external ip * * Non-load balancer services return immediately * @param {string} namespace The namespace to go to * @param {string} name The name of the object * @param {number?} maxTime The maximum amount of time in milliseconds to wait * @returns {Promise<void>} A promise that returns once a load balancer ip is assigned */ waitForServiceLoadBalancerIp( namespace: string, name: string, maxTime?: number ): Promise<void> /** * Trigger a rollout of a pod controller * @param {T['apiVersion']} apiVersion The version of that API * @param {T['kind']} kind the Kind of object to rollout * @param {string} namespace The namespace to go to * @param {string} name The name of the object * @returns {Promise<void>} A promise that returns once a rollout has been triggered */ rollout< T extends | Models.Core.IDeployment | Models.Core.IStatefulSet | Models.Core.IDaemonSet >( apiVersion: T['apiVersion'], kind: T['kind'], namespace: string, name: string ): Promise<void> } export default class Kubernetes implements IKubernetes { private client: IGodaddyClient private streamsToStart: (() => Promise<void>)[] = [] private streams: Readable[] = [] private initialised = false private initialising = false private logger: ILogger private loadCustomResources = false // The timeout for GET, POST, PUT, PATCH, DELETE private requestTimeout = 5000 // The timeout for WATCH private watchTimeout = 60000 // How long will we wait for watch reconnections before erroring private watchReconnectTimeout = 300000 constructor( options: { loadCustomResources?: boolean client?: IGodaddyClient } = {} ) { this.logger = new Logger('client') this.loadCustomResources = options.loadCustomResources || false const request = { timeout: this.requestTimeout } if (options.client) { this.client = options.client this.logger.info('using injected client') return } if (fs.existsSync('/var/run/secrets/kubernetes.io/serviceaccount')) { this.logger.info('using service account') const kubeconfig = new KubeConfig() kubeconfig.loadFromCluster() const backend = new Request({ kubeconfig, request }) this.client = new Client({ backend }) } else { this.logger.info('using kube config') const kubeconfig = new KubeConfig() kubeconfig.loadFromDefault() const backend = new Request({ kubeconfig, request }) this.client = new Client({ backend }) } } private async init(): Promise<void> { if (this.initialised) { return } else if (this.initialising) { this.logger.debug( 'another instance of init is running, waiting for it to complete' ) let waitedFor = 0 while (!this.initialised) { await this.sleep(50) waitedFor += 1 if (waitedFor > 100) { throw new Error('waited 5000 ms for init to complete, it didnt') } } return } this.initialising = true this.logger.debug('loading kubernetes spec') await this.client.loadSpec() if (this.loadCustomResources) { this.logger.debug('spec loaded, loading crds') const query = await (this.client.apis['apiextensions.k8s.io'] .v1beta1 as any).customresourcedefinition.get() query.body.items.forEach((crd) => { this.client.addCustomResourceDefinition(crd) }) this.logger.debug(`${query.body.items.length} crds loaded`) } this.logger.debug('loading complete') this.initialised = true } private getApiParameters<T extends Models.IBaseResource>( apiVersion: T['apiVersion'], kind: T['kind'] ): { api: string; version: string; kind: string } { const [api, version] = apiVersion.indexOf('/') > -1 ? apiVersion.split('/') : ['', apiVersion] let kindLower = kind.toLowerCase() if (kindLower === 'networkpolicy') { kindLower = 'networkpolicie' } return { api, version, kind: kindLower } } private async getApi<T extends Models.IBaseResource>( apiVersion: T['apiVersion'], kind: T['kind'], namespace?: string, name?: string ): Promise<IGodaddyApi> { await this.init() const { api, version, kind: kindLower } = this.getApiParameters( apiVersion, kind ) this.logger.debug('api handler:', api, version, kindLower, namespace, name) let query = api === '' ? this.client.api[version] : this.client.apis[api][version] if (namespace) { query = query.namespaces(namespace) } const result = await query[kindLower] if (!name) { if (typeof result === 'undefined') { throw new Error(`No handler found for ${version}/${api}/${kindLower}`) } return result } if (typeof result === 'undefined') { throw new Error( `No handler found for ${version}/${api}/${kindLower}/${namespace}/${name}` ) } return result(name) } private sleep(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)) } private streamFor<T extends Models.IBaseResource>( apiVersion: T['apiVersion'], kind: T['kind'], wrappedHandler: EventCallback<T & Models.IExistingResource>, namespace?: string | null ) { const { api, version, kind: kindLower } = this.getApiParameters( apiVersion, kind ) const key = `${api}:${version}:${kindLower}` const delayBetweenRetries = 1000 let streamStarted = new Date(new Date().toUTCString()) let lastResourceVersion: string | null = null // The longest we ever want to wait really is 5 minutes as that // is the default configuration of etcds cache let reconnectRetriesTimeout: NodeJS.Timeout | null = null const handleEvent = ( event: IKubernetesWatchEvent<T & Models.IExistingResource> ) => { if (!event.object || !event.object.metadata) { this.logger.debug(key, 'invalid resource returned', event) return } if (event.type === 'ERROR' && (event.object as any).code === 410) { // Resource has gone away, we're using a resourceVersion that is too old this.logger.debug( key, `the last seen resourceVersion: ${lastResourceVersion} was not found in etcd cache` ) lastResourceVersion = null return } const resourceCreationTimestamp = new Date( event.object.metadata.creationTimestamp as string ) /* If we are: * - In a replay state * - And the event is of type ADDED * - And the event creation date is < when the stream started * then we should ignore the event */ if ( lastResourceVersion === null && KubernetesEventType[event.type] === KubernetesEventType.ADDED && resourceCreationTimestamp < streamStarted ) { return } this.logger.debug( `saw resource: ${event.type} ${event.object.metadata.selfLink} ${event.object.metadata.resourceVersion}` ) // Increment the stream last seen version lastResourceVersion = event.object.metadata.resourceVersion wrappedHandler(event) } const result = api === '' ? this.client.api[version] : this.client.apis[api][version] const watchObject = namespace ? result.watch.namespaces(namespace) : result.watch if (!watchObject) { throw new Error(`No handler found for ${version}/${api}/${kindLower}`) } const startReconnectTimeout = () => { if (!reconnectRetriesTimeout) { reconnectRetriesTimeout = setTimeout(() => { this.logger.error( key, 'Failed to reconnect within timeout, exiting process' ) throw new Error( `Unable to reconnect ${key} to kubernetes after ${ this.watchReconnectTimeout / 1000 }s` ) }, this.watchReconnectTimeout) } } const endReconnectTimeout = () => { if (reconnectRetriesTimeout) { clearTimeout(reconnectRetriesTimeout) reconnectRetriesTimeout = null } } const watch: IGodaddyWatch = watchObject[kindLower] const reconnect = async ( retryCount: number, streamPromise: (retryCount: number) => Promise<void> ): Promise<void> => { startReconnectTimeout() return streamPromise(retryCount) } /* eslint max-statements: off */ const streamPromise = async (previousRetryCount = 1): Promise<void> => { let retryCount = previousRetryCount streamStarted = new Date(new Date().toUTCString()) const handleError = (stream: Readable) => { return async (err) => { this.destroyStream(stream) if (err.message === 'ESOCKETTIMEDOUT') { /* Represents our client timing out after successful connection, but seeing no data */ this.logger.debug(key, 'stream read timed out! Reconnecting...') endReconnectTimeout() reconnect(1, streamPromise) } else { /* Represents unexpected errors */ this.logger.error( key, 'stream encountered an error! Reconnecting...', { error: { message: err.message, name: err.name } } ) await this.sleep(delayBetweenRetries) reconnect(retryCount + 1, streamPromise) } } } const handleEnd = (stream: Readable) => { /* Represents kubernetes closing the stream */ return () => { this.logger.debug(key, 'stream was closed. Reconnecting...') this.destroyStream(stream) endReconnectTimeout() reconnect(1, streamPromise) } } let stream: Readable | undefined try { const watchOptions: IWatchOptions = { timeout: this.watchTimeout, qs: {} } if (lastResourceVersion) { watchOptions.qs.resourceVersion = lastResourceVersion } this.logger.debug( key, `stream starting (retry ${retryCount}, resourceVersion: ${lastResourceVersion}. Current active streams: ${this.streams.length}` ) stream = (await watch.getObjectStream(watchOptions)) as Readable this.streams.push(stream) stream.on('data', () => { endReconnectTimeout() retryCount = 1 }) stream.on('data', handleEvent) stream.on('error', handleError(stream)) stream.on('end', handleEnd(stream)) } catch (ex) { if (ex) { this.logger.error(key, 'error setting up watch', ex) } await this.sleep(delayBetweenRetries) /* Represents unexpected errors in the stream */ if (stream) { this.destroyStream(stream) } reconnect(retryCount + 1, streamPromise) } } this.streamsToStart.push(streamPromise) } private async waitFor<T extends Models.IBaseResource>( apiVersion: T['apiVersion'], kind: T['kind'], namespace: string, name: string, condition: (resource: T & Models.IExistingResource) => boolean, maxTime = 10000 ): Promise<void> { const start = new Date() const isPresentAndConditionPasses = (resource) => { return resource ? condition(resource) : false } let resource = await this.get<T>(apiVersion, kind, namespace, name) /* eslint no-await-in-loop: off */ while (!isPresentAndConditionPasses(resource)) { if (new Date().valueOf() - start.valueOf() > maxTime) { throw new Error('Timeout exceeded') } if (!resource) { throw new Error( `Failed to find a ${kind} named ${name} in ${namespace}` ) } await this.sleep(1000) resource = await this.get(apiVersion, kind, namespace, name) } } private destroyStream(stream: Readable) { try { stream.removeAllListeners() stream.destroy() } catch (ex) { this.logger.warn('Failed to destroy stream during cleanup', ex.message) } finally { this.streams = this.streams.filter((arrayItem) => arrayItem !== stream) } } public async waitForPodPhase( namespace: string, name: string, phase: PodPhase = PodPhase.Running, maxTime = 10000 ): Promise<void> { const condition = (pod: Models.Core.IPod) => { if (pod?.status?.phase) { return PodPhase[pod.status.phase] === phase } return false } return this.waitFor<Models.Core.IPod>( 'v1', 'Pod', namespace, name, condition, maxTime ) } public async waitForRollout<T extends Models.Core.IDeployment>( apiVersion: T['apiVersion'], kind: T['kind'], namespace: string, name: string, maxTime = 10000 ): Promise<void> { const assertion = (resource: T) => { const progressingStatus = resource.status?.conditions?.find( (condition) => condition.type === 'Progressing' ) const isProgressing = progressingStatus && progressingStatus.status === 'True' && progressingStatus.reason === 'NewReplicaSetAvailable' const isUpdated = resource.status?.updatedReplicas === resource.spec.replicas const hasSameReplicas = resource.status?.replicas === resource.spec.replicas return (isProgressing && isUpdated && hasSameReplicas) || false } return this.waitFor<T>( apiVersion, kind, namespace, name, assertion, maxTime ) } public async waitForServiceLoadBalancerIp( namespace: string, name: string, maxTime = 60000 ): Promise<void> { const condition = (service: Models.Core.IService) => { if (service.spec.type !== 'LoadBalancer') { return true } return (service.status?.loadBalancer?.ingress?.length || 0) > 0 } return this.waitFor<Models.Core.IService>( 'v1', 'Service', namespace, name, condition, maxTime ) } public async exec( namespace: string, name: string, container: string, command: string[] ): Promise<IExecResult> { try { const api = await this.getApi<Models.Core.IPod>( 'v1', 'Pod', namespace, name ) const res = await api.exec.post({ qs: { command, container, stdout: true, stderr: true } }) const isEmpty = (item: any) => { return typeof item === 'undefined' || item === 'null' || item === '' } const filterByType = (type: string) => { return res.messages .filter((item) => item.channel === type) .map((item) => item.message) .filter((item) => !isEmpty(item)) .join('\n') } const stdout = filterByType('stdout') const stderr = filterByType('stderr') const error = filterByType('error') const result = { stdout: stdout.trim(), stderr: stderr.trim(), error, code: 0 } const codeMatch = error.match( /command terminated with non-zero exit code: Error executing in Docker Container: (\d+)/ ) if (codeMatch) { result.code = parseInt(codeMatch[1], 10) } return result } catch (ex) { this.logger.error('Error executing command on kubernetes', ex) throw ex } } public async delete<T extends Models.IBaseResource>( apiVersion: T['apiVersion'], kind: T['kind'], namespace: string, name: string ): Promise<void> { try { const api = await this.getApi<T>(apiVersion, kind, namespace, name) await api.delete() } catch (ex) { if (ex.code !== 200) { this.logger.error('Error deleting item from kubernetes', ex) throw ex } } } public async get<T extends Models.IBaseResource>( apiVersion: T['apiVersion'], kind: T['kind'], namespace: string, name: string ): Promise<(T & Models.IExistingResource) | null> { try { const api = await this.getApi<T>(apiVersion, kind, namespace, name) const result = await api.get() return result.body } catch (ex) { if (ex.code !== 404) { this.logger.error('Error getting item from kubernetes', ex) throw new Error(ex) } return null } } public async select<T extends Models.IBaseResource>( apiVersion: T['apiVersion'], kind: T['kind'], namespace?: string, labelSelector?: string ): Promise<(T & Models.IExistingResource)[]> { const api = await this.getApi<T>(apiVersion, kind, namespace) const result = labelSelector ? await api.get({ qs: { labelSelector } }) : await api.get() if (result.statusCode !== 200) { throw new Error( `Non-200 status code returned from Kubernetes API (${result.statusCode})` ) } return result.body.items } public async create<T extends Models.IBaseResource>( manifest: T & Models.INewResource ): Promise<void> { const kindHandler = await this.getApi<T>( manifest.apiVersion, manifest.kind, manifest.metadata.namespace ) return kindHandler.post({ body: manifest }) } public async addStatusCondition<T extends Models.IBaseResource>( apiVersion: T['apiVersion'], kind: T['kind'], namespace: string, name: string, type: string, status: string ): Promise<void> { const patch = [ { op: 'add', path: '/status/conditions/-', value: { type, status } } ] return this.patch<T>( apiVersion, kind, namespace, name, PatchType.JsonPatch, patch ) } public async patch<T extends Models.IBaseResource>( apiVersion: T['apiVersion'], kind: T['kind'], namespace: string, name: string, patchType: PatchType, patch: any ): Promise<void> { const patchTypeMappings = { 0: 'application/merge-patch+json', 1: 'application/json-patch+json' } const contentType = patchTypeMappings[patchType] if (!contentType) { throw new Error( `Unable to match patch ${PatchType[patchType]} to a content type` ) } const patchMutated: any = { headers: { accept: 'application/json', 'content-type': contentType }, body: patch } // If this is a JSON patch to add a status condition, then mutate the url if ( patchType === PatchType.JsonPatch && patch[0].op === 'add' && patch[0].path === '/status/conditions/-' ) { let plural = kind.toLowerCase() if (plural.slice(-1) !== 's') { plural += 's' } const date = new Date().toISOString().split('.')[0] patch[0].value.lastTransitionTime = `${date}.000000Z` const pathname = `/api/v1/namespaces/${namespace}/${plural}/${name}/status` patchMutated.pathname = pathname } const api = await this.getApi<T>(apiVersion, kind, namespace, name) const result = await api.patch(patchMutated) if (result.statusCode !== 200) { throw new Error( `Non-200 status code returned from Kubernetes API (${result.statusCode})` ) } } public async watch<T extends Models.IBaseResource>( apiVersion: T['apiVersion'], kind: T['kind'], handler: ResourceCallback<T & Models.IExistingResource>, eventTypes: KubernetesEventType[] = [KubernetesEventType.ALL], namespace?: string | null ) { await this.init() const wrappedHandler: EventCallback<T> = ( event: IKubernetesWatchEvent<T & Models.IExistingResource> ) => { const eventType: KubernetesEventType = KubernetesEventType[event.type] if ( eventTypes.indexOf(eventType) > -1 || eventTypes.indexOf(KubernetesEventType.ALL) > -1 ) { handler(event.object, eventType) } } this.streamFor<T>(apiVersion, kind, wrappedHandler, namespace) } public async start(): Promise<void> { await this.init() this.logger.log('starting all streams') for (const stream of this.streamsToStart) { await stream() } } public async stop(): Promise<void> { this.logger.log('stopping all streams') for (const stream of this.streams) { await this.destroyStream(stream) } } public async rollout< T extends | Models.Core.IDeployment | Models.Core.IStatefulSet | Models.Core.IDaemonSet >( apiVersion: T['apiVersion'], kind: T['kind'], namespace: string, name: string ): Promise<void> { const patch = { spec: { template: { metadata: { annotations: { 'node-at-kubernetes/restartedAt': `${new Date().getTime()}` } } } } } return this.patch( apiVersion, kind, namespace, name, PatchType.MergePatch, patch ) } }
the_stack
import * as changeCase from 'change-case'; import * as cliFormat from 'cli-format'; import * as Handlebars from 'handlebars'; import toposort = require('toposort'); import { AbiDefinition, DataItem, MethodAbi } from 'ethereum-types'; import { utils } from './utils'; /** * Register all Python-related Handlebars helpers */ export function registerPythonHelpers(): void { Handlebars.registerHelper('equal', (lhs: any, rhs: any) => { return lhs === rhs; }); Handlebars.registerHelper('safeString', (str: string) => new Handlebars.SafeString(str)); Handlebars.registerHelper('parameterType', utils.solTypeToPyType.bind(utils)); Handlebars.registerHelper('returnType', utils.solTypeToPyType.bind(utils)); Handlebars.registerHelper('toPythonIdentifier', utils.toPythonIdentifier.bind(utils)); Handlebars.registerHelper('sanitizeDevdocDetails', (_methodName: string, devdocDetails: string, indent: number) => { // wrap to 80 columns, assuming given indent, so that generated // docstrings can pass pycodestyle checks. also, replace repeated // spaces, likely caused by leading indents in the Solidity, because // they cause repeated spaces in the output, and in particular they may // cause repeated spaces at the beginning of a line in the docstring, // which leads to "unexpected indent" errors when generating // documentation. if (devdocDetails === undefined || devdocDetails.length === 0) { return ''; } const columnsPerRow = 80; return new Handlebars.SafeString( `\n${cliFormat.wrap(devdocDetails.replace(/ +/g, ' ') || '', { paddingLeft: ' '.repeat(indent), width: columnsPerRow, ansi: false, })}\n`, ); }); Handlebars.registerHelper('makeParameterDocstringRole', (name: string, description: string, indent: number) => { let docstring = `:param ${name}:`; if (description && description.length > 0) { docstring = `${docstring} ${description}`; } return new Handlebars.SafeString(utils.wrapPythonDocstringRole(docstring, indent)); }); Handlebars.registerHelper( 'makeReturnDocstringRole', (description: string, indent: number) => new Handlebars.SafeString( utils.wrapPythonDocstringRole(`:returns: ${description.replace(/ +/g, ' ')}`, indent), ), ); Handlebars.registerHelper( 'makeEventParameterDocstringRole', (eventName: string, indent: number) => new Handlebars.SafeString( utils.wrapPythonDocstringRole( `:param tx_hash: hash of transaction emitting ${eventName} event`, indent, ), ), ); Handlebars.registerHelper('tupleDefinitions', (abisJSON: string) => { const abis: AbiDefinition[] = JSON.parse(abisJSON); // build an array of objects, each of which has one key, the Python // name of a tuple, with a string value holding the body of a Python // class representing that tuple. Using a key-value object conveniently // filters duplicate references to the same tuple. const tupleBodies: { [pythonTupleName: string]: string } = {}; // build an array of tuple dependencies, whose format conforms to the // expected input to toposort, a function to do a topological sort, // which will help us declare tuples in the proper order, avoiding // references to tuples that haven't been declared yet. const tupleDependencies: Array<[string, string]> = []; for (const abi of abis) { let parameters: DataItem[] = []; if (abi.hasOwnProperty('inputs')) { // HACK(feuGeneA): using "as MethodAbi" below, but abi // could just as well be ConstructorAbi, EventAbi, etc. We // just need to tell the TypeScript compiler that it's NOT // FallbackAbi, or else it would complain, "Property // 'inputs' does not exist on type 'AbiDefinition'. // Property 'inputs' does not exist on type // 'FallbackAbi'.", despite the enclosing if statement. // tslint:disable:no-unnecessary-type-assertion parameters = parameters.concat((abi as MethodAbi).inputs); } if (abi.hasOwnProperty('outputs')) { // HACK(feuGeneA): same as described above, except here we // KNOW that it's a MethodAbi, given the enclosing if // statement, because that's the only AbiDefinition subtype // that actually has an outputs field. parameters = parameters.concat((abi as MethodAbi).outputs); } for (const parameter of parameters) { utils.extractTuples(parameter, tupleBodies, tupleDependencies); } } // build up a list of tuples to declare. the order they're pushed into // this array is the order they will be declared. const tuplesToDeclare = []; // first push the ones that have dependencies tuplesToDeclare.push(...toposort(tupleDependencies)); // then push any remaining bodies (the ones that DON'T have // dependencies) for (const pythonTupleName in tupleBodies) { if (!tuplesToDeclare.includes(pythonTupleName)) { tuplesToDeclare.push(pythonTupleName); } } // now iterate over those ordered tuples-to-declare, and prefix the // corresponding class bodies with their class headers, to form full // class declarations. const tupleDeclarations = []; for (const pythonTupleName of tuplesToDeclare) { if (tupleBodies[pythonTupleName]) { tupleDeclarations.push( `class ${pythonTupleName}(TypedDict):\n """Python representation of a tuple or struct.\n\n Solidity compiler output does not include the names of structs that appear\n in method definitions. A tuple found in an ABI may have been written in\n Solidity as a literal, anonymous tuple, or it may have been written as a\n named \`struct\`:code:, but there is no way to tell from the compiler\n output. This class represents a tuple that appeared in a method\n definition. Its name is derived from a hash of that tuple's field names,\n and every method whose ABI refers to a tuple with that same list of field\n names will have a generated wrapper method that refers to this class.\n\n Any members of type \`bytes\`:code: should be encoded as UTF-8, which can be\n accomplished via \`str.encode("utf_8")\`:code:\n """${ tupleBodies[pythonTupleName] }`, ); } } // finally, join the class declarations together for the output file return new Handlebars.SafeString(tupleDeclarations.join('\n\n\n')); }); Handlebars.registerHelper('docBytesIfNecessary', (abisJSON: string) => { const abis: AbiDefinition[] = JSON.parse(abisJSON); // see if any ABIs accept params of type bytes, and if so then emit // explanatory documentation string. for (const abi of abis) { if (abi.hasOwnProperty('inputs')) { // HACK(feuGeneA): using "as MethodAbi" below, but abi // could just as well be ConstructorAbi, EventAbi, etc. We // just need to tell the TypeScript compiler that it's NOT // FallbackAbi, or else it would complain, "Property // 'inputs' does not exist on type 'AbiDefinition'. // Property 'inputs' does not exist on type // 'FallbackAbi'.", despite the enclosing if statement. // tslint:disable:no-unnecessary-type-assertion if ((abi as MethodAbi).inputs) { for (const input of (abi as MethodAbi).inputs) { if (input.type === 'bytes') { return new Handlebars.SafeString( '\n\n All method parameters of type `bytes`:code: should be encoded as UTF-8,\n which can be accomplished via `str.encode("utf_8")`:code:.\n ', ); } } } } } return ''; }); Handlebars.registerHelper('toPythonClassname', (sourceName: string) => { let pascalCased = changeCase.pascal(sourceName); // Retain trailing underscores. const m = /^.+?(_*)$/.exec(sourceName); if (m) { pascalCased = `${pascalCased}${m[1]}`; } return new Handlebars.SafeString(pascalCased); }); Handlebars.registerHelper( 'makeOutputsValue', /** * Produces a Python expression representing the return value from a * Solidity function. * @param pythonVariable the name of the Python variable holding the value * to be used to populate the output expression. * @param abiOutputs the "outputs" object of the function's ABI. */ (pythonVariable: string, abiOutputs: DataItem[]) => { if (abiOutputs.length === 1) { return new Handlebars.SafeString(solValueToPyValue(pythonVariable, abiOutputs[0])); } else { let tupleValue = '('; for (let i = 0; i < abiOutputs.length; i++) { tupleValue += `${pythonVariable}[${i}],`; } tupleValue += ')'; return new Handlebars.SafeString(tupleValue); } }, ); } function solValueToPyValue(pythonVariable: string, abiItem: DataItem): string { const pythonTypeName = utils.solTypeToPyType(abiItem); if (pythonTypeName.match(/List\[.*\]/) !== null) { return `[${solValueToPyValue('element', { ...abiItem, type: abiItem.type.replace('[]', ''), })} for element in ${pythonVariable}]`; } else { let pyValue = `${pythonTypeName}(`; if (abiItem.components) { let i = 0; for (const component of abiItem.components) { pyValue += `${component.name}=${pythonVariable}[${i}],`; i++; } } else { pyValue += pythonVariable; } pyValue += ')'; return pyValue; } }
the_stack
import { apply, chain, Tree, Rule, url, move, template, mergeWith, branchAndMerge, SchematicContext, SchematicsException, externalSchematic, noop, ExecutionOptions, } from '@angular-devkit/schematics'; import { formatFiles, updateWorkspace, getWorkspace } from '@nrwl/workspace'; import { stringUtils, updatePackageScripts, missingArgument, getDefaultTemplateOptions, XplatHelpers, readWorkspaceJson, } from '@nstudio/xplat'; import { prerun, getNpmScope, getPrefix, getJsonFromFile, updateJsonFile, supportedPlatforms, } from '@nstudio/xplat-utils'; import { Schema } from './schema'; export default function (options: Schema) { if (!options.name) { throw new SchematicsException( missingArgument( 'name', 'Provide a name for your app.', 'nx g @nstudio/angular:app my-app' ) ); } if (options.useXplat) { // xplat is configured for sass only (at moment) options.style = 'scss'; } return chain([ prerun(options), // adjust naming convention XplatHelpers.applyAppNamingConvention(options, 'web'), // use xplat or not options.useXplat ? externalSchematic('@nstudio/angular', 'xplat', { platforms: 'web', framework: 'angular', }) : noop(), (tree: Tree, context: SchematicContext) => { const nrwlWebOptions = { ...options, skipInstall: true, }; let executionOptions: Partial<ExecutionOptions>; if (options.useXplat) { // when generating xplat architecture, ensure: // 1. sass is used nrwlWebOptions.style = 'scss'; // executionOptions = { // interactive: false // }; } return externalSchematic( '@nrwl/angular', 'app', nrwlWebOptions, executionOptions )(tree, context); }, (tree: Tree, context: SchematicContext) => addHeadlessE2e(options)(tree, context), options.useXplat ? (tree: Tree, context: SchematicContext) => addAppFiles(options)(tree, context) : noop(), options.useXplat ? (tree: Tree, context: SchematicContext) => addAppFiles(options, 'routing')(tree, context) : noop(), // adjust app files options.useXplat ? (tree: Tree, context: SchematicContext) => adjustAppFiles(options, tree) : noop(), <any>formatFiles({ skipFormat: options.skipFormat }), ]); } /** * Add a Protractor config with headless Chrome and create a * target configuration to use the config created. * * @param options */ function addProtractorCiConfig(options: Schema) { return (tree: Tree, context: SchematicContext) => { const config = ` const defaultConfig = require('./protractor.conf').config; defaultConfig.capabilities.chromeOptions = { args: ['--headless'] }; exports.config = defaultConfig; `; const directory = options.directory ? `${options.directory}/` : ''; const e2eProjectName = `${options.name}-e2e`; const confFile = 'protractor.headless.js'; tree.create(`/apps/${directory}${e2eProjectName}/${confFile}`, config); return updateWorkspace((workspace) => { if (workspace.projects.has(e2eProjectName)) { const projectDef = workspace.projects.get(e2eProjectName); const e2eDef = projectDef.targets.get('e2e'); if (e2eDef) { e2eDef.configurations.ci = { protractorConfig: `apps/${directory}${e2eProjectName}/${confFile}`, }; projectDef.targets.set('e2e', e2eDef); } } }); }; } /** * Add headless options to e2e tests * @param options */ function addHeadlessE2e(options: Schema): Rule { const framework: 'protractor' | 'cypress' | 'none' = options.e2eTestRunner; switch (framework) { case 'protractor': return <any>addProtractorCiConfig(options); default: return noop(); } } function addAppFiles(options: Schema, extra: string = ''): Rule { extra = extra ? `${extra}_` : ''; const directory = options.directory ? `${options.directory}/` : ''; return branchAndMerge( mergeWith( apply(url(`./_${extra}files`), [ template({ ...(options as any), ...getDefaultTemplateOptions(), xplatFolderName: XplatHelpers.getXplatFoldername('web', 'angular'), }), move(`apps/${directory}${options.name}`), ]) ) ); } async function adjustAppFiles(options: Schema, tree: Tree): Promise<Rule> { const directory = options.directory ? `${options.directory}/` : ''; tree.overwrite( `/apps/${directory}${options.name}/src/index.html`, indexContent(options.name) ); tree.overwrite( `/apps/${directory}${options.name}/src/main.ts`, mainContent() ); tree.overwrite( `/apps/${directory}${options.name}/src/styles.scss`, `@import 'scss/index';` ); tree.overwrite( `/apps/${directory}${options.name}/src/app/app.component.html`, options.routing ? `<router-outlet></router-outlet>` : appCmpHtml(options.name) ); if (options.routing) { // update home route to reflect with root cmp would have been tree.overwrite( `/apps/${directory}${options.name}/src/app/features/home/components/home.component.html`, appCmpHtml(options.name) ); } tree.overwrite( `/apps/${directory}${options.name}/src/app/app.component.ts`, appCmpContent() ); tree.overwrite( `/apps/${directory}${options.name}/src/app/app.component.spec.ts`, appCmpSpec() ); tree.overwrite( `/apps/${directory}${options.name}/src/app/app.module.ts`, appModuleContent(options) ); // update cli config for shared web specific scss const workspace = await getWorkspace(tree); const project = workspace.projects.get(options.name); if (project && project.targets) { const buildOptions = project.targets.get('build').options; if (buildOptions) { project.targets.get('build').options.styles = [ `libs/xplat/${XplatHelpers.getXplatFoldername( 'web', 'angular' )}/scss/src/_index.scss`, `apps/${directory}${options.name}/src/styles.scss`, ]; } } return updateWorkspace(workspace); } function indexContent(name: string) { return `<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>${getNpmScope()} ${name}</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> </head> <body> <${getPrefix()}-root></${getPrefix()}-root> </body> </html>`; } function mainContent() { return `import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; // libs import { environment } from '@${getNpmScope()}/xplat/core'; // app import { AppModule } from './app/app.module'; if (environment.production) { enableProdMode(); } platformBrowserDynamic() .bootstrapModule(AppModule) .catch(err => console.log(err)); `; } function appCmpHtml(name: string) { return `<div class="p-x-20"> <${getPrefix()}-header title="${name}"></${getPrefix()}-header> <h2>Nx</h2> Nx is a smart and extensible build framework to help you architect, test, and build at any scale — integrating seamlessly with modern technologies and libraries while providing a robust CLI, caching, dependency management, and more. <a href="https://nx.dev">Learn more about Nx.</a> <h1>{{'welcome' | translate}}!</h1> <h3>Try things out</h3> <a href="https://nstudio.io/xplat">Learn more about xplat.</a> </div>`; } function appCmpContent() { return `import { Component } from '@angular/core'; // xplat import { AppBaseComponent } from '@${getNpmScope()}/xplat/${XplatHelpers.getXplatFoldername( 'web', 'angular' )}/features'; @Component({ selector: '${getPrefix()}-root', templateUrl: './app.component.html' }) export class AppComponent extends AppBaseComponent { constructor() { super(); } } `; } /** * @todo Pass this initial tests */ function appCmpSpec() { return ` describe('Web App component generic test', () => { it('Should be true', () => { expect(true).toBeTruthy(); }); }); /*import { TestBed, async } from '@angular/core/testing'; import { HttpClient } from '@angular/common/http'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TranslateLoader, TranslateModule, TranslateService } from '@ngx-translate/core'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; import { AppComponent } from './app.component'; const translationsEn = require('../assets/i18n/en.json'); export function HttpLoaderFactory(httpClient: HttpClient) { return new TranslateHttpLoader(httpClient); } describe('AppComponent', () => { let translate: TranslateService; let http: HttpTestingController; beforeEach( async(() => { TestBed.configureTestingModule({ imports: [ HttpClientTestingModule, TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient] } }) ], declarations: [AppComponent], providers: [TranslateService] }).compileComponents(); translate = TestBed.get(TranslateService); http = TestBed.get(HttpTestingController); }) ); it( 'should create the app', async(() => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); }) ); it( 'should render xplat hello in a h2 tag', async(() => { spyOn(translate, 'getBrowserLang').and.returnValue('en'); translate.use('en'); const fixture = TestBed.createComponent(AppComponent); const compiled = fixture.debugElement.nativeElement; // the DOM should be empty for now since the translations haven't been rendered yet expect(compiled.querySelector('h1').textContent).toEqual(''); http.expectOne('/assets/i18n/en.json').flush(translationsEn); // Finally, assert that there are no outstanding requests. http.verify(); fixture.detectChanges(); expect(compiled.querySelector('h2').textContent).toContain( 'Hello xplat' ); }) ); }); */ `; } function appModuleContent(options) { return `import { NgModule } from '@angular/core'; // app import { CoreModule } from './core/core.module'; import { SharedModule } from './features/shared/shared.module'; ${options.routing ? `import { AppRoutingModule } from './app.routing';` : ''} import { AppComponent } from './app.component'; @NgModule({ imports: [ CoreModule, SharedModule${ options.routing ? `, AppRoutingModule` : '' } ], declarations: [AppComponent], bootstrap: [AppComponent] }) export class AppModule {} `; }
the_stack
import { VssueAPI } from 'vssue'; import MockAdapter from 'axios-mock-adapter'; import fixtures from './fixtures'; import GitlabV4 from '../src/index'; import { normalizeUser, normalizeIssue, normalizeComment, normalizeReactions, } from '../src/utils'; const baseURL = 'https://gitlab.com'; const APIEndpoint = 'https://gitlab.com/api/v4'; const options = { owner: 'owner', repo: 'repo', clientId: 'clientId', state: 'state', labels: [], }; const encodedRepo = encodeURIComponent(`${options.owner}/${options.repo}`); const API = new GitlabV4(options); const mock = new MockAdapter(API.$http); const mockToken = 'test-token'; describe('properties', () => { test('common properties', () => { expect(API.owner).toBe(options.owner); expect(API.repo).toBe(options.repo); expect(API.clientId).toBe(options.clientId); expect(API.state).toBe(options.state); expect(API.platform.name).toBe('GitLab'); expect(API.platform.version).toBe('v4'); }); test('with default baseURL', () => { expect(API.baseURL).toBe(baseURL); expect(API.platform.link).toBe(baseURL); expect(API.$http.defaults.baseURL).toBe(APIEndpoint); }); }); describe('methods', () => { afterEach(() => { mock.reset(); }); test('redirectAuth', () => { // to make `window.location` writable const location = window.location; delete window.location; const url = 'https://vssue.js.org'; window.location = { href: url } as any; API.redirectAuth(); expect(window.location.href).toBe( `${baseURL}/oauth/authorize?client_id=${ options.clientId }&redirect_uri=${encodeURIComponent(url)}&response_type=token&state=${ options.state }` ); // reset `window.location` window.location = location; }); describe('handleAuth', () => { test('without access_token', async () => { const url = `https://vssue.js.org/`; window.history.replaceState(null, '', url); const token = await API.handleAuth(); expect(window.location.href).toBe(url); expect(token).toBe(null); }); test('with matched state', async () => { const url = `https://vssue.js.org/#access_token=${mockToken}&state=${options.state}`; window.history.replaceState(null, '', url); const token = await API.handleAuth(); expect(window.location.href).toBe('https://vssue.js.org/'); expect(token).toBe(mockToken); }); test('with unmatched state', async () => { const url = `https://vssue.js.org/#access_token=${mockToken}&state=${options.state}-unmatched`; window.history.replaceState(null, '', url); const token = await API.handleAuth(); expect(window.location.href).toBe(url); expect(token).toBe(null); }); test('with extra hash', async () => { const url = `https://vssue.js.org/#access_token=${mockToken}&state=${options.state}&extra=hash`; window.history.replaceState(null, '', url); const token = await API.handleAuth(); expect(window.location.href).toBe('https://vssue.js.org/#extra=hash'); expect(token).toBe(mockToken); }); }); test('getUser', async () => { mock.onGet(new RegExp('/user$')).reply(200, fixtures.user); const user = await API.getUser({ accessToken: mockToken }); expect(mock.history.get.length).toBe(1); const request = mock.history.get[0]; expect(request.method).toBe('get'); expect(request.headers.Authorization).toBe(`Bearer ${mockToken}`); expect(user).toEqual(normalizeUser(fixtures.user)); }); describe('getIssue', () => { describe('with issue id', () => { const issueId = fixtures.issues[0].id; describe('issue exists', () => { beforeEach(() => { mock .onGet(new RegExp(`projects/${encodedRepo}/issues/${issueId}$`)) .reply(200, fixtures.issue); }); test('login', async () => { const issue = (await API.getIssue({ issueId, accessToken: mockToken, })) as VssueAPI.Issue; expect(mock.history.get.length).toBe(1); const request = mock.history.get[0]; expect(request.method).toBe('get'); expect(request.headers.Authorization).toBe(`Bearer ${mockToken}`); expect(issue).toEqual(normalizeIssue(fixtures.issue)); }); test('not login', async () => { const issue = (await API.getIssue({ issueId, accessToken: null, })) as VssueAPI.Issue; expect(mock.history.get.length).toBe(1); const request = mock.history.get[0]; expect(request.method).toBe('get'); expect(request.headers.Authorization).toBeUndefined(); expect(issue).toEqual(normalizeIssue(fixtures.issue)); }); }); test('issue does not exist', async () => { mock .onGet(new RegExp(`projects/${encodedRepo}/issues/${issueId}$`)) .reply(404); const issue = await API.getIssue({ issueId, accessToken: null, }); expect(mock.history.get.length).toBe(1); const request = mock.history.get[0]; expect(request.method).toBe('get'); expect(issue).toBe(null); }); test('error', async () => { mock .onGet(new RegExp(`projects/${encodedRepo}/issues/${issueId}$`)) .reply(500); await expect( API.getIssue({ issueId, accessToken: null, }) ).rejects.toThrow(); expect(mock.history.get.length).toBe(1); const request = mock.history.get[0]; expect(request.method).toBe('get'); }); }); describe('with issue title', () => { const issueTitle = fixtures.issues[0].title; describe('issue exists', () => { beforeEach(() => { mock .onGet(new RegExp(`projects/${encodedRepo}/issues$`)) .reply(200, fixtures.issues); }); test('login', async () => { const issue = (await API.getIssue({ issueTitle, accessToken: mockToken, })) as VssueAPI.Issue; expect(mock.history.get.length).toBe(1); const request = mock.history.get[0]; expect(request.method).toBe('get'); expect(request.headers.Authorization).toBe(`Bearer ${mockToken}`); expect(issue).toEqual(normalizeIssue(fixtures.issues[0])); }); test('not login', async () => { const issue = (await API.getIssue({ issueTitle, accessToken: null, })) as VssueAPI.Issue; expect(mock.history.get.length).toBe(1); const request = mock.history.get[0]; expect(request.method).toBe('get'); expect(request.headers.Authorization).toBeUndefined(); expect(issue).toEqual(normalizeIssue(fixtures.issues[0])); }); }); test('issue does not exist', async () => { mock .onGet(new RegExp(`projects/${encodedRepo}/issues$`)) .reply(200, []); const issue = await API.getIssue({ issueTitle, accessToken: null, }); expect(mock.history.get.length).toBe(1); const request = mock.history.get[0]; expect(request.method).toBe('get'); expect(issue).toBe(null); }); }); }); test('postIssue', async () => { const title = fixtures.issue.title; const content = fixtures.issue.description; mock .onPost(new RegExp(`projects/${encodedRepo}/issues$`)) .reply(201, fixtures.issue); const issue = (await API.postIssue({ title, content, accessToken: mockToken, })) as VssueAPI.Issue; expect(mock.history.post.length).toBe(1); const request = mock.history.post[0]; expect(request.method).toBe('post'); expect(request.headers.Authorization).toBe(`Bearer ${mockToken}`); const data = JSON.parse(request.data); expect(data.title).toBe(title); expect(data.description).toBe(content); expect(data.labels).toBe(options.labels.join(',')); expect(issue).toEqual(normalizeIssue(fixtures.issue)); }); describe('getComments', () => { const issueId = 1; beforeEach(() => { mock .onGet(new RegExp(`projects/${encodedRepo}/issues/${issueId}/notes$`)) .reply(200, fixtures.comments, { 'x-total': fixtures.comments.length, 'x-page': 1, 'x-per-page': 10, }) .onPost(new RegExp(`markdown$`)) .reply(200, { html: '<p>Faked HTML body</p>' }) .onGet( new RegExp( `projects/${encodedRepo}/issues/${issueId}/notes/\\d*/award_emoji$` ) ) .reply(200, fixtures.reactions); }); test('login', async () => { /* eslint-disable-next-line no-unused-expressions */ (await API.getComments({ issueId, accessToken: mockToken, })) as VssueAPI.Comments; expect(mock.history.get.length).toBe(1 + fixtures.comments.length); expect(mock.history.post.length).toBe(fixtures.comments.length); const request = mock.history.get[0]; expect(request.method).toBe('get'); expect(request.headers.Authorization).toBe(`Bearer ${mockToken}`); }); test('not login', async () => { /* eslint-disable-next-line no-unused-expressions */ (await API.getComments({ issueId, accessToken: null, })) as VssueAPI.Comments; expect(mock.history.get.length).toBe(1 + fixtures.comments.length); expect(mock.history.post.length).toBe(fixtures.comments.length); const request = mock.history.get[0]; expect(request.method).toBe('get'); expect(request.headers.Authorization).toBeUndefined(); }); describe('query', () => { const query = { page: 1, perPage: 10, sort: 'desc', }; test('common', async () => { const comments = (await API.getComments({ issueId, accessToken: mockToken, query, })) as VssueAPI.Comments; const request = mock.history.get[0]; expect(request.params.page).toBe(query.page); expect(request.params.per_page).toBe(query.perPage); expect(request.params.order_by).toBe('created_at'); expect(request.params.sort).toBe('desc'); expect(comments.count).toEqual(fixtures.comments.length); expect(comments.page).toEqual(query.page); expect(comments.perPage).toEqual(query.perPage); expect(comments.data).toEqual( fixtures.comments.slice(0, query.perPage).map(normalizeComment) ); }); test('default value', async () => { /* eslint-disable-next-line no-unused-expressions */ (await API.getComments({ issueId, accessToken: mockToken, query: {}, })) as VssueAPI.Comments; const request = mock.history.get[0]; expect(request.params.page).toBe(1); expect(request.params.per_page).toBe(10); expect(request.params.order_by).toBe('created_at'); expect(request.params.sort).toBe('desc'); }); test('sort asc', async () => { /* eslint-disable-next-line no-unused-expressions */ (await API.getComments({ issueId, accessToken: mockToken, query: { sort: 'asc', }, })) as VssueAPI.Comments; const request = mock.history.get[0]; expect(request.params.sort).toBe('asc'); }); }); }); test('postComment', async () => { const issueId = 1; const content = fixtures.comment.body; mock .onPost(new RegExp(`projects/${encodedRepo}/issues/${issueId}/notes$`)) .reply(201, fixtures.comment); const comment = (await API.postComment({ issueId, content, accessToken: mockToken, })) as VssueAPI.Comment; expect(mock.history.post.length).toBe(1); const request = mock.history.post[0]; expect(request.method).toBe('post'); expect(request.headers.Authorization).toBe(`Bearer ${mockToken}`); const data = JSON.parse(request.data); expect(data.body).toBe(content); expect(comment).toEqual(normalizeComment(fixtures.comment)); }); test('putComment', async () => { const issueId = 1; const commentId = fixtures.comment.id; const content = fixtures.comment.body; const contentHTML = '<p>Faked HTML body</p>'; mock .onPut( new RegExp( `projects/${encodedRepo}/issues/${issueId}/notes/${commentId}$` ) ) .reply(200, fixtures.comment) .onPost(new RegExp(`markdown$`)) .reply(200, { html: contentHTML }) .onGet( new RegExp( `projects/${encodedRepo}/issues/${issueId}/notes/\\d*/award_emoji$` ) ) .reply(200, fixtures.reactions); const comment = (await API.putComment({ issueId, commentId, content, accessToken: mockToken, })) as VssueAPI.Comment; expect(mock.history.put.length).toBe(1); expect(mock.history.get.length).toBe(1); expect(mock.history.post.length).toBe(1); const request = mock.history.put[0]; expect(request.method).toBe('put'); expect(request.headers.Authorization).toBe(`Bearer ${mockToken}`); const data = JSON.parse(request.data); expect(data.body).toBe(content); expect(comment).toEqual( normalizeComment({ ...fixtures.comment, body_html: contentHTML, reactions: normalizeReactions(fixtures.reactions), }) ); }); test('deleteComment', async () => { const issueId = 1; const commentId = fixtures.comment.id; mock .onDelete( new RegExp( `projects/${encodedRepo}/issues/${issueId}/notes/${commentId}$` ) ) .reply(204); const success = await API.deleteComment({ issueId, commentId, accessToken: mockToken, }); expect(mock.history.delete.length).toBe(1); const request = mock.history.delete[0]; expect(request.method).toBe('delete'); expect(request.headers.Authorization).toBe(`Bearer ${mockToken}`); expect(success).toBe(true); }); test('getCommentReactions', async () => { const issueId = 1; const commentId = fixtures.comment.id; mock .onGet( new RegExp( `projects/${encodedRepo}/issues/${issueId}/notes/${commentId}/award_emoji$` ) ) .reply(200, fixtures.reactions); const reactions = await API.getCommentReactions({ issueId, commentId, accessToken: mockToken, }); expect(mock.history.get.length).toBe(1); const request = mock.history.get[0]; expect(request.method).toBe('get'); expect(request.headers.Authorization).toBe(`Bearer ${mockToken}`); expect(reactions).toEqual(normalizeReactions(fixtures.reactions)); }); test('postCommentReaction', async () => { const issueId = 1; const commentId = fixtures.comment.id; mock .onPost( new RegExp( `projects/${encodedRepo}/issues/${issueId}/notes/${commentId}/award_emoji$` ) ) .reply(201); const success = await API.postCommentReaction({ issueId, commentId, accessToken: mockToken, reaction: 'like', }); expect(mock.history.post.length).toBe(1); const request = mock.history.post[0]; expect(request.method).toBe('post'); expect(request.headers.Authorization).toBe(`Bearer ${mockToken}`); expect(success).toBe(true); }); });
the_stack
import { MediaBreakpointProps } from "./Media" import { createRuleSet, createClassName } from "./Utils" /** * A union of possible breakpoint props. */ export type BreakpointConstraintKey = keyof MediaBreakpointProps type ValueBreakpointPropsTuple<SizeValue, BreakpointKey> = [ SizeValue, MediaBreakpointProps<BreakpointKey> ] type Tuple = [string, string] function breakpointKey(breakpoint: string | Tuple) { return Array.isArray(breakpoint) ? breakpoint.join("-") : breakpoint } export enum BreakpointConstraint { at = "at", lessThan = "lessThan", greaterThan = "greaterThan", greaterThanOrEqual = "greaterThanOrEqual", between = "between", } /** * Encapsulates all breakpoint data needed by the Media component. The data is * generated on initialization so no further runtime work is necessary. */ export class Breakpoints<BreakpointKey extends string> { static validKeys() { return [ BreakpointConstraint.at, BreakpointConstraint.lessThan, BreakpointConstraint.greaterThan, BreakpointConstraint.greaterThanOrEqual, BreakpointConstraint.between, ] } private _sortedBreakpoints: ReadonlyArray<string> private _breakpoints: Record<string, number> private _mediaQueries: Record<BreakpointConstraint, Map<string, string>> constructor(breakpoints: { [key: string]: number }) { this._breakpoints = breakpoints this._sortedBreakpoints = Object.keys(breakpoints) .map(breakpoint => [breakpoint, breakpoints[breakpoint]]) .sort((a, b) => (a[1] < b[1] ? -1 : 1)) .map(breakpointAndValue => breakpointAndValue[0] as string) // List of all possible and valid `between` combinations const betweenCombinations = this._sortedBreakpoints .slice(0, -1) .reduce( (acc: Tuple[], b1, i) => [ ...acc, ...this._sortedBreakpoints.slice(i + 1).map(b2 => [b1, b2] as Tuple), ], [] ) this._mediaQueries = { [BreakpointConstraint.at]: this._createBreakpointQueries( BreakpointConstraint.at, this._sortedBreakpoints ), [BreakpointConstraint.lessThan]: this._createBreakpointQueries( BreakpointConstraint.lessThan, this._sortedBreakpoints.slice(1) ), [BreakpointConstraint.greaterThan]: this._createBreakpointQueries( BreakpointConstraint.greaterThan, this._sortedBreakpoints.slice(0, -1) ), [BreakpointConstraint.greaterThanOrEqual]: this._createBreakpointQueries( BreakpointConstraint.greaterThanOrEqual, this._sortedBreakpoints ), [BreakpointConstraint.between]: this._createBreakpointQueries( BreakpointConstraint.between, betweenCombinations ), } } public get sortedBreakpoints() { return this._sortedBreakpoints as BreakpointKey[] } public get dynamicResponsiveMediaQueries() { return Array.from( this._mediaQueries[BreakpointConstraint.at].entries() ).reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {}) } public get largestBreakpoint() { return this._sortedBreakpoints[this._sortedBreakpoints.length - 1] } public findBreakpointsForWidths = ( fromWidth: number, throughWidth: number ) => { const fromBreakpoint = this.findBreakpointAtWidth(fromWidth) if (!fromBreakpoint) { return undefined } const throughBreakpoint = this.findBreakpointAtWidth(throughWidth) if (!throughBreakpoint || fromBreakpoint === throughBreakpoint) { return [fromBreakpoint] as BreakpointKey[] } else { return this._sortedBreakpoints.slice( this._sortedBreakpoints.indexOf(fromBreakpoint), this._sortedBreakpoints.indexOf(throughBreakpoint) + 1 ) as BreakpointKey[] } } public findBreakpointAtWidth = (width: number) => { return this._sortedBreakpoints.find((breakpoint, i) => { const nextBreakpoint = this._sortedBreakpoints[i + 1] if (nextBreakpoint) { return ( width >= this._breakpoints[breakpoint] && width < this._breakpoints[nextBreakpoint] ) } else { return width >= this._breakpoints[breakpoint] } }) as BreakpointKey | undefined } public toVisibleAtBreakpointSet(breakpointProps: MediaBreakpointProps) { breakpointProps = this._normalizeProps(breakpointProps) if (breakpointProps.lessThan) { const breakpointIndex = this.sortedBreakpoints.findIndex( bp => bp === breakpointProps.lessThan ) return this.sortedBreakpoints.slice(0, breakpointIndex) } else if (breakpointProps.greaterThan) { const breakpointIndex = this.sortedBreakpoints.findIndex( bp => bp === breakpointProps.greaterThan ) return this.sortedBreakpoints.slice(breakpointIndex + 1) } else if (breakpointProps.greaterThanOrEqual) { const breakpointIndex = this.sortedBreakpoints.findIndex( bp => bp === breakpointProps.greaterThanOrEqual ) return this.sortedBreakpoints.slice(breakpointIndex) } else if (breakpointProps.between) { const between = breakpointProps.between const fromBreakpointIndex = this.sortedBreakpoints.findIndex( bp => bp === between[0] ) const toBreakpointIndex = this.sortedBreakpoints.findIndex( bp => bp === between[1] ) return this.sortedBreakpoints.slice( fromBreakpointIndex, toBreakpointIndex ) } return [] } public toRuleSets(keys = Breakpoints.validKeys()) { const selectedMediaQueries = keys.reduce( (mediaQueries, query) => { mediaQueries[query] = this._mediaQueries[query] return mediaQueries }, {} as Record<BreakpointConstraint, Map<string, string>> ) return Object.entries(selectedMediaQueries).reduce( (acc: string[], [type, queries]) => { queries.forEach((query, breakpoint) => { // We need to invert the query, such that it matches when we want the // element to be hidden. acc.push( createRuleSet( createClassName(type, breakpoint), `not all and ${query}` ) ) }) return acc }, [] ) } public shouldRenderMediaQuery( breakpointProps: MediaBreakpointProps, onlyRenderAt: string[] ): boolean { breakpointProps = this._normalizeProps(breakpointProps) if (breakpointProps.lessThan) { const width = this._breakpoints[breakpointProps.lessThan] const lowestAllowedWidth = Math.min( ...onlyRenderAt.map(breakpoint => this._breakpoints[breakpoint]) ) return lowestAllowedWidth < width } else if (breakpointProps.greaterThan) { const width = this._breakpoints[ this._findNextBreakpoint(breakpointProps.greaterThan) ] const highestAllowedWidth = Math.max( ...onlyRenderAt.map(breakpoint => this._breakpoints[breakpoint]) ) return highestAllowedWidth >= width } else if (breakpointProps.greaterThanOrEqual) { const width = this._breakpoints[breakpointProps.greaterThanOrEqual] const highestAllowedWidth = Math.max( ...onlyRenderAt.map(breakpoint => this._breakpoints[breakpoint]) ) return highestAllowedWidth >= width } else if (breakpointProps.between) { // TODO: This is the only useful breakpoint to negate, but we’ll // we’ll see when/if we need it. We could then also decide // to add `oustide`. const fromWidth = this._breakpoints[breakpointProps.between[0]] const toWidth = this._breakpoints[breakpointProps.between[1]] const allowedWidths = onlyRenderAt.map( breakpoint => this._breakpoints[breakpoint] ) return !( Math.max(...allowedWidths) < fromWidth || Math.min(...allowedWidths) >= toWidth ) } return false } public valuesWithBreakpointProps = <SizeValue>( values: SizeValue[] ): Array<ValueBreakpointPropsTuple<SizeValue, BreakpointKey>> => { type ValueBreakpoints = [SizeValue, string[]] const max = values.length const valueBreakpoints: ValueBreakpoints[] = [] let lastTuple: ValueBreakpoints this._sortedBreakpoints.forEach((breakpoint, i) => { const value = values[i] if (i < max && (!lastTuple || lastTuple[0] !== value)) { lastTuple = [value, [breakpoint]] valueBreakpoints.push(lastTuple) } else { lastTuple[1].push(breakpoint) } }) return valueBreakpoints.map(([value, breakpoints], i) => { const props: MediaBreakpointProps<any> = {} if (i === valueBreakpoints.length - 1) { props.greaterThanOrEqual = breakpoints[0] } else if (breakpoints.length === 1) { props.at = breakpoints[0] } else { // TODO: This is less than ideal, would be good to have a `through` // prop, which unlike `between` is inclusive. props.between = [breakpoints[0], valueBreakpoints[i + 1][1][0]] } return [value, props] as ValueBreakpointPropsTuple< SizeValue, BreakpointKey > }) } private _normalizeProps( breakpointProps: MediaBreakpointProps ): MediaBreakpointProps { if (breakpointProps.at) { const fromIndex = this._sortedBreakpoints.indexOf(breakpointProps.at) const to = this._sortedBreakpoints[fromIndex + 1] return to ? { between: [breakpointProps.at, to] } : { greaterThanOrEqual: breakpointProps.at } } return breakpointProps } private _createBreakpointQuery( breakpointProps: MediaBreakpointProps ): string { breakpointProps = this._normalizeProps(breakpointProps) if (breakpointProps.lessThan) { const width = this._breakpoints[breakpointProps.lessThan] return `(max-width:${width - 1}px)` } else if (breakpointProps.greaterThan) { const width = this._breakpoints[ this._findNextBreakpoint(breakpointProps.greaterThan) ] return `(min-width:${width}px)` } else if (breakpointProps.greaterThanOrEqual) { const width = this._breakpoints[breakpointProps.greaterThanOrEqual] return `(min-width:${width}px)` } else if (breakpointProps.between) { // TODO: This is the only useful breakpoint to negate, but we’ll // we’ll see when/if we need it. We could then also decide // to add `outside`. const fromWidth = this._breakpoints[breakpointProps.between[0]] const toWidth = this._breakpoints[breakpointProps.between[1]] return `(min-width:${fromWidth}px) and (max-width:${toWidth - 1}px)` } throw new Error( `Unexpected breakpoint props: ${JSON.stringify(breakpointProps)}` ) } private _createBreakpointQueries( key: BreakpointConstraintKey, forBreakpoints: ReadonlyArray<string | [string, string]> ) { return forBreakpoints.reduce<Map<string, string>>((map, breakpoint) => { map.set( breakpointKey(breakpoint), this._createBreakpointQuery({ [key]: breakpoint, }) ) return map }, new Map()) } private _findNextBreakpoint(breakpoint: string) { const nextBreakpoint = this._sortedBreakpoints[ this._sortedBreakpoints.indexOf(breakpoint) + 1 ] if (!nextBreakpoint) { throw new Error(`There is no breakpoint larger than ${breakpoint}`) } return nextBreakpoint } }
the_stack
import * as uuid from 'uuid'; import { app, BrowserWindow, Event } from 'electron'; import { Lock } from '../tools/env.lock'; import { inspect } from 'util'; import { Subscription } from '../tools/index'; import { THandler } from '../tools/types.common'; import { IService } from '../interfaces/interface.service'; import { IPCMessages } from '../controllers/electron/controller.electron.ipc'; import { IApplication, EExitCodes } from '../interfaces/interface.app'; import ControllerElectronIpc from '../controllers/electron/controller.electron.ipc'; import ServiceProduction from './service.production'; import ServiceEnv from './service.env'; import ControllerBrowserWindow from '../controllers/electron/controller.browserwindow'; import ControllerDock from '../controllers/electron/controller.dock'; import ControllerElectronMenu from '../controllers/electron/controller.electron.menu'; import Logger from '../tools/env.logger'; export { IPCMessages, Subscription }; /** * @class ServiceElectron * @description Electron instance */ class ServiceElectron implements IService { public IPCMessages = IPCMessages; public IPC: { send: (instance: IPCMessages.TMessage) => Promise<void>, request: (instance: IPCMessages.TMessage, expected?: IPCMessages.TMessage) => Promise<any>, subscribe: (event: Function, handler: (event: IPCMessages.TMessage, response: (instance: IPCMessages.TMessage) => any) => any) => Promise<Subscription>, available: () => boolean, } = { send: this._send.bind(this), request: this._request.bind(this), subscribe: this._subscribe.bind(this), available: this.available.bind(this), }; private _logger: Logger = new Logger('ServiceElectron'); private _controllerBrowserWindow: ControllerBrowserWindow | undefined; private _controllerElectronMenu: ControllerElectronMenu | undefined; private _controllerDock: ControllerDock | undefined; private _onReadyResolve: THandler | null = null; private _ipc: ControllerElectronIpc | undefined; private _ipcLock: Lock = new Lock(false); private _ready: { electron: boolean; service: boolean; } = { electron: false, service: false, }; private _app: IApplication | undefined; constructor() { this._configure(); this._bind(); } /** * Initialization function * @returns Promise<void> */ public init(application: IApplication): Promise<void> { return new Promise((resolve) => { this._app = application; this._onReadyResolve = resolve; this._ready.service = true; this._init(); }); } public destroy(): Promise<void> { return new Promise((resolve) => { if (this._controllerBrowserWindow === undefined) { return resolve(); } this._logger.debug(`Destroing browser window`); this._controllerBrowserWindow.destroy(); this._controllerBrowserWindow = undefined; if (this._ipc !== undefined) { this._ipc.destroy(); this._ipc = undefined; } resolve(); }); } public getName(): string { return 'ServiceElectron'; } public getVersion(): string | Error { if (process.versions === void 0 || process.versions === null) { return new Error(this._logger.error(`Fail to find electron version. Object "versions" isn't valid.`)); } if (typeof process.versions.electron !== 'string' || process.versions.electron.trim() === '') { return new Error(this._logger.error(`Fail to find electron version. Field "electron" has incorrect format: ${typeof process.versions.electron}/"${process.versions.electron}"`)); } return process.versions.electron; } public redirectIPCMessageToPluginRender(message: IPCMessages.PluginInternalMessage | IPCMessages.PluginError, sequence?: string) { if (this._ipc === undefined) { return this._logger.error(`Fail to redirect message of plugin by token: ${message.token}, because IPC is undefined. Income message: ${message.data}`); } this._ipc.send(message, sequence).catch((sendingError: Error) => { this._logger.error(`Fail redirect message by token ${message.token} due error: ${sendingError.message}`); }); } public updateMenu() { if (this._controllerElectronMenu === undefined) { return; } this._controllerElectronMenu.rebuild(); } public getMenu(): ControllerElectronMenu | undefined { return this._controllerElectronMenu; } /* public quit(code: EExitCodes = EExitCodes.normal) { this._logger.debug(`Closing app with code: ${code}`); app.exit(code); process.exit(code); } */ public getBrowserWindow(): BrowserWindow | undefined { if (this._controllerBrowserWindow === undefined) { return undefined; } return this._controllerBrowserWindow.getBrowserWindow(); } public lock(): void { this._ipcLock.lock(); } public available(): boolean { return this._ipc === undefined ? false : !this._ipcLock.isLocked(); } public closeWindow(): Promise<void> { return new Promise((resolve) => { if (this._controllerBrowserWindow === undefined) { return resolve(); } this._controllerBrowserWindow.close().catch((error: Error) => { this._logger.warn(`Fail to destroy ControllerBrowserWindow due error: ${error.message}`); }).finally(() => { resolve(); }); }); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Electron IPC * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ private _subscribe(event: Function, handler: (event: IPCMessages.TMessage, response: (instance: IPCMessages.TMessage) => any) => any): Promise<Subscription> { return new Promise((resolve, reject) => { if (this._ipcLock.isLocked()) { return reject(new Error(`IPC is locked.`)); } if (this._ipc === undefined) { return reject(new Error(`IPC isn't inited yet, cannot delivery IPC controller.`)); } this._ipc.subscribe(event, handler).then((subscription: Subscription) => { resolve(subscription); }).catch((subscribeError: Error) => { this._logger.warn(`Fail to subscribe due error: ${subscribeError.message}`); reject(subscribeError); }); }); } private _send(instance: IPCMessages.TMessage): Promise<void> { return new Promise((resolve, reject) => { if (this._ipcLock.isLocked()) { return reject(new Error(`IPC is locked.`)); } if (this._ipc === undefined) { return reject(new Error(`IPC controller isn't inited yet, cannot delivery IPC controller.`)); } this._ipc.send(instance).then(() => { resolve(); }).catch((sendingError: Error) => { reject(new Error(this._logger.warn(`Fail to send message via IPC due error: ${sendingError.message}. Message: ${inspect(instance)}`))); }); }); } private _request(instance: IPCMessages.TMessage, expected?: IPCMessages.TMessage): Promise<any> { return new Promise((resolve, reject) => { if (this._ipcLock.isLocked()) { return reject(new Error(`IPC is locked.`)); } if (this._ipc === undefined) { return reject(new Error(`IPC controller isn't inited yet, cannot delivery IPC controller.`)); } this._ipc.request(instance, expected).then((response: any) => { resolve(response); }).catch((sendingError: Error) => { reject(new Error(this._logger.warn(`Fail to send message via IPC due error: ${sendingError.message}. Message: ${inspect(instance)}`))); }); }); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Internal * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ private _bind() { app.once('ready', this._onReady.bind(this)); app.once('activate', this._onActivate.bind(this)); } private _configure() { this._logger.debug(`Hardware acceleration is disabled.`); app.disableHardwareAcceleration(); } private _init() { if (!this._ready.electron || !this._ready.service) { return; } // Create client this._createBrowserWindow().then(() => { if (!ServiceProduction.isProduction() && !ServiceEnv.get().CHIPMUNK_NO_WEBDEVTOOLS) { if (this._controllerBrowserWindow !== undefined) { this._controllerBrowserWindow.debug(); } } // Menu this._controllerElectronMenu = new ControllerElectronMenu(); // Files from cmd // cmd // Finish initialization if (this._onReadyResolve !== null) { this._onReadyResolve(); this._onReadyResolve = null; } }).catch((error: Error) => { this._logger.error(`Failed to create browser window due to error: ${error.message}`); }); } private _createBrowserWindow(): Promise<void> { return new Promise((resolve, reject) => { if (this._controllerBrowserWindow !== undefined) { return resolve(); } this._logger.debug(`Creating new browser window`); this._controllerDock = new ControllerDock(); this._controllerBrowserWindow = new ControllerBrowserWindow(uuid.v4()); this._controllerBrowserWindow.getIpc().then((ipc: ControllerElectronIpc | undefined) => { this._ipc = ipc; resolve(); }).catch((error: Error) => { reject(this._logger.error(`Fail to get IPC: ${error.message}`)); }); }); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Electron events * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ private _onReady() { this._ready.electron = true; this._init(); } private _onActivate() { // Create client if it's needed this._createBrowserWindow().catch((error: Error) => { this._logger.error(`Failed to create browser window due to error: ${error.message}`); }); } } export default (new ServiceElectron());
the_stack
import * as admin from 'firebase-admin' import { get, chunk, isObject } from 'lodash' import { batchCopyBetweenFirestoreRefs } from './utils' import { downloadFromStorage, uploadToStorage } from '../utils/cloudStorage' import { to, promiseWaterfall } from '../utils/async' import { isDocPath } from '../utils/firestore' import { shallowRtdbGet } from './utils' import { ActionStep, ActionRunnerEventData } from './types' /** * Create data object with values for each document with keys being doc.id. * @param snap - Data for which to create * an ordered array. * @returns Object documents from snapshot or null */ function dataByIdSnapshot(snap) { const data = {} if (snap.data && snap.exists) { data[snap.id] = snap.data() } else if (snap.forEach) { snap.forEach((doc) => { data[doc.id] = doc.data() || doc }) } return Object.keys(data).length ? data : null } /** * Copy data between Firestore instances from two different Firebase projects * @param app1 - First app for the action * @param app2 - Second app for the action * @param eventData - Data from event (contains settings) * @param inputValues - Values of inputs * @returns Resolves with result of update call */ export async function copyBetweenFirestoreInstances( app1: admin.app.App, app2: admin.app.App, eventData: ActionStep, inputValues: any[] ) { const { merge = true, subcollections } = eventData const srcPath = inputValueOrTemplatePath(eventData, inputValues, 'src') const destPath = inputValueOrTemplatePath(eventData, inputValues, 'dest') const dataPathMethod = isDocPath(srcPath) ? 'doc' : 'collection' // Get Firestore references from slash paths (handling both doc and collection) const srcRef = app1.firestore()[dataPathMethod](srcPath) const destRef = app2.firestore()[dataPathMethod](destPath) // Copy from src ref to dest ref with support for merging and subcollections const [copyErr, writeRes] = await to( batchCopyBetweenFirestoreRefs({ srcRef, destRef, opts: { merge, copySubcollections: subcollections } }) ) // Handle errors copying between Firestore Refs if (copyErr) { console.error('Error copying data between Firestore refs: ', { message: copyErr.message || copyErr, srcPath, destPath }) throw copyErr } console.log('Copy between Firestore instances successful!') return writeRes } /** * Copy data from Cloud Firestore to Firebase Real Time Database * @param app1 - First app for the action * @param app2 - Second app for the action * @param eventData - Data from event (contains settings) * @param inputValues - Values of inputs * @returns Resolves with result of update call */ export async function copyFromFirestoreToRTDB( app1: admin.app.App, app2: admin.app.App, eventData: ActionStep, inputValues: any[] ): Promise<any> { const firestore1 = app1.firestore() const secondRTDB = app2.database() const destPath = inputValueOrTemplatePath(eventData, inputValues, 'dest') const srcPath = inputValueOrTemplatePath(eventData, inputValues, 'src') // Get Firestore instance from slash path (handling both doc and collection) const dataPathMethod = isDocPath(srcPath) ? 'doc' : 'collection' const srcRef = firestore1[dataPathMethod](srcPath) // Get data from first instance const [getErr, firstSnap] = await to(srcRef.get()) // Handle errors getting original data if (getErr) { console.error( `Error getting data from first firestore instance: ${ getErr.message || '' }`, getErr ) throw getErr } // Get data into array (regardless of single doc or collection) const dataFromSrc = dataByIdSnapshot(firstSnap) // Handle no data within provided source path if (!dataFromSrc) { const noDataErr = 'No data exists within source path' console.error(noDataErr) throw new Error(noDataErr) } // Write data to destination RTDB path const [updateErr] = await to(secondRTDB.ref(destPath).update(dataFromSrc)) // Handle errors writing data to destination RTDB if (updateErr) { console.error( 'Error copying from Firestore to RTDB', updateErr.message || updateErr ) throw updateErr } console.log('Copy from Firestore to RTDB successful!') return null } /** * Copy data from Real Time Database to Cloud Firestore * @param app1 - First app for the action * @param app2 - Second app for the action * @param eventData - Data from event (contains settings) * @param inputValues - Values of inputs * @returns Resolves with result of update call */ export async function copyFromRTDBToFirestore( app1: admin.app.App, app2: admin.app.App, eventData: ActionStep, inputValues: any[] ) { const firestore2 = app2.firestore() const firstRTDB = app1.database() const destPath = inputValueOrTemplatePath(eventData, inputValues, 'dest') const srcPath = inputValueOrTemplatePath(eventData, inputValues, 'src') try { const dataSnapFromFirst = await firstRTDB.ref(srcPath).once('value') const dataFromFirst = dataSnapFromFirst.val() const updateRes = await firestore2.doc(destPath).update(dataFromFirst) console.log('Copy from RTDB to Firestore successful') return updateRes } catch (err) { console.error('Error copying from RTDB to Firestore', err.message || err) throw err } } /** * Get input value if pathtype is input otherwise get path value from template * @param templateStep - Step from which to get pathType and fallback paths. * @param inputValues - Converted input values * @param [location='src'] - Path location (i.e. src/dest) * @returns Inputs value or path provided within template's step */ function inputValueOrTemplatePath(templateStep: ActionStep, inputValues: any[], location = 'src'): any { return get(templateStep, `${location}.pathType`) === 'input' ? get(inputValues, get(templateStep, `${location}.path`)) : get(templateStep, `${location}.path`) } /** * Copy data between Firebase Realtime Database Instances * @param app1 - First app for the action * @param app2 - Second app for the action * @param eventData - Data from event (contains settings) * @param inputValues - Converted input values * @returns Resolves with result of update call */ export async function copyBetweenRTDBInstances( app1: admin.app.App, app2: admin.app.App, eventData: ActionStep, inputValues: any[] ): Promise<null> { if (!app1?.database || !app2?.database) { console.error('Database not found on app instance') throw new Error('Invalid service account, does not have access to database') } try { const firstRTDB = app1.database() const secondRTDB = app2.database() const destPath = inputValueOrTemplatePath(eventData, inputValues, 'dest') const srcPath = inputValueOrTemplatePath(eventData, inputValues, 'src') // Handle source path not being provided if (!srcPath) { const noSrcPathErr = 'Copying whole database is not currently supported, please provide a source path.' console.warn('Attempted to copy whole database, throwing an error') throw new Error(noSrcPathErr) } // Load data from first database const dataSnapFromFirst = await firstRTDB.ref(srcPath).once('value') const dataFromFirst = dataSnapFromFirst.val() // Handle data not existing in source database if (!dataFromFirst) { const errorMessage = 'Path does not exist in Source Real Time Database Instance' console.error(errorMessage) throw new Error(errorMessage) } const writeMethod = isObject(dataFromFirst) ? 'update' : 'set' // Update second database with data from first datbase await secondRTDB.ref(destPath)[writeMethod](dataFromFirst) console.log('Copy between RTDB instances successful') return null } catch (err) { console.error('Error copying between RTDB instances', err.message || err) throw err } } /** * Copy data between Firebase Realtime Database Instances * @param app1 - First app for the action * @param app2 - Second app for the action * @param srcPath - Data source path * @param destPath - Data destination path * @returns Resolves with result of update call */ export async function copyPathBetweenRTDBInstances( app1: admin.app.App, app2: admin.app.App, srcPath: string, destPath: string ): Promise<null> { if (!app1?.database || !app2?.database) { console.error('Database not found on app instance') throw new Error('Invalid service account, does not have access to database') } try { const firstRTDB = app1.database() const secondRTDB = app2.database() // Handle source path not being provided if (!srcPath) { const noSrcPathErr = 'Copying whole database is not currently supported, please provide a source path.' console.warn('Attempted to copy whole database, throwing an error') throw new Error(noSrcPathErr) } // Load data from first database const dataSnapFromFirst = await firstRTDB.ref(srcPath).once('value') const dataFromFirst = dataSnapFromFirst.val() // Handle data not existing in source database if (!dataFromFirst) { const errorMessage = `Path does not exist in Source Real Time Database Instance for path ${srcPath}` console.error(errorMessage) throw new Error(errorMessage) } const writeMethod = isObject(dataFromFirst) ? 'update' : 'set' // Update second database with data from first datbase await secondRTDB.ref(destPath || srcPath)[writeMethod](dataFromFirst) return null } catch (err) { console.error('Error copying between RTDB instances', err.message || err) throw err } } const DEFAULT_RTDB_BATCH_SIZE = 50 /** * Copy data between Firebase Realtime Database Instances in batches (suited for large data sets) * @param app1 - First app for the action * @param app2 - Second app for the action * @param step - Current step * @param inputValues - Converted input values * @param eventData - Data from event (contains settings) * @returns Resolves with result of update call */ export async function batchCopyBetweenRTDBInstances( app1: admin.app.App, app2: admin.app.App, step: ActionStep, inputValues: any[], eventData: ActionRunnerEventData ): Promise<void> { // TODO: Support passing in chunk size (it will have to be validated) const chunkSize = DEFAULT_RTDB_BATCH_SIZE const srcPath = inputValueOrTemplatePath(step, inputValues, 'src') const destPath = inputValueOrTemplatePath(step, inputValues, 'dest') const { projectId, environmentValues = [] } = eventData // TODO: Look into a smarter way to get environmentId since first may not always be source const shallowConfig = { projectId, environmentId: environmentValues[0] } // Call Firebase REST API using shallow: true to get a list of keys to chunk into groups const shallowResults = await shallowRtdbGet(shallowConfig, srcPath) // Handle source path not being provided if (!srcPath) { const noSrcPathErr = 'Copying whole database is not currently supported, please provide a source path.' console.warn('Attempted to copy whole database, throwing an error') throw new Error(noSrcPathErr) } const keysChunks = chunk(Object.keys(shallowResults), chunkSize) await promiseWaterfall( keysChunks.map((keyChunk, i) => { return () => { console.log(`Copying key chunk: "${i}" from path: "${srcPath}"`) return Promise.all( keyChunk.map((rtdbKey) => copyPathBetweenRTDBInstances( app1, app2, `${srcPath}/${rtdbKey}`, `${destPath}/${rtdbKey}` ) ) ) } }) ) console.log('Batch copy between RTDB instances successful') } /** * Copy JSON from Firebase Real Time Database to Google Cloud Storage * @param app1 - First app for the action * @param app2 - Second app for the action * @param eventData - Data from event (contains settings) * @returns Resolves with result of update call */ export async function copyFromStorageToRTDB(app1: admin.app.App, app2: admin.app.App, eventData: ActionStep) { if (!app1?.database || !app2?.database) { throw new Error('Invalid service account, database not defined on app') } const secondRTDB = app2.database() const { src, dest } = eventData try { const dataFromFirst = await downloadFromStorage(app1, src.path) const updateRes = await secondRTDB.ref(dest.path).update(dataFromFirst) console.log('Copy from Storage to RTDB was successful') return updateRes } catch (err) { console.error('Error copying from storage instances', err.message || err) throw err } } /** * Copy JSON from Cloud Storage to Firebase Real Time Database * @param app1 - First app for the action * @param app2 - Second app for the action * @param eventData - Data from event (contains settings) * @returns Resolves with result of update call */ export async function copyFromRTDBToStorage(app1: admin.app.App, app2: admin.app.App, eventData: ActionStep) { if (!app1?.database) { throw new Error('Invalid service account, database not defined on app1') } const { src, dest } = eventData try { const firstRTDB = app1.database() const firstDataSnap = await firstRTDB.ref(src.path).once('value') const firstDataVal = firstDataSnap.val() if (!firstDataVal) { throw new Error('Data not found at provided path') } // TODO: Handle non-json values await uploadToStorage(app2, dest.path, firstDataVal) console.log('copy from RTDB to Storage was successful') } catch (err) { console.error('Error copying from RTDB to Storage: ', err.message || err) throw err } }
the_stack
import { VueConstructor } from 'vue'; export type previewPropType = string | string[] | Element | NodeList; export type DragMode = 'none' | 'crop' | 'move'; export interface CroppedCanvasOptions { /** * the destination width of the output canvas. */ width?: number | undefined; /** * the destination height of the output canvas. */ height?: number | undefined; /** * the minimum destination width of the output canvas, the default value is 0. */ minWidth?: number | undefined; /** * the minimum destination height of the output canvas, the default value is 0. */ minHeight?: number | undefined; /** * the maximum destination width of the output canvas, the default value is Infinity. */ maxWidth?: number | undefined; /** * the maximum destination height of the output canvas, the default value is Infinity. */ maxHeight?: number | undefined; /** * a color to fill any alpha values in the output canvas, the default value is transparent. */ fillColor?: string | undefined; /** * set to change if images are smoothed (true, default) or not (false). */ imageSmoothingEnabled?: boolean | undefined; /** * set the quality of image smoothing, one of "low" (default), "medium", or "high". */ imageSmoothingQuality?: 'low' | 'medium' | 'high' | undefined; } export interface CropBoxData { /** * the offset left of the crop box */ left: number; /** * the offset top of the crop box */ top: number; /** * the width of the crop box */ width: number; /** * the height of the crop box */ height: number; } export interface CanvasData { /** * the offset left of the canvas */ left: number; /** * the offset top of the canvas */ top: number; /** * the width of the canvas */ width: number; /** * the height of the canvas */ height: number; /** * the natural width of the canvas (read only) */ naturalWidth: number; /** * the natural height of the canvas (read only) */ naturalHeight: number; } export interface ImageData { /** * the offset left of the image */ left: number; /** * the offset top of the image */ top: number; /** * the width of the image */ width: number; /** * the height of the image */ height: number; /** * the natural width of the image */ naturalWidth: number; /** * the natural height of the image */ naturalHeight: number; /** * the aspect ratio of the image */ aspectRatio: number; /** * the rotated degrees of the image if rotated */ rotate: number; /** * the scaling factor to apply on the abscissa of the image if scaled */ scaleX: number; /** * the scaling factor to apply on the ordinate of the image if scaled */ scaleY: number; } export interface ContainerData { /** * the current width of the container */ width: number; /** * the current height of the container */ height: number; } export interface CropperData { /** * the offset left of the cropped area */ x: number; /** * the offset top of the cropped area */ y: number; /** * the width of the cropped area */ width: number; /** * the height of the cropped area */ height: number; /** * the rotated degrees of the image */ rotate: number; /** * the scaling factor to apply on the abscissa of the image */ scaleX: number; /** * the scaling factor to apply on the ordinate of the image */ scaleY: number; } export interface VueCropperMethods { /** * Reset cropper to original state */ reset(): void; /** * Clear image from the cropper */ clear(): void; /** * Initialize the cropper */ initCrop(): void; /** * Replace the image's src and rebuild the cropper. * @param url A new image url. * @param hasSameSize Default false If the new image has the same size as the old one, * then it will not rebuild the cropper and only update the URLs of all related images. This can be used for applying filters. */ replace(url: string, hasSameSize?: boolean): void; /** * Enable (unfreeze) the cropper. */ enable(): void; /** * Disable (freeze) the cropper. */ disable(): void; /** * Destroy the cropper and remove the instance from the image. */ destroy(): void; /** * Move the canvas (image wrapper) with relative offsets. * @param offsetX Moving size (px) in the horizontal direction. * @param offsetY Moving size (px) in the vertical direction. If not present, its default value is offsetX. */ move(offsetX: number, offsetY?: number): void; /** * Move the canvas (image wrapper) to an absolute point. * @param x The left value of the canvas * @param y The top value of the canvas. If not present, its default value is x. */ moveTo(x: number, y?: number): void; /** * Zoom the canvas (image wrapper) with a relative ratio. * @param ratio Zoom in: requires a positive number (ratio > 0) Zoom out: requires a negative number (ratio < 0) * @param _originalEvent */ relativeZoom(ratio: number, _originalEvent?: Event): void; /** * Zoom the canvas (image wrapper) to an absolute ratio. * @param ratio Requires a positive number (ratio > 0) * @param _originalEvent */ zoomTo(ratio: number, _originalEvent?: Event): void; /** * Rotate the image with a relative degree. * @param degree Rotate right: requires a positive number (degree > 0) Rotate left: requires a negative number (degree < 0) */ rotate(degree: number): void; /** * Rotate the image to an absolute degree. * @param degree Amount to rotate image */ rotateTo(degree: number): void; /** * @param _scaleX The scaling factor to apply to the abscissa of the image. When equal to 1 it does nothing */ scaleX(_scaleX: number): void; /** * @param _scaleY The scaling factor to apply to the ordinate of the image. When equal to 1 it does nothing */ scaleY(_scaleY: number): void; /** * Scale the image. * Requires CSS3 2D Transforms support (IE 9+). * @param scaleX The scaling factor to apply to the abscissa of the image. When equal to 1 it does nothing * @param scaleY The scaling factor to apply to the ordinate of the image. When equal to 1 it does nothing */ scale(scaleX: number, scaleY?: number): void; /** * Change the cropped area position and size with new data (base on the original image). * Note: This method only available when the value of the viewMode option is greater than or equal to 1. * @param data The cropper data to set with. You may need to round the data properties before passing them in. */ setData(data: CropperData): void; /** * Output the final cropped area position and size data (base on the natural size of the original image). */ getData(rounded?: boolean): CropperData; /** * Output the container size data. */ getContainerData(): ContainerData; /** * Output the image position, size, and other related data. */ getImageData(): ImageData; /** * Output the canvas (image wrapper) position and size data. */ getCanvasData(): CanvasData; /** * Change the canvas (image wrapper) position and size with new data. * @param data Canvas Data to be set */ setCanvasData(data: CanvasData): void; /** * Output the crop box position and size data. */ getCropBoxData(): CropBoxData; /** * Change the crop box position and size with new data. * @param data Crop Box Data */ setCropBoxData(data: CropBoxData): void; /** * Get a canvas drawn the cropped image (lossy compression). If it is not cropped, then returns a canvas drawn the whole image. * Avoid to get a blank (or black) output image, you might need to set the maxWidth and maxHeight properties to limited numbers, because of the size limits of a canvas element. * Also, you should limit them maximum zoom ratio (in the zoom event) as the same reason. * @param options */ getCroppedCanvas(options?: CroppedCanvasOptions): HTMLCanvasElement; /** * Change the aspect ratio of the crop box. * @param aspectRatio */ setAspectRatio(aspectRatio: number): void; /** * Change the drag mode. * Tips: You can toggle the "crop" and "move" mode by double click on the cropper. * @param mode */ setDragMode(mode: DragMode): void; } export interface VueCropperProps { containerStyle: Record<string, any>; src: { type: string; default: ''; }; alt: string; imgStyle: Record<string, any>; viewMode: number; dragMode: string; initialAspectRatio: number; aspectRatio: number; data: Record<string, any>; preview: previewPropType; responsive: { type: boolean; default: true; }; restore: { type: boolean; default: true; }; checkCrossOrigin: { type: boolean; default: true; }; checkOrientation: { type: boolean; default: true; }; modal: { type: boolean; default: true; }; guides: { type: boolean; default: true; }; center: { type: boolean; default: true; }; highlight: { type: boolean; default: true; }; background: { type: boolean; default: true; }; autoCrop: { type: boolean; default: true; }; autoCropArea: number; movable: { type: boolean; default: true; }; rotatable: { type: boolean; default: true; }; scalable: { type: boolean; default: true; }; zoomable: { type: boolean; default: true; }; zoomOnTouch: { type: boolean; default: true; }; zoomOnWheel: { type: boolean; default: true; }; wheelZoomRatio: number; cropBoxMovable: { type: boolean; default: true; }; cropBoxResizable: { type: boolean; default: true; }; toggleDragModeOnDblclick: { type: boolean; default: true; }; minCanvasWidth: number; minCanvasHeight: number; minCropBoxWidth: number; minCropBoxHeight: number; minContainerWidth: number; minContainerHeight: number; ready: () => void; cropstart: () => void; cropmove: () => void; cropend: () => void; crop: () => void; zoom: () => void; } export interface VueCropperJsConstructor extends VueConstructor { props: VueCropperProps; methods: VueCropperMethods; data: () => void; } export const VueCropperJs: VueCropperJsConstructor; export default VueCropperJs;
the_stack
// Utility types /** * @internal Base type for all `methods`-like metadata. * @template This The type to use for `this` within methods. */ interface MethodMap<This> { [s: string]: ((this: This, ...args: any[]) => any) | {}; } /** @internal A plain old JavaScript object created by a `Stamp`. */ type Pojo = object; // { [s: string]: any; } /** @internal Base type for all `properties`-like metadata. */ // TODO: discriminate Array type PropertyMap = object; // { [s: string]: any; } /** @internal Signature common to every `Stamp`s. */ interface StampSignature { (options?: PropertyMap, ...args: unknown[]): any; compose: ComposeMethod & stampit.Descriptor<any, any>; } /** * @internal Extracts the `Stamp` type. * @template Original The type to extract the `Stamp` type from. */ type StampType<Original> = Original extends /* disallowed types */ [] | bigint ? never : stampit.IsADescriptor<Original> extends true ? (Original extends stampit.ExtendedDescriptor<infer Obj, infer Stamp> ? Stamp : never) : unknown extends Original /* is any or unknown */ ? stampit.Stamp<Original> : Original extends StampSignature ? Original : Original extends stampit.ExtendedDescriptor<infer Obj, any> ? stampit.Stamp<Obj> : Original extends Pojo ? stampit.Stamp<Original> /*assume it is the object from a stamp object*/ : never; /** * @internal The type of the object produced by the `Stamp`. * @template Original The type (either a `Stamp` or a `ExtendedDescriptor`) to get the object type from. */ type StampObjectType<Original> = Original extends /* disallowed types */ bigint | boolean | number | string | symbol ? never : stampit.IsADescriptor<Original> extends true ? (Original extends stampit.ExtendedDescriptor<infer Obj, any> ? Obj : never) : unknown extends Original /* is any or unknown */ ? Original : Original extends StampSignature ? (Original extends stampit.Stamp<infer Obj> /* extended stamps may require infering twice */ ? (Obj extends stampit.Stamp<infer Obj> ? Obj : Obj) : any) : Original extends stampit.ExtendedDescriptor<infer Obj, any> ? Obj : Original extends Pojo ? Original : never; /** * A factory function to create plain object instances. * @template Obj The object type that the `Stamp` will create. */ interface FactoryFunction<Obj> { (options?: PropertyMap, ...args: any[]): StampObjectType<Obj>; } /** * @internal Chainables `Stamp` additionnal methods * @template Obj The object type that the `Stamp` will create. */ type StampChainables<Obj> = Chainables<StampObjectType<Obj>, StampType<Obj>>; /** * @internal Chainables `Stamp` additionnal methods * @template Obj The object type that the `Stamp` will create. * @template S̤t̤a̤m̤p̤ The type of the `Stamp` (when extending a `Stamp`.) */ interface Chainables<Obj, S̤t̤a̤m̤p̤ extends StampSignature> { /** * Add methods to the methods prototype. Creates and returns new Stamp. **Chainable**. * @template This The type to use for `this` within methods. * @param methods Object(s) containing map of method names and bodies for delegation. */ // tslint:disable-next-line: no-unnecessary-generics methods<This = Obj>(...methods: Array<MethodMap<This>>): S̤t̤a̤m̤p̤; /** * Take a variable number of objects and shallow assign them to any future created instance of the Stamp. Creates and returns new Stamp. **Chainable**. * @param objects Object(s) to shallow assign for each new object. */ properties(...objects: PropertyMap[]): S̤t̤a̤m̤p̤; /** * Take a variable number of objects and shallow assign them to any future created instance of the Stamp. Creates and returns new Stamp. **Chainable**. * @param objects Object(s) to shallow assign for each new object. */ props(...objects: PropertyMap[]): S̤t̤a̤m̤p̤; /** * Take a variable number of objects and deeply merge them to any future created instance of the Stamp. Creates and returns a new Stamp. **Chainable**. * @param deepObjects The object(s) to deeply merge for each new object. */ deepProperties(...deepObjects: PropertyMap[]): S̤t̤a̤m̤p̤; /** * Take a variable number of objects and deeply merge them to any future created instance of the Stamp. Creates and returns a new Stamp. **Chainable**. * @param deepObjects The object(s) to deeply merge for each new object. */ deepProps(...deepObjects: PropertyMap[]): S̤t̤a̤m̤p̤; /** * Take in a variable number of functions and add them to the initializers prototype as initializers. **Chainable**. * @param functions Initializer functions used to create private data and privileged methods. */ initializers(...functions: Array<stampit.Initializer<Obj, S̤t̤a̤m̤p̤>>): S̤t̤a̤m̤p̤; initializers(functions: Array<stampit.Initializer<Obj, S̤t̤a̤m̤p̤>>): S̤t̤a̤m̤p̤; /** * Take in a variable number of functions and add them to the initializers prototype as initializers. **Chainable**. * @param functions Initializer functions used to create private data and privileged methods. */ init(...functions: Array<stampit.Initializer<Obj, S̤t̤a̤m̤p̤>>): S̤t̤a̤m̤p̤; init(functions: Array<stampit.Initializer<Obj, S̤t̤a̤m̤p̤>>): S̤t̤a̤m̤p̤; /** * Take n objects and add them to a new stamp and any future stamp it composes with. Creates and returns new Stamp. **Chainable**. * @param statics Object(s) containing map of property names and values to mixin into each new stamp. */ staticProperties(...statics: PropertyMap[]): S̤t̤a̤m̤p̤; /** * Take n objects and add them to a new stamp and any future stamp it composes with. Creates and returns new Stamp. **Chainable**. * @param statics Object(s) containing map of property names and values to mixin into each new stamp. */ statics(...statics: PropertyMap[]): S̤t̤a̤m̤p̤; /** * Deeply merge a variable number of objects and add them to a new stamp and any future stamp it composes. Creates and returns a new Stamp. **Chainable**. * @param deepStatics The object(s) containing static properties to be merged. */ staticDeepProperties(...deepStatics: PropertyMap[]): S̤t̤a̤m̤p̤; /** * Deeply merge a variable number of objects and add them to a new stamp and any future stamp it composes. Creates and returns a new Stamp. **Chainable**. * @param deepStatics The object(s) containing static properties to be merged. */ deepStatics(...deepStatics: PropertyMap[]): S̤t̤a̤m̤p̤; /** * Take in a variable number of functions and add them to the composers prototype as composers. **Chainable**. * @param functions Composer functions that will run in sequence while creating a new stamp from a list of composables. The resulting stamp and the composables get passed to composers. */ composers(...functions: Array<stampit.Composer<S̤t̤a̤m̤p̤>>): S̤t̤a̤m̤p̤; composers(functions: Array<stampit.Composer<S̤t̤a̤m̤p̤>>): S̤t̤a̤m̤p̤; /** * Shallowly assign properties of Stamp arbitrary metadata and add them to a new stamp and any future Stamp it composes. Creates and returns a new Stamp. **Chainable**. * @param confs The object(s) containing metadata properties. */ configuration(...confs: PropertyMap[]): S̤t̤a̤m̤p̤; /** * Shallowly assign properties of Stamp arbitrary metadata and add them to a new stamp and any future Stamp it composes. Creates and returns a new Stamp. **Chainable**. * @param confs The object(s) containing metadata properties. */ conf(...confs: PropertyMap[]): S̤t̤a̤m̤p̤; /** * Deeply merge properties of Stamp arbitrary metadata and add them to a new Stamp and any future Stamp it composes. Creates and returns a new Stamp. **Chainable**. * @param deepConfs The object(s) containing metadata properties. */ deepConfiguration(...deepConfs: PropertyMap[]): S̤t̤a̤m̤p̤; /** * Deeply merge properties of Stamp arbitrary metadata and add them to a new Stamp and any future Stamp it composes. Creates and returns a new Stamp. **Chainable**. * @param deepConfs The object(s) containing metadata properties. */ deepConf(...deepConfs: PropertyMap[]): S̤t̤a̤m̤p̤; /** * Apply ES5 property descriptors to object instances created by the new Stamp returned by the function and any future Stamp it composes. Creates and returns a new stamp. **Chainable**. * @param descriptors */ propertyDescriptors(...descriptors: PropertyDescriptorMap[]): S̤t̤a̤m̤p̤; /** * Apply ES5 property descriptors to a Stamp and any future Stamp it composes. Creates and returns a new stamp. **Chainable**. * @param descriptors */ staticPropertyDescriptors(...descriptors: PropertyDescriptorMap[]): S̤t̤a̤m̤p̤; } /** * A function which creates a new `Stamp`s from a list of `Composable`s. * @template Obj The type of the object instance being produced by the `Stamp` or the type of the `Stamp` being created (when extending a `Stamp`.) */ type ComposeMethod = typeof stampit; /** * A function which creates a new `Stamp`s from a list of `Composable`s. * @template Obj The type of the object instance being created by the `Stamp` or the type of the `Stamp` being created (when extending a `Stamp`.) */ // tslint:disable-next-line: no-unnecessary-generics declare function stampit<Obj = any>(...composables: stampit.Composable[]): StampType<Obj>; declare namespace stampit { /** A composable object (either a `Stamp` or a `ExtendedDescriptor`.) */ type Composable = StampSignature | ExtendedDescriptor<any, any>; /** * A `Stamp`'s metadata. * @template Obj The type of the object instance being produced by the `Stamp`. * @template S̤t̤a̤m̤p̤ The type of the `Stamp` (when extending a `Stamp`.) */ interface Descriptor<Obj, S̤t̤a̤m̤p̤ extends StampSignature = Stamp<Obj>> { /** A set of methods that will be added to the object's delegate prototype. */ methods?: MethodMap<Obj>; /** A set of properties that will be added to new object instances by assignment. */ properties?: PropertyMap; /** A set of properties that will be added to new object instances by deep property merge. */ deepProperties?: PropertyMap; /** A set of object property descriptors (`PropertyDescriptor`) used for fine-grained control over object property behaviors. */ propertyDescriptors?: PropertyDescriptorMap; /** A set of static properties that will be copied by assignment to the `Stamp`. */ staticProperties?: PropertyMap /* & ThisType<S> */; /** A set of static properties that will be added to the `Stamp` by deep property merge. */ staticDeepProperties?: PropertyMap /* & ThisType<S> */; /** A set of object property descriptors (`PropertyDescriptor`) to apply to the `Stamp`. */ staticPropertyDescriptors?: PropertyDescriptorMap /* & ThisType<S> */; /** An array of functions that will run in sequence while creating an object instance from a `Stamp`. `Stamp` details and arguments get passed to initializers. */ initializers?: Initializer<Obj, S̤t̤a̤m̤p̤> | Array<Initializer<Obj, S̤t̤a̤m̤p̤>>; /** An array of functions that will run in sequence while creating a new `Stamp` from a list of `Composable`s. The resulting `Stamp` and the `Composable`s get passed to composers. */ composers?: Array<Composer<S̤t̤a̤m̤p̤>>; /** A set of options made available to the `Stamp` and its initializers during object instance creation. These will be copied by assignment. */ configuration?: PropertyMap /* & ThisType<S> */; /** A set of options made available to the `Stamp` and its initializers during object instance creation. These will be deep merged. */ deepConfiguration?: PropertyMap /* & ThisType<S> */; } /** * A `stampit`'s metadata. * @template Obj The type of the object instance being produced by the `Stamp`. * @template S̤t̤a̤m̤p̤ The type of the `Stamp` (when extending a `Stamp`.) */ interface ExtendedDescriptor<Obj, S̤t̤a̤m̤p̤ extends StampSignature = Stamp<Obj>> extends Descriptor<Obj, S̤t̤a̤m̤p̤> { /** A set of properties that will be added to new object instances by assignment. */ props?: PropertyMap; /** A set of properties that will be added to new object instances by deep property merge. */ deepProps?: PropertyMap; /** A set of static properties that will be copied by assignment to the `Stamp`. */ statics?: PropertyMap /* & ThisType<S> */; /** A set of static properties that will be added to the `Stamp` by deep property merge. */ deepStatics?: PropertyMap /* & ThisType<S> */; /** An array of functions that will run in sequence while creating an object instance from a `Stamp`. `Stamp` details and arguments get passed to initializers. */ init?: Initializer<Obj, S̤t̤a̤m̤p̤> | Array<Initializer<Obj, S̤t̤a̤m̤p̤>>; /** A set of options made available to the `Stamp` and its initializers during object instance creation. These will be copied by assignment. */ conf?: PropertyMap /* & ThisType<S> */; /** A set of options made available to the `Stamp` and its initializers during object instance creation. These will be deep merged. */ deepConf?: PropertyMap /* & ThisType<S> */; // TODO: Add description name?: string; } /** * @internal Checks that a type is a ExtendedDescriptor (except `any` and `unknown`). * @template Type A type to check if a ExtendedDescriptor. */ // TODO: Improve test by checking the type of common keys type IsADescriptor<Type> = unknown extends Type ? (keyof Type extends never ? false : keyof Type extends infer K ? (K extends keyof ExtendedDescriptor<unknown> ? true : false) : false) : false; /** * A function used as `.initializers` argument. * @template Obj The type of the object instance being produced by the `Stamp`. * @template S̤t̤a̤m̤p̤ The type of the `Stamp` producing the instance. */ interface Initializer<Obj, S̤t̤a̤m̤p̤ extends StampSignature> { (this: Obj, options: /*_propertyMap*/ any, context: InitializerContext<Obj, S̤t̤a̤m̤p̤>): void | Obj; } /** * The `Initializer` function context. * @template Obj The type of the object instance being produced by the `Stamp`. * @template S̤t̤a̤m̤p̤ The type of the `Stamp` producing the instance. */ interface InitializerContext<Obj, S̤t̤a̤m̤p̤ extends StampSignature> { /** The object instance being produced by the `Stamp`. If the initializer returns a value other than `undefined`, it replaces the instance. */ instance: Obj; /** A reference to the `Stamp` producing the instance. */ stamp: S̤t̤a̤m̤p̤; /** An array of the arguments passed into the `Stamp`, including the options argument. */ // ! above description from the specification is obscure args: any[]; } /** * A function used as `.composers` argument. * @template S̤t̤a̤m̤p̤ The type of the `Stamp` produced by the `.compose()` method. */ interface Composer<S̤t̤a̤m̤p̤ extends StampSignature> { (parameters: ComposerParameters<S̤t̤a̤m̤p̤>): void | S̤t̤a̤m̤p̤; } /** * The parameters received by the current `.composers` function. * @template S̤t̤a̤m̤p̤ The type of the `Stamp` produced by the `.compose()` method. */ interface ComposerParameters<S̤t̤a̤m̤p̤ extends StampSignature> { /** The result of the `Composable`s composition. */ stamp: S̤t̤a̤m̤p̤; /** The list of composables the `Stamp` was just composed of. */ composables: Composable[]; } /** * A factory function to create plain object instances. * * It also has a `.compose()` method which is a copy of the `ComposeMethod` function and a `.compose` accessor to its `Descriptor`. * @template Obj The object type that the `Stamp` will create. */ interface Stamp<Obj> extends FactoryFunction<Obj>, StampChainables<Obj>, StampSignature { /** Just like calling stamp(), stamp.create() invokes the stamp and returns a new instance. */ create: FactoryFunction<Obj>; /** * A function which creates a new `Stamp`s from a list of `Composable`s. * @template Obj The type of the object instance being produced by the `Stamp`. or the type of the `Stamp` being created. */ compose: ComposeMethod & Descriptor<StampObjectType<Obj>>; } /** * A shortcut method for stampit().methods() * * Add methods to the methods prototype. Creates and returns new Stamp. **Chainable**. * @template Obj The type of the object instance being produced by the `Stamp`. or the type of the `Stamp` being created. * @template This The type to use for `this` within methods. * @param methods Object(s) containing map of method names and bodies for delegation. */ function methods<Obj = any>(this: StampObjectType<Obj>, ...methods: Array<MethodMap<Obj>>): StampType<Obj>; /** * A shortcut method for stampit().properties() * * Take a variable number of objects and shallow assign them to any future created instance of the Stamp. Creates and returns new Stamp. **Chainable**. * @template Obj The type of the object instance being produced by the `Stamp`. or the type of the `Stamp` being created. * @param objects Object(s) to shallow assign for each new object. */ // tslint:disable-next-line: no-unnecessary-generics function properties<Obj = any>(...objects: PropertyMap[]): StampType<Obj>; /** * A shortcut method for stampit().props() * * Take a variable number of objects and shallow assign them to any future created instance of the Stamp. Creates and returns new Stamp. **Chainable**. * @template Obj The type of the object instance being produced by the `Stamp`. or the type of the `Stamp` being created. * @param objects Object(s) to shallow assign for each new object. */ // tslint:disable-next-line: no-unnecessary-generics function props<Obj = any>(...objects: PropertyMap[]): StampType<Obj>; /** * A shortcut method for stampit().deepProperties() * * Take a variable number of objects and deeply merge them to any future created instance of the Stamp. Creates and returns a new Stamp. * @template Obj The type of the object instance being produced by the `Stamp`. or the type of the `Stamp` being created. * @param deepObjects The object(s) to deeply merge for each new object */ // tslint:disable-next-line: no-unnecessary-generics function deepProperties<Obj = any>(...deepObjects: PropertyMap[]): StampType<Obj>; /** * A shortcut method for stampit().deepProps() * * Take a variable number of objects and deeply merge them to any future created instance of the Stamp. Creates and returns a new Stamp. * @template Obj The type of the object instance being produced by the `Stamp`. or the type of the `Stamp` being created. * @param deepObjects The object(s) to deeply merge for each new object */ // tslint:disable-next-line: no-unnecessary-generics function deepProps<Obj = any>(...deepObjects: PropertyMap[]): StampType<Obj>; /** * A shortcut method for stampit().initializers() * * Take in a variable number of functions and add them to the initializers prototype as initializers. **Chainable**. * @template Obj The type of the object instance being produced by the `Stamp`. or the type of the `Stamp` being created. * @param functions Initializer functions used to create private data and privileged methods */ function initializers<Obj = any, S̤t̤a̤m̤p̤ extends StampSignature = StampType<Obj>>( // tslint:disable-next-line: no-unnecessary-generics ...functions: Array<Initializer<StampObjectType<Obj>, S̤t̤a̤m̤p̤>> ): S̤t̤a̤m̤p̤; function initializers<Obj = any, S̤t̤a̤m̤p̤ extends StampSignature = StampType<Obj>>( // tslint:disable-next-line: no-unnecessary-generics functions: Array<Initializer<StampObjectType<Obj>, S̤t̤a̤m̤p̤>>, ): S̤t̤a̤m̤p̤; /** * A shortcut method for stampit().init() * * Take in a variable number of functions and add them to the initializers prototype as initializers. **Chainable**. * @template Obj The type of the object instance being produced by the `Stamp`. or the type of the `Stamp` being created. * @param functions Initializer functions used to create private data and privileged methods */ function init<Obj = any, S̤t̤a̤m̤p̤ extends StampSignature = StampType<Obj>>( // tslint:disable-next-line: no-unnecessary-generics ...functions: Array<Initializer<StampObjectType<Obj>, S̤t̤a̤m̤p̤>> ): S̤t̤a̤m̤p̤; function init<Obj = any, S̤t̤a̤m̤p̤ extends StampSignature = StampType<Obj>>( // tslint:disable-next-line: no-unnecessary-generics functions: Array<Initializer<StampObjectType<Obj>, S̤t̤a̤m̤p̤>>, ): S̤t̤a̤m̤p̤; /** * A shortcut method for stampit().statics() * * Take n objects and add them to a new stamp and any future stamp it composes with. Creates and returns new Stamp. **Chainable**. * @template Obj The type of the object instance being produced by the `Stamp`. or the type of the `Stamp` being created. * @param statics Object(s) containing map of property names and values to mixin into each new stamp. */ // tslint:disable-next-line: no-unnecessary-generics function staticProperties<Obj = any>(...statics: PropertyMap[]): StampType<Obj>; /** * A shortcut method for stampit().staticProperties() * * Take n objects and add them to a new stamp and any future stamp it composes with. Creates and returns new Stamp. **Chainable**. * @template Obj The type of the object instance being produced by the `Stamp`. or the type of the `Stamp` being created. * @param statics Object(s) containing map of property names and values to mixin into each new stamp. */ // tslint:disable-next-line: no-unnecessary-generics function statics<Obj = any>(...statics: PropertyMap[]): StampType<Obj>; /** * A shortcut method for stampit().staticDeepProperties() * * Deeply merge a variable number of objects and add them to a new stamp and any future stamp it composes. Creates and returns a new Stamp. **Chainable**. * @template Obj The type of the object instance being produced by the `Stamp`. or the type of the `Stamp` being created. * @param deepStatics The object(s) containing static properties to be merged */ // tslint:disable-next-line: no-unnecessary-generics function staticDeepProperties<Obj = any>(...deepStatics: PropertyMap[]): StampType<Obj>; /** * A shortcut method for stampit().deepStatics() * * Deeply merge a variable number of objects and add them to a new stamp and any future stamp it composes. Creates and returns a new Stamp. **Chainable**. * @template Obj The type of the object instance being produced by the `Stamp`. or the type of the `Stamp` being created. * @param deepStatics The object(s) containing static properties to be merged */ // tslint:disable-next-line: no-unnecessary-generics function deepStatics<Obj = any>(...deepStatics: PropertyMap[]): StampType<Obj>; /** * A shortcut method for stampit().composers() * * Take in a variable number of functions and add them to the composers prototype as composers. **Chainable**. * @template Obj The type of the object instance being produced by the `Stamp`. or the type of the `Stamp` being created. * @param functions Composer functions that will run in sequence while creating a new stamp from a list of composables. The resulting stamp and the composables get passed to composers. */ function composers<Obj = any>(...functions: Array<Composer<StampType<Obj>>>): StampType<Obj>; function composers<Obj = any>(functions: Array<Composer<StampType<Obj>>>): StampType<Obj>; /** * A shortcut method for stampit().configuration() * * Shallowly assign properties of Stamp arbitrary metadata and add them to a new stamp and any future Stamp it composes. Creates and returns a new Stamp. **Chainable**. * @template Obj The type of the object instance being produced by the `Stamp`. or the type of the `Stamp` being created. * @param confs The object(s) containing metadata properties */ // tslint:disable-next-line: no-unnecessary-generics function configuration<Obj = any>(...confs: PropertyMap[]): StampType<Obj>; /** * A shortcut method for stampit().conf() * * Shallowly assign properties of Stamp arbitrary metadata and add them to a new stamp and any future Stamp it composes. Creates and returns a new Stamp. **Chainable**. * @template Obj The type of the object instance being produced by the `Stamp`. or the type of the `Stamp` being created. * @param confs The object(s) containing metadata properties */ // tslint:disable-next-line: no-unnecessary-generics function conf<Obj = any>(...confs: PropertyMap[]): StampType<Obj>; /** * A shortcut method for stampit().deepConfiguration() * * Deeply merge properties of Stamp arbitrary metadata and add them to a new Stamp and any future Stamp it composes. Creates and returns a new Stamp. **Chainable**. * @template Obj The type of the object instance being produced by the `Stamp`. or the type of the `Stamp` being created. * @param deepConfs The object(s) containing metadata properties */ // tslint:disable-next-line: no-unnecessary-generics function deepConfiguration<Obj = any>(...deepConfs: PropertyMap[]): StampType<Obj>; /** * A shortcut method for stampit().deepConf() * * Deeply merge properties of Stamp arbitrary metadata and add them to a new Stamp and any future Stamp it composes. Creates and returns a new Stamp. **Chainable**. * @template Obj The type of the object instance being produced by the `Stamp`. or the type of the `Stamp` being created. * @param deepConfs The object(s) containing metadata properties */ // tslint:disable-next-line: no-unnecessary-generics function deepConf<Obj = any>(...deepConfs: PropertyMap[]): StampType<Obj>; /** * A shortcut method for stampit().propertyDescriptors() * * Apply ES5 property descriptors to object instances created by the new Stamp returned by the function and any future Stamp it composes. Creates and returns a new stamp. **Chainable**. * @template Obj The type of the object instance being produced by the `Stamp`. or the type of the `Stamp` being created. * @param descriptors */ // tslint:disable-next-line: no-unnecessary-generics function propertyDescriptors<Obj = any>(...descriptors: PropertyDescriptorMap[]): StampType<Obj>; /** * A shortcut method for stampit().staticPropertyDescriptors() * * Apply ES5 property descriptors to a Stamp and any future Stamp it composes. Creates and returns a new stamp. **Chainable**. * @template Obj The type of the object instance being produced by the `Stamp`. or the type of the `Stamp` being created. * @param descriptors */ // tslint:disable-next-line: no-unnecessary-generics function staticPropertyDescriptors<Obj = any>(...descriptors: PropertyDescriptorMap[]): StampType<Obj>; /** A function which creates a new `Stamp`s from a list of `Composable`s. */ const compose: ComposeMethod; /** the version of the NPM `stampit` package. */ const version: string; } export const compose: typeof stampit.compose; export const composers: typeof stampit.composers; export const conf: typeof stampit.conf; export const configuration: typeof stampit.configuration; export const deepConf: typeof stampit.deepConf; export const deepConfiguration: typeof stampit.deepConfiguration; export const deepProperties: typeof stampit.deepProperties; export const deepProps: typeof stampit.deepProps; export const deepStatics: typeof stampit.deepStatics; export const init: typeof stampit.init; export const initializers: typeof stampit.initializers; export const methods: typeof stampit.methods; export const properties: typeof stampit.properties; export const propertyDescriptors: typeof stampit.propertyDescriptors; export const props: typeof stampit.props; export const staticDeepProperties: typeof stampit.staticDeepProperties; export const staticProperties: typeof stampit.staticProperties; export const staticPropertyDescriptors: typeof stampit.staticPropertyDescriptors; export const version: typeof stampit.version; // tslint:disable-next-line: npm-naming export default stampit;
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * A user-defined function or a stored procedure that belongs to a Dataset * * To get more information about Routine, see: * * * [API documentation](https://cloud.google.com/bigquery/docs/reference/rest/v2/routines) * * How-to Guides * * [Routines Intro](https://cloud.google.com/bigquery/docs/reference/rest/v2/routines) * * ## Example Usage * ### Big Query Routine Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const test = new gcp.bigquery.Dataset("test", {datasetId: "dataset_id"}); * const sproc = new gcp.bigquery.Routine("sproc", { * datasetId: test.datasetId, * routineId: "routine_id", * routineType: "PROCEDURE", * language: "SQL", * definitionBody: "CREATE FUNCTION Add(x FLOAT64, y FLOAT64) RETURNS FLOAT64 AS (x + y);", * }); * ``` * * ## Import * * Routine can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:bigquery/routine:Routine default projects/{{project}}/datasets/{{dataset_id}}/routines/{{routine_id}} * ``` * * ```sh * $ pulumi import gcp:bigquery/routine:Routine default {{project}}/{{dataset_id}}/{{routine_id}} * ``` * * ```sh * $ pulumi import gcp:bigquery/routine:Routine default {{dataset_id}}/{{routine_id}} * ``` */ export class Routine extends pulumi.CustomResource { /** * Get an existing Routine resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: RoutineState, opts?: pulumi.CustomResourceOptions): Routine { return new Routine(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:bigquery/routine:Routine'; /** * Returns true if the given object is an instance of Routine. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is Routine { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Routine.__pulumiType; } /** * Input/output argument of a function or a stored procedure. * Structure is documented below. */ public readonly arguments!: pulumi.Output<outputs.bigquery.RoutineArgument[] | undefined>; /** * The time when this routine was created, in milliseconds since the epoch. */ public /*out*/ readonly creationTime!: pulumi.Output<number>; /** * The ID of the dataset containing this routine */ public readonly datasetId!: pulumi.Output<string>; /** * The body of the routine. For functions, this is the expression in the AS clause. * If language=SQL, it is the substring inside (but excluding) the parentheses. */ public readonly definitionBody!: pulumi.Output<string>; /** * The description of the routine if defined. */ public readonly description!: pulumi.Output<string | undefined>; /** * The determinism level of the JavaScript UDF if defined. * Possible values are `DETERMINISM_LEVEL_UNSPECIFIED`, `DETERMINISTIC`, and `NOT_DETERMINISTIC`. */ public readonly determinismLevel!: pulumi.Output<string | undefined>; /** * Optional. If language = "JAVASCRIPT", this field stores the path of the * imported JAVASCRIPT libraries. */ public readonly importedLibraries!: pulumi.Output<string[] | undefined>; /** * The language of the routine. * Possible values are `SQL` and `JAVASCRIPT`. */ public readonly language!: pulumi.Output<string | undefined>; /** * The time when this routine was modified, in milliseconds since the epoch. */ public /*out*/ readonly lastModifiedTime!: pulumi.Output<number>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ public readonly project!: pulumi.Output<string>; /** * Optional. Can be set only if routineType = "TABLE_VALUED_FUNCTION". * If absent, the return table type is inferred from definitionBody at query time in each query * that references this routine. If present, then the columns in the evaluated table result will * be cast to match the column types specificed in return table type, at query time. */ public readonly returnTableType!: pulumi.Output<string | undefined>; /** * A JSON schema for the return type. Optional if language = "SQL"; required otherwise. * If absent, the return type is inferred from definitionBody at query time in each query * that references this routine. If present, then the evaluated result will be cast to * the specified returned type at query time. ~>**NOTE**: Because this field expects a JSON * string, any changes to the string will create a diff, even if the JSON itself hasn't * changed. If the API returns a different value for the same schema, e.g. it switche * d the order of values or replaced STRUCT field type with RECORD field type, we currently * cannot suppress the recurring diff this causes. As a workaround, we recommend using * the schema as returned by the API. */ public readonly returnType!: pulumi.Output<string | undefined>; /** * The ID of the the routine. The ID must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum length is 256 characters. */ public readonly routineId!: pulumi.Output<string>; /** * The type of routine. * Possible values are `SCALAR_FUNCTION`, `PROCEDURE`, and `TABLE_VALUED_FUNCTION`. */ public readonly routineType!: pulumi.Output<string | undefined>; /** * Create a Routine resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: RoutineArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: RoutineArgs | RoutineState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as RoutineState | undefined; inputs["arguments"] = state ? state.arguments : undefined; inputs["creationTime"] = state ? state.creationTime : undefined; inputs["datasetId"] = state ? state.datasetId : undefined; inputs["definitionBody"] = state ? state.definitionBody : undefined; inputs["description"] = state ? state.description : undefined; inputs["determinismLevel"] = state ? state.determinismLevel : undefined; inputs["importedLibraries"] = state ? state.importedLibraries : undefined; inputs["language"] = state ? state.language : undefined; inputs["lastModifiedTime"] = state ? state.lastModifiedTime : undefined; inputs["project"] = state ? state.project : undefined; inputs["returnTableType"] = state ? state.returnTableType : undefined; inputs["returnType"] = state ? state.returnType : undefined; inputs["routineId"] = state ? state.routineId : undefined; inputs["routineType"] = state ? state.routineType : undefined; } else { const args = argsOrState as RoutineArgs | undefined; if ((!args || args.datasetId === undefined) && !opts.urn) { throw new Error("Missing required property 'datasetId'"); } if ((!args || args.definitionBody === undefined) && !opts.urn) { throw new Error("Missing required property 'definitionBody'"); } if ((!args || args.routineId === undefined) && !opts.urn) { throw new Error("Missing required property 'routineId'"); } inputs["arguments"] = args ? args.arguments : undefined; inputs["datasetId"] = args ? args.datasetId : undefined; inputs["definitionBody"] = args ? args.definitionBody : undefined; inputs["description"] = args ? args.description : undefined; inputs["determinismLevel"] = args ? args.determinismLevel : undefined; inputs["importedLibraries"] = args ? args.importedLibraries : undefined; inputs["language"] = args ? args.language : undefined; inputs["project"] = args ? args.project : undefined; inputs["returnTableType"] = args ? args.returnTableType : undefined; inputs["returnType"] = args ? args.returnType : undefined; inputs["routineId"] = args ? args.routineId : undefined; inputs["routineType"] = args ? args.routineType : undefined; inputs["creationTime"] = undefined /*out*/; inputs["lastModifiedTime"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Routine.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Routine resources. */ export interface RoutineState { /** * Input/output argument of a function or a stored procedure. * Structure is documented below. */ arguments?: pulumi.Input<pulumi.Input<inputs.bigquery.RoutineArgument>[]>; /** * The time when this routine was created, in milliseconds since the epoch. */ creationTime?: pulumi.Input<number>; /** * The ID of the dataset containing this routine */ datasetId?: pulumi.Input<string>; /** * The body of the routine. For functions, this is the expression in the AS clause. * If language=SQL, it is the substring inside (but excluding) the parentheses. */ definitionBody?: pulumi.Input<string>; /** * The description of the routine if defined. */ description?: pulumi.Input<string>; /** * The determinism level of the JavaScript UDF if defined. * Possible values are `DETERMINISM_LEVEL_UNSPECIFIED`, `DETERMINISTIC`, and `NOT_DETERMINISTIC`. */ determinismLevel?: pulumi.Input<string>; /** * Optional. If language = "JAVASCRIPT", this field stores the path of the * imported JAVASCRIPT libraries. */ importedLibraries?: pulumi.Input<pulumi.Input<string>[]>; /** * The language of the routine. * Possible values are `SQL` and `JAVASCRIPT`. */ language?: pulumi.Input<string>; /** * The time when this routine was modified, in milliseconds since the epoch. */ lastModifiedTime?: pulumi.Input<number>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * Optional. Can be set only if routineType = "TABLE_VALUED_FUNCTION". * If absent, the return table type is inferred from definitionBody at query time in each query * that references this routine. If present, then the columns in the evaluated table result will * be cast to match the column types specificed in return table type, at query time. */ returnTableType?: pulumi.Input<string>; /** * A JSON schema for the return type. Optional if language = "SQL"; required otherwise. * If absent, the return type is inferred from definitionBody at query time in each query * that references this routine. If present, then the evaluated result will be cast to * the specified returned type at query time. ~>**NOTE**: Because this field expects a JSON * string, any changes to the string will create a diff, even if the JSON itself hasn't * changed. If the API returns a different value for the same schema, e.g. it switche * d the order of values or replaced STRUCT field type with RECORD field type, we currently * cannot suppress the recurring diff this causes. As a workaround, we recommend using * the schema as returned by the API. */ returnType?: pulumi.Input<string>; /** * The ID of the the routine. The ID must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum length is 256 characters. */ routineId?: pulumi.Input<string>; /** * The type of routine. * Possible values are `SCALAR_FUNCTION`, `PROCEDURE`, and `TABLE_VALUED_FUNCTION`. */ routineType?: pulumi.Input<string>; } /** * The set of arguments for constructing a Routine resource. */ export interface RoutineArgs { /** * Input/output argument of a function or a stored procedure. * Structure is documented below. */ arguments?: pulumi.Input<pulumi.Input<inputs.bigquery.RoutineArgument>[]>; /** * The ID of the dataset containing this routine */ datasetId: pulumi.Input<string>; /** * The body of the routine. For functions, this is the expression in the AS clause. * If language=SQL, it is the substring inside (but excluding) the parentheses. */ definitionBody: pulumi.Input<string>; /** * The description of the routine if defined. */ description?: pulumi.Input<string>; /** * The determinism level of the JavaScript UDF if defined. * Possible values are `DETERMINISM_LEVEL_UNSPECIFIED`, `DETERMINISTIC`, and `NOT_DETERMINISTIC`. */ determinismLevel?: pulumi.Input<string>; /** * Optional. If language = "JAVASCRIPT", this field stores the path of the * imported JAVASCRIPT libraries. */ importedLibraries?: pulumi.Input<pulumi.Input<string>[]>; /** * The language of the routine. * Possible values are `SQL` and `JAVASCRIPT`. */ language?: pulumi.Input<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * Optional. Can be set only if routineType = "TABLE_VALUED_FUNCTION". * If absent, the return table type is inferred from definitionBody at query time in each query * that references this routine. If present, then the columns in the evaluated table result will * be cast to match the column types specificed in return table type, at query time. */ returnTableType?: pulumi.Input<string>; /** * A JSON schema for the return type. Optional if language = "SQL"; required otherwise. * If absent, the return type is inferred from definitionBody at query time in each query * that references this routine. If present, then the evaluated result will be cast to * the specified returned type at query time. ~>**NOTE**: Because this field expects a JSON * string, any changes to the string will create a diff, even if the JSON itself hasn't * changed. If the API returns a different value for the same schema, e.g. it switche * d the order of values or replaced STRUCT field type with RECORD field type, we currently * cannot suppress the recurring diff this causes. As a workaround, we recommend using * the schema as returned by the API. */ returnType?: pulumi.Input<string>; /** * The ID of the the routine. The ID must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum length is 256 characters. */ routineId: pulumi.Input<string>; /** * The type of routine. * Possible values are `SCALAR_FUNCTION`, `PROCEDURE`, and `TABLE_VALUED_FUNCTION`. */ routineType?: pulumi.Input<string>; }
the_stack
import type { Duration as _google_protobuf_Duration, Duration__Output as _google_protobuf_Duration__Output } from '../../../../google/protobuf/Duration'; import type { UInt32Value as _google_protobuf_UInt32Value, UInt32Value__Output as _google_protobuf_UInt32Value__Output } from '../../../../google/protobuf/UInt32Value'; import type { BoolValue as _google_protobuf_BoolValue, BoolValue__Output as _google_protobuf_BoolValue__Output } from '../../../../google/protobuf/BoolValue'; import type { EventServiceConfig as _envoy_config_core_v3_EventServiceConfig, EventServiceConfig__Output as _envoy_config_core_v3_EventServiceConfig__Output } from '../../../../envoy/config/core/v3/EventServiceConfig'; import type { Struct as _google_protobuf_Struct, Struct__Output as _google_protobuf_Struct__Output } from '../../../../google/protobuf/Struct'; import type { HeaderValueOption as _envoy_config_core_v3_HeaderValueOption, HeaderValueOption__Output as _envoy_config_core_v3_HeaderValueOption__Output } from '../../../../envoy/config/core/v3/HeaderValueOption'; import type { Int64Range as _envoy_type_v3_Int64Range, Int64Range__Output as _envoy_type_v3_Int64Range__Output } from '../../../../envoy/type/v3/Int64Range'; import type { CodecClientType as _envoy_type_v3_CodecClientType } from '../../../../envoy/type/v3/CodecClientType'; import type { StringMatcher as _envoy_type_matcher_v3_StringMatcher, StringMatcher__Output as _envoy_type_matcher_v3_StringMatcher__Output } from '../../../../envoy/type/matcher/v3/StringMatcher'; import type { Any as _google_protobuf_Any, Any__Output as _google_protobuf_Any__Output } from '../../../../google/protobuf/Any'; import type { Long } from '@grpc/proto-loader'; /** * Custom health check. */ export interface _envoy_config_core_v3_HealthCheck_CustomHealthCheck { /** * The registered name of the custom health checker. */ 'name'?: (string); 'typed_config'?: (_google_protobuf_Any | null); /** * A custom health checker specific configuration which depends on the custom health checker * being instantiated. See :api:`envoy/config/health_checker` for reference. */ 'config_type'?: "typed_config"; } /** * Custom health check. */ export interface _envoy_config_core_v3_HealthCheck_CustomHealthCheck__Output { /** * The registered name of the custom health checker. */ 'name': (string); 'typed_config'?: (_google_protobuf_Any__Output | null); /** * A custom health checker specific configuration which depends on the custom health checker * being instantiated. See :api:`envoy/config/health_checker` for reference. */ 'config_type': "typed_config"; } /** * `grpc.health.v1.Health * <https://github.com/grpc/grpc/blob/master/src/proto/grpc/health/v1/health.proto>`_-based * healthcheck. See `gRPC doc <https://github.com/grpc/grpc/blob/master/doc/health-checking.md>`_ * for details. */ export interface _envoy_config_core_v3_HealthCheck_GrpcHealthCheck { /** * An optional service name parameter which will be sent to gRPC service in * `grpc.health.v1.HealthCheckRequest * <https://github.com/grpc/grpc/blob/master/src/proto/grpc/health/v1/health.proto#L20>`_. * message. See `gRPC health-checking overview * <https://github.com/grpc/grpc/blob/master/doc/health-checking.md>`_ for more information. */ 'service_name'?: (string); /** * The value of the :authority header in the gRPC health check request. If * left empty (default value), the name of the cluster this health check is associated * with will be used. The authority header can be customized for a specific endpoint by setting * the :ref:`hostname <envoy_api_field_config.endpoint.v3.Endpoint.HealthCheckConfig.hostname>` field. */ 'authority'?: (string); } /** * `grpc.health.v1.Health * <https://github.com/grpc/grpc/blob/master/src/proto/grpc/health/v1/health.proto>`_-based * healthcheck. See `gRPC doc <https://github.com/grpc/grpc/blob/master/doc/health-checking.md>`_ * for details. */ export interface _envoy_config_core_v3_HealthCheck_GrpcHealthCheck__Output { /** * An optional service name parameter which will be sent to gRPC service in * `grpc.health.v1.HealthCheckRequest * <https://github.com/grpc/grpc/blob/master/src/proto/grpc/health/v1/health.proto#L20>`_. * message. See `gRPC health-checking overview * <https://github.com/grpc/grpc/blob/master/doc/health-checking.md>`_ for more information. */ 'service_name': (string); /** * The value of the :authority header in the gRPC health check request. If * left empty (default value), the name of the cluster this health check is associated * with will be used. The authority header can be customized for a specific endpoint by setting * the :ref:`hostname <envoy_api_field_config.endpoint.v3.Endpoint.HealthCheckConfig.hostname>` field. */ 'authority': (string); } /** * [#next-free-field: 12] */ export interface _envoy_config_core_v3_HealthCheck_HttpHealthCheck { /** * The value of the host header in the HTTP health check request. If * left empty (default value), the name of the cluster this health check is associated * with will be used. The host header can be customized for a specific endpoint by setting the * :ref:`hostname <envoy_api_field_config.endpoint.v3.Endpoint.HealthCheckConfig.hostname>` field. */ 'host'?: (string); /** * Specifies the HTTP path that will be requested during health checking. For example * * /healthcheck*. */ 'path'?: (string); /** * [#not-implemented-hide:] HTTP specific payload. */ 'send'?: (_envoy_config_core_v3_HealthCheck_Payload | null); /** * [#not-implemented-hide:] HTTP specific response. */ 'receive'?: (_envoy_config_core_v3_HealthCheck_Payload | null); /** * Specifies a list of HTTP headers that should be added to each request that is sent to the * health checked cluster. For more information, including details on header value syntax, see * the documentation on :ref:`custom request headers * <config_http_conn_man_headers_custom_request_headers>`. */ 'request_headers_to_add'?: (_envoy_config_core_v3_HeaderValueOption)[]; /** * Specifies a list of HTTP headers that should be removed from each request that is sent to the * health checked cluster. */ 'request_headers_to_remove'?: (string)[]; /** * Specifies a list of HTTP response statuses considered healthy. If provided, replaces default * 200-only policy - 200 must be included explicitly as needed. Ranges follow half-open * semantics of :ref:`Int64Range <envoy_api_msg_type.v3.Int64Range>`. The start and end of each * range are required. Only statuses in the range [100, 600) are allowed. */ 'expected_statuses'?: (_envoy_type_v3_Int64Range)[]; /** * Use specified application protocol for health checks. */ 'codec_client_type'?: (_envoy_type_v3_CodecClientType | keyof typeof _envoy_type_v3_CodecClientType); /** * An optional service name parameter which is used to validate the identity of * the health checked cluster using a :ref:`StringMatcher * <envoy_api_msg_type.matcher.v3.StringMatcher>`. See the :ref:`architecture overview * <arch_overview_health_checking_identity>` for more information. */ 'service_name_matcher'?: (_envoy_type_matcher_v3_StringMatcher | null); } /** * [#next-free-field: 12] */ export interface _envoy_config_core_v3_HealthCheck_HttpHealthCheck__Output { /** * The value of the host header in the HTTP health check request. If * left empty (default value), the name of the cluster this health check is associated * with will be used. The host header can be customized for a specific endpoint by setting the * :ref:`hostname <envoy_api_field_config.endpoint.v3.Endpoint.HealthCheckConfig.hostname>` field. */ 'host': (string); /** * Specifies the HTTP path that will be requested during health checking. For example * * /healthcheck*. */ 'path': (string); /** * [#not-implemented-hide:] HTTP specific payload. */ 'send': (_envoy_config_core_v3_HealthCheck_Payload__Output | null); /** * [#not-implemented-hide:] HTTP specific response. */ 'receive': (_envoy_config_core_v3_HealthCheck_Payload__Output | null); /** * Specifies a list of HTTP headers that should be added to each request that is sent to the * health checked cluster. For more information, including details on header value syntax, see * the documentation on :ref:`custom request headers * <config_http_conn_man_headers_custom_request_headers>`. */ 'request_headers_to_add': (_envoy_config_core_v3_HeaderValueOption__Output)[]; /** * Specifies a list of HTTP headers that should be removed from each request that is sent to the * health checked cluster. */ 'request_headers_to_remove': (string)[]; /** * Specifies a list of HTTP response statuses considered healthy. If provided, replaces default * 200-only policy - 200 must be included explicitly as needed. Ranges follow half-open * semantics of :ref:`Int64Range <envoy_api_msg_type.v3.Int64Range>`. The start and end of each * range are required. Only statuses in the range [100, 600) are allowed. */ 'expected_statuses': (_envoy_type_v3_Int64Range__Output)[]; /** * Use specified application protocol for health checks. */ 'codec_client_type': (keyof typeof _envoy_type_v3_CodecClientType); /** * An optional service name parameter which is used to validate the identity of * the health checked cluster using a :ref:`StringMatcher * <envoy_api_msg_type.matcher.v3.StringMatcher>`. See the :ref:`architecture overview * <arch_overview_health_checking_identity>` for more information. */ 'service_name_matcher': (_envoy_type_matcher_v3_StringMatcher__Output | null); } /** * Describes the encoding of the payload bytes in the payload. */ export interface _envoy_config_core_v3_HealthCheck_Payload { /** * Hex encoded payload. E.g., "000000FF". */ 'text'?: (string); /** * [#not-implemented-hide:] Binary payload. */ 'binary'?: (Buffer | Uint8Array | string); 'payload'?: "text"|"binary"; } /** * Describes the encoding of the payload bytes in the payload. */ export interface _envoy_config_core_v3_HealthCheck_Payload__Output { /** * Hex encoded payload. E.g., "000000FF". */ 'text'?: (string); /** * [#not-implemented-hide:] Binary payload. */ 'binary'?: (Buffer); 'payload': "text"|"binary"; } export interface _envoy_config_core_v3_HealthCheck_RedisHealthCheck { /** * If set, optionally perform ``EXISTS <key>`` instead of ``PING``. A return value * from Redis of 0 (does not exist) is considered a passing healthcheck. A return value other * than 0 is considered a failure. This allows the user to mark a Redis instance for maintenance * by setting the specified key to any value and waiting for traffic to drain. */ 'key'?: (string); } export interface _envoy_config_core_v3_HealthCheck_RedisHealthCheck__Output { /** * If set, optionally perform ``EXISTS <key>`` instead of ``PING``. A return value * from Redis of 0 (does not exist) is considered a passing healthcheck. A return value other * than 0 is considered a failure. This allows the user to mark a Redis instance for maintenance * by setting the specified key to any value and waiting for traffic to drain. */ 'key': (string); } export interface _envoy_config_core_v3_HealthCheck_TcpHealthCheck { /** * Empty payloads imply a connect-only health check. */ 'send'?: (_envoy_config_core_v3_HealthCheck_Payload | null); /** * When checking the response, “fuzzy” matching is performed such that each * binary block must be found, and in the order specified, but not * necessarily contiguous. */ 'receive'?: (_envoy_config_core_v3_HealthCheck_Payload)[]; } export interface _envoy_config_core_v3_HealthCheck_TcpHealthCheck__Output { /** * Empty payloads imply a connect-only health check. */ 'send': (_envoy_config_core_v3_HealthCheck_Payload__Output | null); /** * When checking the response, “fuzzy” matching is performed such that each * binary block must be found, and in the order specified, but not * necessarily contiguous. */ 'receive': (_envoy_config_core_v3_HealthCheck_Payload__Output)[]; } /** * Health checks occur over the transport socket specified for the cluster. This implies that if a * cluster is using a TLS-enabled transport socket, the health check will also occur over TLS. * * This allows overriding the cluster TLS settings, just for health check connections. */ export interface _envoy_config_core_v3_HealthCheck_TlsOptions { /** * Specifies the ALPN protocols for health check connections. This is useful if the * corresponding upstream is using ALPN-based :ref:`FilterChainMatch * <envoy_api_msg_config.listener.v3.FilterChainMatch>` along with different protocols for health checks * versus data connections. If empty, no ALPN protocols will be set on health check connections. */ 'alpn_protocols'?: (string)[]; } /** * Health checks occur over the transport socket specified for the cluster. This implies that if a * cluster is using a TLS-enabled transport socket, the health check will also occur over TLS. * * This allows overriding the cluster TLS settings, just for health check connections. */ export interface _envoy_config_core_v3_HealthCheck_TlsOptions__Output { /** * Specifies the ALPN protocols for health check connections. This is useful if the * corresponding upstream is using ALPN-based :ref:`FilterChainMatch * <envoy_api_msg_config.listener.v3.FilterChainMatch>` along with different protocols for health checks * versus data connections. If empty, no ALPN protocols will be set on health check connections. */ 'alpn_protocols': (string)[]; } /** * [#next-free-field: 25] */ export interface HealthCheck { /** * The time to wait for a health check response. If the timeout is reached the * health check attempt will be considered a failure. */ 'timeout'?: (_google_protobuf_Duration | null); /** * The interval between health checks. */ 'interval'?: (_google_protobuf_Duration | null); /** * An optional jitter amount in milliseconds. If specified, during every * interval Envoy will add interval_jitter to the wait time. */ 'interval_jitter'?: (_google_protobuf_Duration | null); /** * The number of unhealthy health checks required before a host is marked * unhealthy. Note that for *http* health checking if a host responds with 503 * this threshold is ignored and the host is considered unhealthy immediately. */ 'unhealthy_threshold'?: (_google_protobuf_UInt32Value | null); /** * The number of healthy health checks required before a host is marked * healthy. Note that during startup, only a single successful health check is * required to mark a host healthy. */ 'healthy_threshold'?: (_google_protobuf_UInt32Value | null); /** * [#not-implemented-hide:] Non-serving port for health checking. */ 'alt_port'?: (_google_protobuf_UInt32Value | null); /** * Reuse health check connection between health checks. Default is true. */ 'reuse_connection'?: (_google_protobuf_BoolValue | null); /** * HTTP health check. */ 'http_health_check'?: (_envoy_config_core_v3_HealthCheck_HttpHealthCheck | null); /** * TCP health check. */ 'tcp_health_check'?: (_envoy_config_core_v3_HealthCheck_TcpHealthCheck | null); /** * gRPC health check. */ 'grpc_health_check'?: (_envoy_config_core_v3_HealthCheck_GrpcHealthCheck | null); /** * The "no traffic interval" is a special health check interval that is used when a cluster has * never had traffic routed to it. This lower interval allows cluster information to be kept up to * date, without sending a potentially large amount of active health checking traffic for no * reason. Once a cluster has been used for traffic routing, Envoy will shift back to using the * standard health check interval that is defined. Note that this interval takes precedence over * any other. * * The default value for "no traffic interval" is 60 seconds. */ 'no_traffic_interval'?: (_google_protobuf_Duration | null); /** * Custom health check. */ 'custom_health_check'?: (_envoy_config_core_v3_HealthCheck_CustomHealthCheck | null); /** * The "unhealthy interval" is a health check interval that is used for hosts that are marked as * unhealthy. As soon as the host is marked as healthy, Envoy will shift back to using the * standard health check interval that is defined. * * The default value for "unhealthy interval" is the same as "interval". */ 'unhealthy_interval'?: (_google_protobuf_Duration | null); /** * The "unhealthy edge interval" is a special health check interval that is used for the first * health check right after a host is marked as unhealthy. For subsequent health checks * Envoy will shift back to using either "unhealthy interval" if present or the standard health * check interval that is defined. * * The default value for "unhealthy edge interval" is the same as "unhealthy interval". */ 'unhealthy_edge_interval'?: (_google_protobuf_Duration | null); /** * The "healthy edge interval" is a special health check interval that is used for the first * health check right after a host is marked as healthy. For subsequent health checks * Envoy will shift back to using the standard health check interval that is defined. * * The default value for "healthy edge interval" is the same as the default interval. */ 'healthy_edge_interval'?: (_google_protobuf_Duration | null); /** * Specifies the path to the :ref:`health check event log <arch_overview_health_check_logging>`. * If empty, no event log will be written. */ 'event_log_path'?: (string); /** * An optional jitter amount as a percentage of interval_ms. If specified, * during every interval Envoy will add interval_ms * * interval_jitter_percent / 100 to the wait time. * * If interval_jitter_ms and interval_jitter_percent are both set, both of * them will be used to increase the wait time. */ 'interval_jitter_percent'?: (number); /** * If set to true, health check failure events will always be logged. If set to false, only the * initial health check failure event will be logged. * The default value is false. */ 'always_log_health_check_failures'?: (boolean); /** * An optional jitter amount in milliseconds. If specified, Envoy will start health * checking after for a random time in ms between 0 and initial_jitter. This only * applies to the first health check. */ 'initial_jitter'?: (_google_protobuf_Duration | null); /** * This allows overriding the cluster TLS settings, just for health check connections. */ 'tls_options'?: (_envoy_config_core_v3_HealthCheck_TlsOptions | null); /** * [#not-implemented-hide:] * The gRPC service for the health check event service. * If empty, health check events won't be sent to a remote endpoint. */ 'event_service'?: (_envoy_config_core_v3_EventServiceConfig | null); /** * Optional key/value pairs that will be used to match a transport socket from those specified in the cluster's * :ref:`tranport socket matches <envoy_api_field_config.cluster.v3.Cluster.transport_socket_matches>`. * For example, the following match criteria * * .. code-block:: yaml * * transport_socket_match_criteria: * useMTLS: true * * Will match the following :ref:`cluster socket match <envoy_api_msg_config.cluster.v3.Cluster.TransportSocketMatch>` * * .. code-block:: yaml * * transport_socket_matches: * - name: "useMTLS" * match: * useMTLS: true * transport_socket: * name: envoy.transport_sockets.tls * config: { ... } # tls socket configuration * * If this field is set, then for health checks it will supersede an entry of *envoy.transport_socket* in the * :ref:`LbEndpoint.Metadata <envoy_api_field_config.endpoint.v3.LbEndpoint.metadata>`. * This allows using different transport socket capabilities for health checking versus proxying to the * endpoint. * * If the key/values pairs specified do not match any * :ref:`transport socket matches <envoy_api_field_config.cluster.v3.Cluster.transport_socket_matches>`, * the cluster's :ref:`transport socket <envoy_api_field_config.cluster.v3.Cluster.transport_socket>` * will be used for health check socket configuration. */ 'transport_socket_match_criteria'?: (_google_protobuf_Struct | null); /** * The "no traffic healthy interval" is a special health check interval that * is used for hosts that are currently passing active health checking * (including new hosts) when the cluster has received no traffic. * * This is useful for when we want to send frequent health checks with * `no_traffic_interval` but then revert to lower frequency `no_traffic_healthy_interval` once * a host in the cluster is marked as healthy. * * Once a cluster has been used for traffic routing, Envoy will shift back to using the * standard health check interval that is defined. * * If no_traffic_healthy_interval is not set, it will default to the * no traffic interval and send that interval regardless of health state. */ 'no_traffic_healthy_interval'?: (_google_protobuf_Duration | null); 'health_checker'?: "http_health_check"|"tcp_health_check"|"grpc_health_check"|"custom_health_check"; } /** * [#next-free-field: 25] */ export interface HealthCheck__Output { /** * The time to wait for a health check response. If the timeout is reached the * health check attempt will be considered a failure. */ 'timeout': (_google_protobuf_Duration__Output | null); /** * The interval between health checks. */ 'interval': (_google_protobuf_Duration__Output | null); /** * An optional jitter amount in milliseconds. If specified, during every * interval Envoy will add interval_jitter to the wait time. */ 'interval_jitter': (_google_protobuf_Duration__Output | null); /** * The number of unhealthy health checks required before a host is marked * unhealthy. Note that for *http* health checking if a host responds with 503 * this threshold is ignored and the host is considered unhealthy immediately. */ 'unhealthy_threshold': (_google_protobuf_UInt32Value__Output | null); /** * The number of healthy health checks required before a host is marked * healthy. Note that during startup, only a single successful health check is * required to mark a host healthy. */ 'healthy_threshold': (_google_protobuf_UInt32Value__Output | null); /** * [#not-implemented-hide:] Non-serving port for health checking. */ 'alt_port': (_google_protobuf_UInt32Value__Output | null); /** * Reuse health check connection between health checks. Default is true. */ 'reuse_connection': (_google_protobuf_BoolValue__Output | null); /** * HTTP health check. */ 'http_health_check'?: (_envoy_config_core_v3_HealthCheck_HttpHealthCheck__Output | null); /** * TCP health check. */ 'tcp_health_check'?: (_envoy_config_core_v3_HealthCheck_TcpHealthCheck__Output | null); /** * gRPC health check. */ 'grpc_health_check'?: (_envoy_config_core_v3_HealthCheck_GrpcHealthCheck__Output | null); /** * The "no traffic interval" is a special health check interval that is used when a cluster has * never had traffic routed to it. This lower interval allows cluster information to be kept up to * date, without sending a potentially large amount of active health checking traffic for no * reason. Once a cluster has been used for traffic routing, Envoy will shift back to using the * standard health check interval that is defined. Note that this interval takes precedence over * any other. * * The default value for "no traffic interval" is 60 seconds. */ 'no_traffic_interval': (_google_protobuf_Duration__Output | null); /** * Custom health check. */ 'custom_health_check'?: (_envoy_config_core_v3_HealthCheck_CustomHealthCheck__Output | null); /** * The "unhealthy interval" is a health check interval that is used for hosts that are marked as * unhealthy. As soon as the host is marked as healthy, Envoy will shift back to using the * standard health check interval that is defined. * * The default value for "unhealthy interval" is the same as "interval". */ 'unhealthy_interval': (_google_protobuf_Duration__Output | null); /** * The "unhealthy edge interval" is a special health check interval that is used for the first * health check right after a host is marked as unhealthy. For subsequent health checks * Envoy will shift back to using either "unhealthy interval" if present or the standard health * check interval that is defined. * * The default value for "unhealthy edge interval" is the same as "unhealthy interval". */ 'unhealthy_edge_interval': (_google_protobuf_Duration__Output | null); /** * The "healthy edge interval" is a special health check interval that is used for the first * health check right after a host is marked as healthy. For subsequent health checks * Envoy will shift back to using the standard health check interval that is defined. * * The default value for "healthy edge interval" is the same as the default interval. */ 'healthy_edge_interval': (_google_protobuf_Duration__Output | null); /** * Specifies the path to the :ref:`health check event log <arch_overview_health_check_logging>`. * If empty, no event log will be written. */ 'event_log_path': (string); /** * An optional jitter amount as a percentage of interval_ms. If specified, * during every interval Envoy will add interval_ms * * interval_jitter_percent / 100 to the wait time. * * If interval_jitter_ms and interval_jitter_percent are both set, both of * them will be used to increase the wait time. */ 'interval_jitter_percent': (number); /** * If set to true, health check failure events will always be logged. If set to false, only the * initial health check failure event will be logged. * The default value is false. */ 'always_log_health_check_failures': (boolean); /** * An optional jitter amount in milliseconds. If specified, Envoy will start health * checking after for a random time in ms between 0 and initial_jitter. This only * applies to the first health check. */ 'initial_jitter': (_google_protobuf_Duration__Output | null); /** * This allows overriding the cluster TLS settings, just for health check connections. */ 'tls_options': (_envoy_config_core_v3_HealthCheck_TlsOptions__Output | null); /** * [#not-implemented-hide:] * The gRPC service for the health check event service. * If empty, health check events won't be sent to a remote endpoint. */ 'event_service': (_envoy_config_core_v3_EventServiceConfig__Output | null); /** * Optional key/value pairs that will be used to match a transport socket from those specified in the cluster's * :ref:`tranport socket matches <envoy_api_field_config.cluster.v3.Cluster.transport_socket_matches>`. * For example, the following match criteria * * .. code-block:: yaml * * transport_socket_match_criteria: * useMTLS: true * * Will match the following :ref:`cluster socket match <envoy_api_msg_config.cluster.v3.Cluster.TransportSocketMatch>` * * .. code-block:: yaml * * transport_socket_matches: * - name: "useMTLS" * match: * useMTLS: true * transport_socket: * name: envoy.transport_sockets.tls * config: { ... } # tls socket configuration * * If this field is set, then for health checks it will supersede an entry of *envoy.transport_socket* in the * :ref:`LbEndpoint.Metadata <envoy_api_field_config.endpoint.v3.LbEndpoint.metadata>`. * This allows using different transport socket capabilities for health checking versus proxying to the * endpoint. * * If the key/values pairs specified do not match any * :ref:`transport socket matches <envoy_api_field_config.cluster.v3.Cluster.transport_socket_matches>`, * the cluster's :ref:`transport socket <envoy_api_field_config.cluster.v3.Cluster.transport_socket>` * will be used for health check socket configuration. */ 'transport_socket_match_criteria': (_google_protobuf_Struct__Output | null); /** * The "no traffic healthy interval" is a special health check interval that * is used for hosts that are currently passing active health checking * (including new hosts) when the cluster has received no traffic. * * This is useful for when we want to send frequent health checks with * `no_traffic_interval` but then revert to lower frequency `no_traffic_healthy_interval` once * a host in the cluster is marked as healthy. * * Once a cluster has been used for traffic routing, Envoy will shift back to using the * standard health check interval that is defined. * * If no_traffic_healthy_interval is not set, it will default to the * no traffic interval and send that interval regardless of health state. */ 'no_traffic_healthy_interval': (_google_protobuf_Duration__Output | null); 'health_checker': "http_health_check"|"tcp_health_check"|"grpc_health_check"|"custom_health_check"; }
the_stack
import React from "react"; import shortid from "shortid"; import { cloneDeep, pick } from "lodash"; import { GET_FORM, GetFormQueryResponse, GetFormQueryVariables, UPDATE_REVISION, UpdateFormRevisionMutationResponse, UpdateFormRevisionMutationVariables } from "./graphql"; import { getFieldPosition, moveField, moveRow, deleteField } from "./functions"; import { plugins } from "@webiny/plugins"; import { FbFormModelField, FieldIdType, FieldLayoutPositionType, FbBuilderFieldPlugin, FbFormModel, FbUpdateFormInput, FbErrorResponse } from "~/types"; import { ApolloClient } from "apollo-client"; import { FormEditorFieldError, FormEditorProviderContext, FormEditorProviderContextState } from "~/admin/components/FormEditor/Context/index"; import dotProp from "dot-prop-immutable"; import { useSnackbar } from "@webiny/app-admin"; interface SetDataCallable { (value: FbFormModel): FbFormModel; } interface MoveFieldParams { field: FieldIdType | FbFormModelField; position: FieldLayoutPositionType; } type State = FormEditorProviderContextState; export interface FormEditor { apollo: ApolloClient<any>; data: FbFormModel; errors: FormEditorFieldError[] | null; state: State; getForm: (id: string) => Promise<{ data: GetFormQueryResponse }>; saveForm: ( data: FbFormModel | null ) => Promise<{ data: FbFormModel | null; error: FbErrorResponse | null }>; setData: (setter: SetDataCallable, saveForm?: boolean) => Promise<void>; getFields: () => FbFormModelField[]; getLayoutFields: () => FbFormModelField[][]; getField: (query: Partial<Record<keyof FbFormModelField, string>>) => FbFormModelField | null; getFieldPlugin: ( query: Partial<Record<keyof FbBuilderFieldPlugin["field"], string>> ) => FbBuilderFieldPlugin | null; insertField: (field: FbFormModelField, position: FieldLayoutPositionType) => void; moveField: (params: MoveFieldParams) => void; moveRow: (source: number, destination: number) => void; updateField: (field: FbFormModelField) => void; deleteField: (field: FbFormModelField) => void; getFieldPosition: (field: FieldIdType | FbFormModelField) => FieldLayoutPositionType | null; } const extractFieldErrors = (error: FbErrorResponse, form: FbFormModel): FormEditorFieldError[] => { const invalidFields: any[] = dotProp.get(error, "data.invalidFields.fields.data", []); if (Array.isArray(invalidFields) === false) { return []; } const results: Record<string, FormEditorFieldError> = {}; for (const invalidField of invalidFields) { if (!invalidField.data || !invalidField.data.invalidFields) { continue; } const index = invalidField.data.index; if (index === undefined) { console.log("Could not determine field index from given error."); console.log(invalidField.data); continue; } const field = form.fields[index]; if (!field) { console.log(`Could not get field by index ${index}. There is an error in it.`); continue; } const er = invalidField.data.invalidFields; if (!results[field.fieldId]) { results[field.fieldId] = { fieldId: field.fieldId, label: field.label || field.fieldId, index, errors: {} }; } results[field.fieldId].errors = Object.keys(er).reduce((collection, key) => { collection[key] = er[key].message || "unknown error"; return collection; }, results[field.fieldId].errors); } return Object.values(results); }; export const useFormEditorFactory = ( FormEditorContext: React.Context<FormEditorProviderContext> ) => { return () => { const context = React.useContext<FormEditorProviderContext>(FormEditorContext); if (!context) { throw new Error("useFormEditor must be used within a FormEditorProvider"); } const { showSnackbar } = useSnackbar(); const { state, dispatch } = context; const self: FormEditor = { apollo: state.apollo, data: state.data || ({} as FbFormModel), errors: state.errors, state, async getForm(id) { const response = await self.apollo.query< GetFormQueryResponse, GetFormQueryVariables >({ query: GET_FORM, variables: { revision: decodeURIComponent(id) } }); const { data, error } = response?.data?.formBuilder?.getForm || {}; if (error) { throw new Error(error.message); } self.setData(() => { const form = cloneDeep(data) as FbFormModel; if (!form.settings.layout.renderer) { form.settings.layout.renderer = state.defaultLayoutRenderer; } return form; }, false); return response; }, saveForm: async data => { data = data || state.data; if (!data) { return { data: null, error: { message: "Missing form data to be saved." } }; } const response = await self.apollo.mutate< UpdateFormRevisionMutationResponse, UpdateFormRevisionMutationVariables >({ mutation: UPDATE_REVISION, variables: { revision: decodeURIComponent(data.id), /** * We can safely cast as FbFormModel is FbUpdateFormInput after all, but with some optional values. */ data: pick(data as FbUpdateFormInput, [ "layout", "fields", "name", "settings", "triggers" ]) } }); const values = dotProp.get(response, "data.formBuilder.updateRevision", {}); const { data: responseData, error: responseError } = values || {}; return { data: responseData || null, error: responseError || null }; }, /** * Set form data by providing a callback, which receives a fresh copy of data on which you can work on. * Return new data once finished. */ setData: async (setter, saveForm = true) => { const data = setter(cloneDeep(self.data)); dispatch({ type: "data", data }); if (!saveForm) { return; } const { error } = await self.saveForm(data); if (!error) { return; } const errors = extractFieldErrors(error, data); if (Object.keys(errors).length === 0) { showSnackbar( "Unspecified Form Builder error. Please check the console for more details." ); console.log(error); return; } dispatch({ type: "errors", errors }); showSnackbar(<h6>Error while saving form!</h6>); }, /** * Returns fields list. */ getFields() { if (!state.data) { return []; } return state.data.fields; }, /** * Returns complete layout with fields data in it (not just field IDs) */ getLayoutFields: () => { // Replace every field ID with actual field object. return state.data.layout.map(row => { return row .map(id => { return self.getField({ _id: id }); }) .filter(Boolean) as FbFormModelField[]; }); }, /** * Return field plugin. */ getFieldPlugin(query) { return ( plugins .byType<FbBuilderFieldPlugin>("form-editor-field-type") .find(({ field }) => { for (const key in query) { if (!(key in field)) { return false; } const fieldKeyValue = field[key as keyof FbBuilderFieldPlugin["field"]]; const queryKeyValue = query[key as keyof FbBuilderFieldPlugin["field"]]; if (fieldKeyValue !== queryKeyValue) { return false; } } return true; }) || null ); }, /** * Checks if field of given type already exists in the list of fields. */ getField(query) { return ( state.data.fields.find(field => { for (const key in query) { if (!(key in field)) { return false; } const fieldKeyValue = field[key as keyof FbFormModelField]; const queryKeyValue = query[key as keyof FbFormModelField]; if (fieldKeyValue !== queryKeyValue) { return false; } } return true; }) || null ); }, /** * Inserts a new field into the target position. */ insertField: (data, position) => { const field = cloneDeep(data); if (!field._id) { field._id = shortid.generate(); } if (!data.name) { throw new Error(`Field "name" missing.`); } const fieldPlugin = self.getFieldPlugin({ name: data.name }); if (!fieldPlugin) { throw new Error(`Invalid field "name".`); } data.type = fieldPlugin.field.type; self.setData(data => { if (!Array.isArray(data.fields)) { data.fields = []; } data.fields.push(field); moveField({ field, position, data }); // We are dropping a new field at the specified index. return data; }); }, /** * Moves field to the given target position. */ moveField: ({ field, position }) => { self.setData(data => { moveField({ field, position, data }); return data; }); }, /** * Moves row to a destination row. */ moveRow: (source, destination) => { self.setData(data => { moveRow({ data, source, destination }); return data; }); }, /** * Updates field. */ updateField: fieldData => { const field = cloneDeep(fieldData); self.setData(data => { for (let i = 0; i < data.fields.length; i++) { if (data.fields[i]._id === field._id) { data.fields[i] = field; break; } } return data; }); }, /** * Deletes a field (both from the list of field and the layout). */ deleteField: field => { self.setData(data => { deleteField({ field, data }); return data; }); }, /** * Returns row / index position for given field. */ getFieldPosition: field => { return getFieldPosition({ field, data: self.data }); } }; return self; }; };
the_stack
import { Constructable, FASTElement, ViewTemplate } from "@microsoft/fast-element"; import { ConfigurableRoute, Endpoint, RecognizedRoute, RouteParameterConverter, RouteRecognizer, } from "./recognizer"; import { Ignore, NavigationCommand, Redirect, Render } from "./commands"; import { Layout, Transition } from "./view"; import { RouterConfiguration } from "./configuration"; import { Router } from "./router"; import { QueryString } from "./query-string"; import { Route } from "./navigation"; /** * @internal */ export const childRouteParameter = "fast-child-route"; /** * @alpha */ export type SupportsSettings<TSettings = any> = { settings?: TSettings; }; /** * @alpha */ export type PathedRouteDefinition<TSettings = any> = SupportsSettings<TSettings> & Route; /** * @alpha */ export type IgnorableRouteDefinition<TSettings = any> = PathedRouteDefinition<TSettings>; /** * @alpha */ export type LayoutAndTransitionRouteDefinition = { layout?: Layout | ViewTemplate; transition?: Transition; }; /** * @alpha */ export type RedirectRouteDefinition<TSettings = any> = PathedRouteDefinition< TSettings > & { redirect: string; }; /** * @alpha */ export type HasTitle = { title?: string; }; /** * @alpha */ export type NavigableRouteDefinition<TSettings = any> = PathedRouteDefinition<TSettings> & LayoutAndTransitionRouteDefinition & HasTitle & { childRouters?: boolean; }; /** * @alpha */ export type FASTElementConstructor = new () => FASTElement; /** * @alpha */ export type HasElement = { element: | string | FASTElementConstructor | HTMLElement | (() => Promise<string | FASTElementConstructor | HTMLElement>); }; /** * @alpha */ export type ElementFallbackRouteDefinition< TSettings = any > = LayoutAndTransitionRouteDefinition & HasElement & SupportsSettings<TSettings> & HasTitle; /** * @alpha */ export type ElementRouteDefinition<TSettings = any> = NavigableRouteDefinition< TSettings > & HasElement; /** * @alpha */ export type HasTemplate = { template: ViewTemplate | (() => Promise<ViewTemplate>); }; /** * @alpha */ export type TemplateFallbackRouteDefinition< TSettings = any > = LayoutAndTransitionRouteDefinition & HasTemplate & SupportsSettings<TSettings> & HasTitle; /** * @alpha */ export type TemplateRouteDefinition<TSettings = any> = NavigableRouteDefinition< TSettings > & HasTemplate; /** * @alpha */ export type HasCommand = { command: NavigationCommand; }; /** * @alpha */ export type CommandRouteDefinition<TSettings = any> = PathedRouteDefinition<TSettings> & HasCommand & HasTitle; /** * @alpha */ export type CommandFallbackRouteDefinition<TSettings = any> = HasCommand & SupportsSettings<TSettings> & HasTitle; /** * @alpha */ export type FallbackRouteDefinition<TSettings = any> = | ElementFallbackRouteDefinition<TSettings> | TemplateFallbackRouteDefinition<TSettings> | Pick<RedirectRouteDefinition<TSettings>, "redirect"> | CommandFallbackRouteDefinition<TSettings>; /** * @alpha */ export type DefinitionCallback = () => | Promise<FallbackRouteDefinition> | FallbackRouteDefinition; /** * @alpha */ export type RenderableRouteDefinition<TSettings = any> = | ElementRouteDefinition<TSettings> | TemplateRouteDefinition<TSettings>; /** * @alpha */ export type MappableRouteDefinition<TSettings = any> = | RenderableRouteDefinition<TSettings> | RedirectRouteDefinition<TSettings> | CommandRouteDefinition<TSettings> | ParentRouteDefinition<TSettings>; /** * @alpha */ export type ParentRouteDefinition<TSettings = any> = PathedRouteDefinition<TSettings> & LayoutAndTransitionRouteDefinition & { children: MappableRouteDefinition<TSettings>[]; }; /** * @alpha */ export type RouteMatch<TSettings = any> = { route: RecognizedRoute<TSettings>; command: NavigationCommand; }; function getFallbackCommand( config: RouterConfiguration, definition: FallbackRouteDefinition ): NavigationCommand { if ("command" in definition) { return definition.command; } else if ("redirect" in definition) { return new Redirect(definition.redirect); } else { return Render.fromDefinition(config, definition); } } /** * @alpha */ export type ConverterObject = { convert: RouteParameterConverter; }; /** * @alpha */ export type ParameterConverter = | RouteParameterConverter | ConverterObject | Constructable<ConverterObject>; const booleanConverter = value => { if (value === void 0 || value === null) { return false; } switch (value.toLowerCase().trim()) { case "true": case "yes": case "1": return true; default: return false; } }; const defaultConverters = { number: value => (value === void 0 ? NaN : parseFloat(value)), float: value => (value === void 0 ? NaN : parseFloat(value)), int: value => (value === void 0 ? NaN : parseInt(value)), integer: value => (value === void 0 ? NaN : parseInt(value)), Date: value => (value === void 0 ? new Date(Date.now()) : new Date(value)), boolean: booleanConverter, bool: booleanConverter, }; /** * @alpha */ export class RouteCollection<TSettings = any> { private _recognizer: RouteRecognizer<TSettings> | null = null; private pathToCommand = new Map<string, NavigationCommand>(); private fallbackCommand: NavigationCommand | null = null; private fallbackSettings: TSettings | null = null; private converters: Record<string, RouteParameterConverter> = {}; public constructor(private owner: RouterConfiguration) {} private get recognizer() { if (this._recognizer === null) { this._recognizer = this.owner.createRouteRecognizer(); } return this._recognizer; } public ignore(definitionOrString: IgnorableRouteDefinition<TSettings> | string) { if (typeof definitionOrString === "string") { definitionOrString = { path: definitionOrString }; } this.pathToCommand.set(definitionOrString.path, new Ignore()); this.recognizer.add(definitionOrString, definitionOrString.settings); } public map(...routes: MappableRouteDefinition<TSettings>[]) { for (const route of routes) { if ("children" in route) { const titleBuilder = this.owner.createTitleBuilder(); const childRoutes = route.children.map(x => { const childRoute = { ...route, ...x, path: `${route.path}/${x.path}`, }; if ("title" in route || "title" in x) { const parentTitle = (route as HasTitle).title || ""; const childTitle = (x as HasTitle).title || ""; (childRoute as HasTitle).title = titleBuilder.joinTitles( parentTitle, childTitle ); } if ("name" in x) { const parentName = route.name ? route.name + "/" : ""; childRoute.name = parentName + x.name; } if (childRoute.children === route.children) { delete (childRoute as any).children; } return childRoute; }); this.map(...childRoutes); continue; } let command: NavigationCommand; if ("command" in route) { command = route.command; } else if ("redirect" in route) { command = new Redirect(route.redirect); } else { command = Render.fromDefinition(this.owner, route); } this.pathToCommand.set(route.path, command); this.recognizer.add(route, route.settings); if ("childRouters" in route && route.childRouters) { const childRouterRoute = { ...route, path: route.path + `/*${childRouteParameter}`, }; this.pathToCommand.set(childRouterRoute.path, command); this.recognizer.add(childRouterRoute, childRouterRoute.settings); } } } public fallback( definitionOrCallback: FallbackRouteDefinition<TSettings> | DefinitionCallback ) { const owner = this.owner; if (typeof definitionOrCallback === "function") { this.fallbackCommand = { async createContributor(router: Router, route: RecognizedRoute) { const input = await definitionOrCallback(); const command = getFallbackCommand(owner, input); return command.createContributor(router, route); }, }; } else { this.fallbackCommand = getFallbackCommand(owner, definitionOrCallback); } } public converter(name: string, converter: ParameterConverter) { let normalizedConverter: RouteParameterConverter; if ("convert" in converter) { normalizedConverter = converter.convert.bind(converter); } else if (converter.prototype && "convert" in converter.prototype) { normalizedConverter = (value: string | undefined) => { const obj = this.owner.construct( converter as Constructable<ConverterObject> ); return obj.convert(value); }; } else { normalizedConverter = converter as RouteParameterConverter; } this.converters[name] = normalizedConverter; } public async recognize(path: string): Promise<RouteMatch<TSettings> | null> { const result = await this.recognizer.recognize(path, this.aggregateConverters()); if (result !== null) { return { route: result, command: this.pathToCommand.get(result.endpoint.path)!, }; } if (this.fallbackCommand !== null) { const separated = QueryString.separate(path); const queryParams = QueryString.parse(separated.queryString); return { route: new RecognizedRoute<TSettings>( new Endpoint<TSettings>( new ConfigurableRoute("*", "", false), [], [], this.fallbackSettings ), {}, {}, queryParams ), command: this.fallbackCommand, }; } return null; } /** * Generate a path and query string from a route name and params object. * * @param name - The name of the route to generate from. * @param params - The route params to use when populating the pattern. * Properties not required by the pattern will be appended to the query string. * @returns The generated absolute path and query string. */ public generateFromName(name: string, params: object): string | null { return this.recognizer.generateFromName(name, params); } /** * Generate a path and query string from a route path and params object. * * @param path - The path of the route to generate from. * @param params - The route params to use when populating the pattern. * Properties not required by the pattern will be appended to the query string. * @returns The generated absolute path and query string. */ public generateFromPath(path: string, params: object): string | null { return this.recognizer.generateFromPath(path, params); } private aggregateConverters() { if (this.owner.parent === null) { return { ...defaultConverters, ...this.converters, }; } return { ...this.owner.parent.routes.aggregateConverters(), ...this.converters, }; } }
the_stack
"use strict"; interface Window { quest: any; } var quest = window.quest || {}; function Left(input: string, length: number): string { return input.substring(0, length); } function Right(input: string, length: number): string { return input.substring(input.length - length); } function Mid(input: string, start: number, length?: number): string { if (typeof length === 'undefined') { return input.substr(start - 1); } return input.substr(start - 1, length); } function UCase(input: string): string { return input.toUpperCase(); } function LCase(input: string): string { return input.toLowerCase(); } function InStr(input: string, search: string): number { return input.indexOf(search) + 1; } function InStrFrom(start: number, input: string, search: string): number { return input.indexOf(search, start - 1) + 1; } function InStrRev(input: string, search: string): number { return input.lastIndexOf(search) + 1; } function Split(input: string, splitChar: string): string[] { return input.split(splitChar); } function IsNumeric(input: any): boolean { return !isNaN(parseFloat(input)) && isFinite(input); } function Trim(input: string): string { return input.trim(); } function LTrim(input: string): string { return input.replace(/^\s+/,""); } function Asc(input: string): number { return input.charCodeAt(0); } var windows1252mapping = ['\u20AC','','\u201A','\u0192','\u201E','\u2026', '\u2020','\u2021','\u02C6','\u2030','\u0160','\u2039','\u0152','', '\u017D','','','\u2018','\u2019','\u201C','\u201D','\u2022','\u2013', '\u2014','\u02DC','\u2122','\u0161','\u203A','\u0153','','\u017E', '\u0178']; function Chr(input: number): string { if (input < 128 || input > 159) { return String.fromCharCode(input); } return windows1252mapping[input - 128]; } function Len(input: string): number { if (input === null || input === undefined) return 0; return input.length; } function UBound(array: any[]): number { return array.length - 1; } function Str(input: number): string { return input.toString(); } function Val(input: string): number { return parseInt(input); } interface StringDictionary { [index: string]: string; } class MenuData { Caption: string; Options: StringDictionary; AllowCancel: boolean; constructor(caption: string, options: StringDictionary, allowCancel: boolean) { this.Caption = caption; this.Options = options; this.AllowCancel = allowCancel; } } class Player { TextFormatter: TextFormatter; ResourceRoot: string; constructor(textFormatter: TextFormatter) { this.TextFormatter = textFormatter; } SetResourceRoot(resourceRoot: string) { this.ResourceRoot = resourceRoot; } ShowMenu(menuData: MenuData) { quest.ui.showMenu(menuData.Caption, menuData.Options, menuData.AllowCancel); } DoWait() { quest.ui.beginWait(); } ShowQuestion(caption: string) { quest.ui.showQuestion(caption); } PlaySound(filename: string, synchronous: boolean, looped: boolean) { quest.ui.playSound(this.ResourceRoot + filename, synchronous, looped); } StopSound() { quest.ui.stopSound; } ClearScreen() { quest.ui.clearScreen(); } SetBackground(colour: string) { quest.ui.setBackground(colour); } SetForeground(colour: string) { this.TextFormatter.foreground = colour; } SetFont(fontName: string) { this.TextFormatter.fontFamily = fontName; } SetFontSize(fontSize: number) { this.TextFormatter.defaultFontSize = fontSize; } SetPanelContents(html: string) { quest.ui.setPanelContents(html); } SetPanesVisible(data: string) { quest.ui.panesVisible(data == "on"); } ShowPicture(filename: string) { var url = this.ResourceRoot + filename; var html = `<img src="${url}" onload="scrollToEnd();" /><br />` quest.print(html); } GetURL(file: string) { return this.ResourceRoot + file; } LocationUpdated(location: string) { quest.ui.locationUpdated(location); } GetNewGameFile(originalFilename: string, extensions: string) { } RequestSave(html: string) { } UpdateGameName(name: string) { if (name.length == 0) name = "Untitled Game"; quest.ui.setGameName(name); } Show(element: string) { quest.ui.show(element); } SetStatusText(text: string) { quest.ui.updateStatus(text.replace("\n", "<br />")); } UpdateInventoryList(items: ListData[]) { quest.ui.updateList("inventory", items); } UpdateObjectsList(items: ListData[]) { quest.ui.updateList("placesobjects", items); } UpdateExitsList(items: ListData[]) { quest.ui.updateCompass(items); } RequestNextTimerTick(seconds: number) { quest.ui.requestNextTimerTick(seconds); } } class ListData { Text: string; Verbs: string[]; ElementId: string; ElementName: string; constructor(text: string, verbs: string[]) { this.Text = text; this.Verbs = verbs; this.ElementId = text; this.ElementName = text; } } enum ListType {InventoryList, ExitsList, ObjectsList}; interface Callback { (): void; } interface BooleanCallback { (data: boolean): void; } interface StringCallback { (data: string): void; } interface FileFetcherCallback { (data: string): void; } interface FileFetcher { (filename: string, onSuccess: FileFetcherCallback, onFailure: FileFetcherCallback): void; } interface BinaryFileFetcherCallback { (data: Uint8Array): void; } interface BinaryFileFetcher { (filename: string, onSuccess: BinaryFileFetcherCallback, onFailure: FileFetcherCallback): void; } enum State {Ready, Working, Waiting, Finished}; class DefineBlock { StartLine: number = 0; EndLine: number = 0; } class Context { CallingObjectId: number = 0; NumParameters: number = 0; Parameters: string[]; FunctionReturnValue: string = ""; AllowRealNamesInCommand: boolean = false; DontProcessCommand: boolean = false; CancelExec: boolean = false; StackCounter: number = 0; } enum LogType {Misc, FatalError, WarningError, Init, LibraryWarningError, Warning, UserError, InternalError}; enum Direction {None = -1, Out = 0, North = 1, South = 2, East = 3, West = 4, NorthWest = 5, NorthEast = 6, SouthWest = 7, SouthEast = 8, Up = 9, Down = 10}; class ItemType { Name: string = ""; Got: boolean = false; } class Collectable { Name: string = ""; Type: string = ""; Value: number = 0; Display: string = ""; DisplayWhenZero: boolean = false; } class PropertyType { PropertyName: string = ""; PropertyValue: string = ""; } class ActionType { ActionName: string = ""; Script: string = ""; } class UseDataType { UseObject: string = ""; UseType: UseType; UseScript: string = ""; } class GiveDataType { GiveObject: string = ""; GiveType: GiveType; GiveScript: string = ""; } class PropertiesActions { Properties: string = ""; NumberActions: number = 0; Actions: ActionType[]; NumberTypesIncluded: number = 0; TypesIncluded: string[]; } class VariableType { VariableName: string = ""; VariableContents: string[]; VariableUBound: number = 0; DisplayString: string = ""; OnChangeScript: string = ""; NoZeroDisplay: boolean = false; } class SynonymType { OriginalWord: string = ""; ConvertTo: string = ""; } class TimerType { TimerName: string = ""; TimerInterval: number = 0; TimerActive: boolean = false; TimerAction: string = ""; TimerTicks: number = 0; BypassThisTurn: boolean = false; } class UserDefinedCommandType { CommandText: string = ""; CommandScript: string = ""; } class TextAction { Data: string = ""; Type: TextActionType; } enum TextActionType {Text, Script, Nothing, Default}; class ScriptText { Text: string = ""; Script: string = ""; } class PlaceType { PlaceName: string = ""; Prefix: string = ""; PlaceAlias: string = ""; Script: string = ""; } class RoomType { RoomName: string = ""; RoomAlias: string = ""; Commands: UserDefinedCommandType[]; NumberCommands: number = 0; Description: TextAction = new TextAction(); Out: ScriptText = new ScriptText(); East: TextAction = new TextAction(); West: TextAction = new TextAction(); North: TextAction = new TextAction(); South: TextAction = new TextAction(); NorthEast: TextAction = new TextAction(); NorthWest: TextAction = new TextAction(); SouthEast: TextAction = new TextAction(); SouthWest: TextAction = new TextAction(); Up: TextAction = new TextAction(); Down: TextAction = new TextAction(); InDescription: string = ""; Look: string = ""; Places: PlaceType[]; NumberPlaces: number = 0; Prefix: string = ""; Script: string = ""; Use: ScriptText[]; NumberUse: number = 0; ObjId: number = 0; BeforeTurnScript: string = ""; AfterTurnScript: string = ""; Exits: RoomExits; } class ObjectType { ObjectName: string = ""; ObjectAlias: string = ""; Detail: string = ""; ContainerRoom: string = ""; Exists: boolean = false; IsGlobal: boolean = false; Prefix: string = ""; Suffix: string = ""; Gender: string = ""; Article: string = ""; DefinitionSectionStart: number = 0; DefinitionSectionEnd: number = 0; Visible: boolean = false; GainScript: string = ""; LoseScript: string = ""; NumberProperties: number = 0; Properties: PropertyType[]; Speak: TextAction = new TextAction(); Take: TextAction = new TextAction(); IsRoom: boolean = false; IsExit: boolean = false; CorresRoom: string = ""; CorresRoomId: number = 0; Loaded: boolean = false; NumberActions: number = 0; Actions: ActionType[]; NumberUseData: number = 0; UseData: UseDataType[]; UseAnything: string = ""; UseOnAnything: string = ""; Use: string = ""; NumberGiveData: number = 0; GiveData: GiveDataType[]; GiveAnything: string = ""; GiveToAnything: string = ""; DisplayType: string = ""; NumberTypesIncluded: number = 0; TypesIncluded: string[]; NumberAltNames: number = 0; AltNames: string[]; AddScript: TextAction = new TextAction(); RemoveScript: TextAction = new TextAction(); OpenScript: TextAction = new TextAction(); CloseScript: TextAction = new TextAction(); } class ChangeType { AppliesTo: string = ""; Change: string = ""; } class GameChangeDataType { NumberChanges: number = 0; ChangeData: ChangeType[]; } class ResourceType { ResourceName: string = ""; ResourceStart: number = 0; ResourceLength: number = 0; Extracted: boolean = false; } class ExpressionResult { Result: string = ""; Success: ExpressionSuccess; Message: string = ""; } class GetAvailableDirectionsResult { Description: string = ""; List: string = ""; } enum PlayerError {BadCommand, BadGo, BadGive, BadCharacter, NoItem, ItemUnwanted, BadLook, BadThing, DefaultLook, DefaultSpeak, BadItem, DefaultTake, BadUse, DefaultUse, DefaultOut, BadPlace, BadExamine, DefaultExamine, BadTake, CantDrop, DefaultDrop, BadDrop, BadPronoun, AlreadyOpen, AlreadyClosed, CantOpen, CantClose, DefaultOpen, DefaultClose, BadPut, CantPut, DefaultPut, CantRemove, AlreadyPut, DefaultRemove, Locked, DefaultWait, AlreadyTaken}; enum ItType {Inanimate, Male, Female}; enum SetResult {Error, Found, Unfound}; enum Thing {Character, Object, Room}; enum ConvertType {Strings, Functions, Numeric, Collectables}; enum UseType {UseOnSomething, UseSomethingOn}; enum GiveType {GiveToSomething, GiveSomethingTo}; enum VarType {String, Numeric}; enum StopType {Win, Lose, Null}; enum ExpressionSuccess {OK, Fail}; class InitGameData { Data: number[]; SourceFile: string; } class ArrayResult { Name: string; Index: number = 0; } class PlayerCanAccessObjectResult { CanAccessObject: boolean = false; ErrorMsg: string; } enum AppliesTo {Object, Room}; interface DefineBlockParams { [index: string]: StringDictionary; } interface ListVerbs { [index: number]: string[]; } class LegacyGame { CopyContext(ctx: Context): Context { var result: Context = new Context(); result.CallingObjectId = ctx.CallingObjectId; result.NumParameters = ctx.NumParameters; result.Parameters = ctx.Parameters; result.FunctionReturnValue = ctx.FunctionReturnValue; result.AllowRealNamesInCommand = ctx.AllowRealNamesInCommand; result.DontProcessCommand = ctx.DontProcessCommand; result.CancelExec = ctx.CancelExec; result.StackCounter = ctx.StackCounter; return result; } _defineBlockParams: DefineBlockParams; _openErrorReport: string = ""; _casKeywords: string[] = []; //Tokenised CAS keywords _lines: string[]; //Stores the lines of the ASL script/definitions _defineBlocks: DefineBlock[]; //Stores the start and end lines of each 'define' section _numberSections: number = 0; //Number of define sections _gameName: string = ""; //The name of the game _nullContext: Context = new Context(); _changeLogRooms: ChangeLog; _changeLogObjects: ChangeLog; _defaultProperties: PropertiesActions; _defaultRoomProperties: PropertiesActions; _rooms: RoomType[]; _numberRooms: number = 0; _numericVariable: VariableType[]; _numberNumericVariables: number = 0; _stringVariable: VariableType[]; _numberStringVariables: number = 0; _synonyms: SynonymType[]; _numberSynonyms: number = 0; _items: ItemType[]; _chars: ObjectType[]; _objs: ObjectType[]; _numberChars: number = 0; _numberObjs: number = 0; _numberItems: number = 0; _currentRoom: string = ""; _collectables: Collectable[]; _numCollectables: number = 0; _gameFileName: string = ""; _defaultFontName: string = ""; _defaultFontSize: number = 0; _autoIntro: boolean = false; _commandOverrideModeOn: boolean = false; _commandOverrideResolve: Callback; _commandOverrideVariable: string = ""; _waitResolve: Callback; _askResolve: BooleanCallback; _menuResolve: StringCallback; _afterTurnScript: string = ""; _beforeTurnScript: string = ""; _outPutOn: boolean = false; _gameAslVersion: number = 0; _choiceNumber: number = 0; _gameLoadMethod: string = ""; _timers: TimerType[]; _numberTimers: number = 0; _numDisplayStrings: number = 0; _numDisplayNumerics: number = 0; _gameFullyLoaded: boolean = false; _gameChangeData: GameChangeDataType = new GameChangeDataType(); _lastIt: number = 0; _lastItMode: ItType; _thisTurnIt: number = 0; _thisTurnItMode: ItType; _badCmdBefore: string = ""; _badCmdAfter: string = ""; _numResources: number = 0; _resources: ResourceType[]; _resourceFile: string = ""; _resourceOffset: number = 0; _startCatPos: number = 0; _useAbbreviations: boolean = false; _loadedFromQsg: boolean = false; _beforeSaveScript: string = ""; _onLoadScript: string = ""; _skipCheckFile = ["bargain.cas", "easymoney.asl", "musicvf1.cas"]; _compassExits: ListData[] = []; _gotoExits: ListData[] = []; _textFormatter: TextFormatter = new TextFormatter(); _casFileData: Uint8Array; _commandLock: Object = new Object(); _stateLock: Object = new Object(); _state: State = State.Ready; _waitLock: Object = new Object(); _readyForCommand: boolean = true; _gameLoading: boolean = false; _playerErrorMessageString: string[] = []; _listVerbs: ListVerbs = {}; _filename: string = ""; _originalFilename: string = ""; _data: string; _player: Player = new Player(this._textFormatter); _gameFinished: boolean = false; _gameIsRestoring: boolean = false; _useStaticFrameForPictures: boolean = false; _fileData: string = ""; _fileDataPos: number = 0; _questionResponse: boolean = false; _fileFetcher: FileFetcher; _binaryFileFetcher: BinaryFileFetcher; constructor(filename: string, originalFilename: string, data: string, fileFetcher: FileFetcher, binaryFileFetcher: BinaryFileFetcher, resourceRoot: string) { this.LoadCASKeywords(); this._gameLoadMethod = "normal"; this._filename = filename; this._originalFilename = originalFilename; this._data = data; this._fileFetcher = fileFetcher; this._binaryFileFetcher = binaryFileFetcher; this._player.SetResourceRoot(resourceRoot); } RemoveFormatting(s: string): string { var code: string; var pos: number = 0; var len: number = 0; do { pos = InStr(s, "|"); if (pos != 0) { code = Mid(s, pos + 1, 3); if (Left(code, 1) == "b") { len = 1; } else if (Left(code, 2) == "xb") { len = 2; } else if (Left(code, 1) == "u") { len = 1; } else if (Left(code, 2) == "xu") { len = 2; } else if (Left(code, 1) == "i") { len = 1; } else if (Left(code, 2) == "xi") { len = 2; } else if (Left(code, 2) == "cr") { len = 2; } else if (Left(code, 2) == "cb") { len = 2; } else if (Left(code, 2) == "cl") { len = 2; } else if (Left(code, 2) == "cy") { len = 2; } else if (Left(code, 2) == "cg") { len = 2; } else if (Left(code, 1) == "n") { len = 1; } else if (Left(code, 2) == "xn") { len = 2; } else if (Left(code, 1) == "s") { len = 3; } else if (Left(code, 2) == "jc") { len = 2; } else if (Left(code, 2) == "jl") { len = 2; } else if (Left(code, 2) == "jr") { len = 2; } else if (Left(code, 1) == "w") { len = 1; } else if (Left(code, 1) == "c") { len = 1; } if (len == 0) { // unknown code len = 1; } s = Left(s, pos - 1) + Mid(s, pos + len + 1); } } while (!(pos == 0)); return s; } CheckSections(): boolean { var defines: number = 0; var braces: number = 0; var checkLine: string = ""; var bracePos: number = 0; var pos: number = 0; var section: string = ""; var hasErrors: boolean = false; var skipBlock: boolean = false; this._openErrorReport = ""; hasErrors = false; defines = 0; braces = 0; for (var i = 1; i <= UBound(this._lines); i++) { if (!this.BeginsWith(this._lines[i], "#!qdk-note: ")) { if (this.BeginsWith(this._lines[i], "define ")) { section = this._lines[i]; braces = 0; defines = defines + 1; skipBlock = this.BeginsWith(this._lines[i], "define text") || this.BeginsWith(this._lines[i], "define synonyms"); } else if (Trim(this._lines[i]) == "end define") { defines = defines - 1; if (defines < 0) { this.LogASLError("Extra 'end define' after block '" + section + "'", LogType.FatalError); this._openErrorReport = this._openErrorReport + "Extra 'end define' after block '" + section + "'\n"; hasErrors = true; defines = 0; } if (braces > 0) { this.LogASLError("Missing } in block '" + section + "'", LogType.FatalError); this._openErrorReport = this._openErrorReport + "Missing } in block '" + section + "'\n"; hasErrors = true; } else if (braces < 0) { this.LogASLError("Too many } in block '" + section + "'", LogType.FatalError); this._openErrorReport = this._openErrorReport + "Too many } in block '" + section + "'\n"; hasErrors = true; } } if (Left(this._lines[i], 1) != "'" && !skipBlock) { checkLine = this.ObliterateParameters(this._lines[i]); if (this.BeginsWith(checkLine, "'<ERROR;")) { // ObliterateParameters denotes a mismatched $, ( etc. // by prefixing line with '<ERROR;*; where * is the mismatched // character this.LogASLError("Expected closing " + Mid(checkLine, 9, 1) + " character in '" + this.ReportErrorLine(this._lines[i]) + "'", LogType.FatalError); this._openErrorReport = this._openErrorReport + "Expected closing " + Mid(checkLine, 9, 1) + " character in '" + this.ReportErrorLine(this._lines[i]) + "'.\n"; return false; } } if (Left(Trim(checkLine), 1) != "'") { // Now check { pos = 1; do { bracePos = InStrFrom(pos, checkLine, "{"); if (bracePos != 0) { pos = bracePos + 1; braces = braces + 1; } } while (!(bracePos == 0 || pos > Len(checkLine))); // Now check } pos = 1; do { bracePos = InStrFrom(pos, checkLine, "}"); if (bracePos != 0) { pos = bracePos + 1; braces = braces - 1; } } while (!(bracePos == 0 || pos > Len(checkLine))); } } } if (defines > 0) { this.LogASLError("Missing 'end define'", LogType.FatalError); this._openErrorReport = this._openErrorReport + "Missing 'end define'.\n"; hasErrors = true; } return !hasErrors; } ConvertFriendlyIfs(): boolean { // Converts // if (%something% < 3) then ... // to // if is <%something%;lt;3> then ... // and also repeat until ... // Returns False if successful var convPos: number = 0; var symbPos: number = 0; var symbol: string; var endParamPos: number = 0; var paramData: string; var startParamPos: number = 0; var firstData: string; var secondData: string; var obscureLine: string; var newParam: string; var varObscureLine: string; var bracketCount: number = 0; for (var i = 1; i <= UBound(this._lines); i++) { obscureLine = this.ObliterateParameters(this._lines[i]); convPos = InStr(obscureLine, "if ("); if (convPos == 0) { convPos = InStr(obscureLine, "until ("); } if (convPos == 0) { convPos = InStr(obscureLine, "while ("); } if (convPos == 0) { convPos = InStr(obscureLine, "not ("); } if (convPos == 0) { convPos = InStr(obscureLine, "and ("); } if (convPos == 0) { convPos = InStr(obscureLine, "or ("); } if (convPos != 0) { varObscureLine = this.ObliterateVariableNames(this._lines[i]); if (this.BeginsWith(varObscureLine, "'<ERROR;")) { // ObliterateVariableNames denotes a mismatched #, % or $ // by prefixing line with '<ERROR;*; where * is the mismatched // character this.LogASLError("Expected closing " + Mid(varObscureLine, 9, 1) + " character in '" + this.ReportErrorLine(this._lines[i]) + "'", LogType.FatalError); return true; } startParamPos = InStrFrom(convPos, this._lines[i], "("); endParamPos = 0; bracketCount = 1; for (var j = startParamPos + 1; j <= Len(this._lines[i]); j++) { if (Mid(this._lines[i], j, 1) == "(") { bracketCount = bracketCount + 1; } else if (Mid(this._lines[i], j, 1) == ")") { bracketCount = bracketCount - 1; } if (bracketCount == 0) { endParamPos = j; break; } } if (endParamPos == 0) { this.LogASLError("Expected ) in '" + this.ReportErrorLine(this._lines[i]) + "'", LogType.FatalError); return true; } paramData = Mid(this._lines[i], startParamPos + 1, (endParamPos - startParamPos) - 1); symbPos = InStr(paramData, "!="); if (symbPos == 0) { symbPos = InStr(paramData, "<>"); if (symbPos == 0) { symbPos = InStr(paramData, "<="); if (symbPos == 0) { symbPos = InStr(paramData, ">="); if (symbPos == 0) { symbPos = InStr(paramData, "<"); if (symbPos == 0) { symbPos = InStr(paramData, ">"); if (symbPos == 0) { symbPos = InStr(paramData, "="); if (symbPos == 0) { this.LogASLError("Unrecognised 'if' condition in '" + this.ReportErrorLine(this._lines[i]) + "'", LogType.FatalError); return true; } else { symbol = "="; } } else { symbol = ">"; } } else { symbol = "<"; } } else { symbol = ">="; } } else { symbol = "<="; } } else { symbol = "<>"; } } else { symbol = "<>"; } firstData = Trim(Left(paramData, symbPos - 1)); secondData = Trim(Mid(paramData, symbPos + Len(symbol))); if (symbol == "=") { newParam = "is <" + firstData + ";" + secondData + ">"; } else { newParam = "is <" + firstData + ";"; if (symbol == "<") { newParam = newParam + "lt"; } else if (symbol == ">") { newParam = newParam + "gt"; } else if (symbol == ">=") { newParam = newParam + "gt="; } else if (symbol == "<=") { newParam = newParam + "lt="; } else if (symbol == "<>") { newParam = newParam + "!="; } newParam = newParam + ";" + secondData + ">"; } this._lines[i] = Left(this._lines[i], startParamPos - 1) + newParam + Mid(this._lines[i], endParamPos + 1); // Repeat processing this line, in case there are // further changes to be made. i = i - 1; } } return false; } ConvertMultiLineSections(): void { var startLine: number = 0; var braceCount: number = 0; var thisLine: string; var lineToAdd: string; var lastBrace: number = 0; var i: number = 0; var restOfLine: string; var procName: string; var endLineNum: number = 0; var afterLastBrace: string; var z: string; var startOfOrig: string; var testLine: string; var testBraceCount: number = 0; var obp: number = 0; var cbp: number = 0; var curProc: number = 0; i = 1; do { z = this._lines[this._defineBlocks[i].StartLine]; if (((!this.BeginsWith(z, "define text ")) && (!this.BeginsWith(z, "define menu ")) && z != "define synonyms")) { for (var j = this._defineBlocks[i].StartLine + 1; j <= this._defineBlocks[i].EndLine - 1; j++) { if (InStr(this._lines[j], "{") > 0) { afterLastBrace = ""; thisLine = Trim(this._lines[j]); procName = "<!intproc" + curProc + ">"; // see if this brace's corresponding closing // brace is on same line: testLine = Mid(this._lines[j], InStr(this._lines[j], "{") + 1); testBraceCount = 1; do { obp = InStr(testLine, "{"); cbp = InStr(testLine, "}"); if (obp == 0) { obp = Len(testLine) + 1; } if (cbp == 0) { cbp = Len(testLine) + 1; } if (obp < cbp) { testBraceCount = testBraceCount + 1; testLine = Mid(testLine, obp + 1); } else if (cbp < obp) { testBraceCount = testBraceCount - 1; testLine = Mid(testLine, cbp + 1); } } while (!(obp == cbp || testBraceCount == 0)); if (testBraceCount != 0) { this.AddLine("define procedure " + procName); startLine = UBound(this._lines); restOfLine = Trim(Right(thisLine, Len(thisLine) - InStr(thisLine, "{"))); braceCount = 1; if (restOfLine != "") { this.AddLine(restOfLine); } for (var m = 1; m <= Len(restOfLine); m++) { if (Mid(restOfLine, m, 1) == "{") { braceCount = braceCount + 1; } else if (Mid(restOfLine, m, 1) == "}") { braceCount = braceCount - 1; } } if (braceCount != 0) { var k = j + 1; do { for (var m = 1; m <= Len(this._lines[k]); m++) { if (Mid(this._lines[k], m, 1) == "{") { braceCount = braceCount + 1; } else if (Mid(this._lines[k], m, 1) == "}") { braceCount = braceCount - 1; } if (braceCount == 0) { lastBrace = m; break; } } if (braceCount != 0) { //put Lines(k) into another variable, as //AddLine ReDims Lines, which it can't do if //passed Lines(x) as a parameter. lineToAdd = this._lines[k]; this.AddLine(lineToAdd); } else { this.AddLine(Left(this._lines[k], lastBrace - 1)); afterLastBrace = Trim(Mid(this._lines[k], lastBrace + 1)); } //Clear original line this._lines[k] = ""; k = k + 1; } while (braceCount != 0); } this.AddLine("end define"); endLineNum = UBound(this._lines); this._numberSections = this._numberSections + 1; if (!this._defineBlocks) this._defineBlocks = []; this._defineBlocks[this._numberSections] = new DefineBlock(); this._defineBlocks[this._numberSections].StartLine = startLine; this._defineBlocks[this._numberSections].EndLine = endLineNum; //Change original line where the { section //started to call the new procedure. startOfOrig = Trim(Left(thisLine, InStr(thisLine, "{") - 1)); this._lines[j] = startOfOrig + " do " + procName + " " + afterLastBrace; curProc = curProc + 1; // Process this line again in case there was stuff after the last brace that included // more braces. e.g. } else { j = j - 1; } } } } i = i + 1; } while (!(i > this._numberSections)); // Join next-line "else"s to corresponding "if"s for (var i = 1; i <= this._numberSections; i++) { z = this._lines[this._defineBlocks[i].StartLine]; if (((!this.BeginsWith(z, "define text ")) && (!this.BeginsWith(z, "define menu ")) && z != "define synonyms")) { for (var j = this._defineBlocks[i].StartLine + 1; j <= this._defineBlocks[i].EndLine - 1; j++) { if (this.BeginsWith(this._lines[j], "else ")) { //Go upwards to find "if" statement that this //belongs to for (var k = j; k >= this._defineBlocks[i].StartLine + 1; k--) { if (this.BeginsWith(this._lines[k], "if ") || InStr(this.ObliterateParameters(this._lines[k]), " if ") != 0) { this._lines[k] = this._lines[k] + " " + Trim(this._lines[j]); this._lines[j] = ""; k = this._defineBlocks[i].StartLine; } } } } } } } ErrorCheck(): boolean { // Parses ASL script for errors. Returns TRUE if OK; // False if a critical error is encountered. var curBegin: number = 0; var curEnd: number = 0; var hasErrors: boolean = false; var curPos: number = 0; var numParamStart: number = 0; var numParamEnd: number = 0; var finLoop: boolean = false; var inText: boolean = false; hasErrors = false; inText = false; // Checks for incorrect number of < and > : for (var i = 1; i <= UBound(this._lines); i++) { numParamStart = 0; numParamEnd = 0; if (this.BeginsWith(this._lines[i], "define text ")) { inText = true; } if (inText && Trim(LCase(this._lines[i])) == "end define") { inText = false; } if (!inText) { //Find number of <'s: curPos = 1; finLoop = false; do { if (InStrFrom(curPos, this._lines[i], "<") != 0) { numParamStart = numParamStart + 1; curPos = InStrFrom(curPos, this._lines[i], "<") + 1; } else { finLoop = true; } } while (!(finLoop)); //Find number of >'s: curPos = 1; finLoop = false; do { if (InStrFrom(curPos, this._lines[i], ">") != 0) { numParamEnd = numParamEnd + 1; curPos = InStrFrom(curPos, this._lines[i], ">") + 1; } else { finLoop = true; } } while (!(finLoop)); if (numParamStart > numParamEnd) { this.LogASLError("Expected > in " + this.ReportErrorLine(this._lines[i]), LogType.FatalError); hasErrors = true; } else if (numParamStart < numParamEnd) { this.LogASLError("Too many > in " + this.ReportErrorLine(this._lines[i]), LogType.FatalError); hasErrors = true; } } } //Exit if errors found if (hasErrors) { return true; } // Checks that define sections have parameters: for (var i = 1; i <= this._numberSections; i++) { curBegin = this._defineBlocks[i].StartLine; curEnd = this._defineBlocks[i].EndLine; if (this.BeginsWith(this._lines[curBegin], "define game")) { if (InStr(this._lines[curBegin], "<") == 0) { this.LogASLError("'define game' has no parameter - game has no name", LogType.FatalError); return true; } } else { if (!this.BeginsWith(this._lines[curBegin], "define synonyms") && !this.BeginsWith(this._lines[curBegin], "define options")) { if (InStr(this._lines[curBegin], "<") == 0) { this.LogASLError(this._lines[curBegin] + " has no parameter", LogType.FatalError); hasErrors = true; } } } } return hasErrors; } GetAfterParameter(s: string): string { // Returns everything after the end of the first parameter // in a string, i.e. for "use <thing> do <myproc>" it // returns "do <myproc>" var eop: number = 0; eop = InStr(s, ">"); if (eop == 0 || eop + 1 > Len(s)) { return ""; } else { return Trim(Mid(s, eop + 1)); } } ObliterateParameters(s: string): string { var inParameter: boolean = false; var exitCharacter: string = ""; var curChar: string; var outputLine: string = ""; var obscuringFunctionName: boolean = false; inParameter = false; for (var i = 1; i <= Len(s); i++) { curChar = Mid(s, i, 1); if (inParameter) { if (exitCharacter == ")") { if (InStr("$#%", curChar) > 0) { // We might be converting a line like: // if ( $rand(1;10)$ < 3 ) then { // and we don't want it to end up like this: // if (~~~~~~~~~~~)$ <~~~~~~~~~~~ // which will cause all sorts of confustion. So, // we get rid of everything between the $ characters // in this case, and set a flag so we know what we're // doing. obscuringFunctionName = true; exitCharacter = curChar; // Move along please outputLine = outputLine + "~"; i = i + 1; curChar = Mid(s, i, 1); } } } if (!inParameter) { outputLine = outputLine + curChar; if (curChar == "<") { inParameter = true; exitCharacter = ">"; } if (curChar == "(") { inParameter = true; exitCharacter = ")"; } } else { if (curChar == exitCharacter) { if (!obscuringFunctionName) { inParameter = false; outputLine = outputLine + curChar; } else { // We've finished obscuring the function name, // now let's find the next ) as we were before // we found this dastardly function obscuringFunctionName = false; exitCharacter = ")"; outputLine = outputLine + "~"; } } else { outputLine = outputLine + "~"; } } } if (inParameter) { return "'<ERROR;" + exitCharacter + ";" + outputLine; } else { return outputLine; } } ObliterateVariableNames(s: string): string { var inParameter: boolean = false; var exitCharacter: string = ""; var outputLine: string = ""; var curChar: string; inParameter = false; for (var i = 1; i <= Len(s); i++) { curChar = Mid(s, i, 1); if (!inParameter) { outputLine = outputLine + curChar; if (curChar == "$") { inParameter = true; exitCharacter = "$"; } if (curChar == "#") { inParameter = true; exitCharacter = "#"; } if (curChar == "%") { inParameter = true; exitCharacter = "%"; } // The ~ was for collectables, and this syntax only // exists in Quest 2.x. The ~ was only finally // allowed to be present on its own in ASL 320. if (curChar == "~" && this._gameAslVersion < 320) { inParameter = true; exitCharacter = "~"; } } else { if (curChar == exitCharacter) { inParameter = false; outputLine = outputLine + curChar; } else { outputLine = outputLine + "X"; } } } if (inParameter) { outputLine = "'<ERROR;" + exitCharacter + ";" + outputLine; } return outputLine; } RemoveComments(): void { var aposPos: number = 0; var inTextBlock: boolean = false; var inSynonymsBlock: boolean = false; var oblitLine: string; // If in a synonyms block, we want to remove lines which are comments, but // we don't want to remove synonyms that contain apostrophes, so we only // get rid of lines with an "'" at the beginning or with " '" in them for (var i = 1; i <= UBound(this._lines); i++) { if (this.BeginsWith(this._lines[i], "'!qdk-note:")) { this._lines[i] = "#!qdk-note:" + this.GetEverythingAfter(this._lines[i], "'!qdk-note:"); } else { if (this.BeginsWith(this._lines[i], "define text ")) { inTextBlock = true; } else if (Trim(this._lines[i]) == "define synonyms") { inSynonymsBlock = true; } else if (this.BeginsWith(this._lines[i], "define type ")) { inSynonymsBlock = true; } else if (Trim(this._lines[i]) == "end define") { inTextBlock = false; inSynonymsBlock = false; } if (!inTextBlock && !inSynonymsBlock) { if (InStr(this._lines[i], "'") > 0) { oblitLine = this.ObliterateParameters(this._lines[i]); if (!this.BeginsWith(oblitLine, "'<ERROR;")) { aposPos = InStr(oblitLine, "'"); if (aposPos != 0) { this._lines[i] = Trim(Left(this._lines[i], aposPos - 1)); } } } } else if (inSynonymsBlock) { if (Left(Trim(this._lines[i]), 1) == "'") { this._lines[i] = ""; } else { // we look for " '", not "'" in synonyms lines aposPos = InStr(this.ObliterateParameters(this._lines[i]), " '"); if (aposPos != 0) { this._lines[i] = Trim(Left(this._lines[i], aposPos - 1)); } } } } } } ReportErrorLine(s: string): string { // We don't want to see the "!intproc" in logged error reports lines. // This function replaces these "do" lines with a nicer-looking "..." for error reporting. var replaceFrom: number = 0; replaceFrom = InStr(s, "do <!intproc"); if (replaceFrom != 0) { return Left(s, replaceFrom - 1) + "..."; } else { return s; } } YesNo(yn: boolean): string { return yn ? "Yes" : "No"; } IsYes(yn: string): boolean { if (LCase(yn) == "yes") { return true; } else { return false; } } BeginsWith(s: string, text: string): boolean { // Compares the beginning of the line with a given // string. Case insensitive. // Example: beginswith("Hello there","HeLlO")=TRUE return Left(LTrim(LCase(s)), Len(text)) == LCase(text); } ConvertCasKeyword(casChar: number): string { var keyword: string = this._casKeywords[casChar]; if (keyword == "!cr") { keyword = "\n"; } return keyword; } ConvertMultiLines(): void { //Goes through each section capable of containing //script commands and puts any multiple-line script commands //into separate procedures. Also joins multiple-line "if" //statements. //This calls RemoveComments after joining lines, so that lines //with "'" as part of a multi-line parameter are not destroyed, //before looking for braces. for (var i = UBound(this._lines); i >= 1; i--) { if (Right(this._lines[i], 2) == "__") { this._lines[i] = Left(this._lines[i], Len(this._lines[i]) - 2) + LTrim(this._lines[i + 1]); this._lines[i + 1] = ""; //Recalculate this line again i = i + 1; } else if (Right(this._lines[i], 1) == "_") { this._lines[i] = Left(this._lines[i], Len(this._lines[i]) - 1) + LTrim(this._lines[i + 1]); this._lines[i + 1] = ""; //Recalculate this line again i = i + 1; } } this.RemoveComments(); } GetDefineBlock(blockname: string): DefineBlock { // Returns the start and end points of a named block. // Returns 0 if block not found. var l: string; var blockType: string; var result = new DefineBlock(); result.StartLine = 0; result.EndLine = 0; for (var i = 1; i <= this._numberSections; i++) { // Get the first line of the define section: l = this._lines[this._defineBlocks[i].StartLine]; // Now, starting from the first word after 'define', // retrieve the next word and compare it to blockname: // Add a space for define blocks with no parameter if (InStrFrom(8, l, " ") == 0) { l = l + " "; } blockType = Mid(l, 8, InStrFrom(8, l, " ") - 8); if (blockType == blockname) { // Return the start and end points result.StartLine = this._defineBlocks[i].StartLine; result.EndLine = this._defineBlocks[i].EndLine; return result; } } return result; } DefineBlockParam(blockname: string, param: string): DefineBlock { // Returns the start and end points of a named block var cache: StringDictionary; var result = new DefineBlock(); param = "k" + param; // protect against numeric block names if (!this._defineBlockParams[blockname]) { // Lazily create cache of define block params cache = {}; this._defineBlockParams[blockname] = cache; for (var i = 1; i <= this._numberSections; i++) { // get the word after "define", e.g. "procedure" var blockType = this.GetEverythingAfter(this._lines[this._defineBlocks[i].StartLine], "define "); var sp = InStr(blockType, " "); if (sp != 0) { blockType = Trim(Left(blockType, sp - 1)); } if (blockType == blockname) { var blockKey = this.GetSimpleParameter(this._lines[this._defineBlocks[i].StartLine]); blockKey = "k" + blockKey; if (!cache[blockKey]) { cache[blockKey] = this._defineBlocks[i].StartLine + "," + this._defineBlocks[i].EndLine; } } } } else { cache = this._defineBlockParams[blockname]; } if (cache[param]) { var blocks = Split(cache[param], ","); result.StartLine = parseInt(blocks[0]); result.EndLine = parseInt(blocks[1]); } return result; } GetEverythingAfter(s: string, text: string): string { if (Len(text) > Len(s)) { return ""; } return Right(s, Len(s) - Len(text)); } LoadCASKeywords(): void { this._casKeywords[0] = "!null"; this._casKeywords[1] = "game"; this._casKeywords[2] = "procedure"; this._casKeywords[3] = "room"; this._casKeywords[4] = "object"; this._casKeywords[5] = "character"; this._casKeywords[6] = "text"; this._casKeywords[7] = "selection"; this._casKeywords[8] = "define"; this._casKeywords[9] = "end"; this._casKeywords[10] = "!quote"; this._casKeywords[11] = "asl-version"; this._casKeywords[12] = "game"; this._casKeywords[13] = "version"; this._casKeywords[14] = "author"; this._casKeywords[15] = "copyright"; this._casKeywords[16] = "info"; this._casKeywords[17] = "start"; this._casKeywords[18] = "possitems"; this._casKeywords[19] = "startitems"; this._casKeywords[20] = "prefix"; this._casKeywords[21] = "look"; this._casKeywords[22] = "out"; this._casKeywords[23] = "gender"; this._casKeywords[24] = "speak"; this._casKeywords[25] = "take"; this._casKeywords[26] = "alias"; this._casKeywords[27] = "place"; this._casKeywords[28] = "east"; this._casKeywords[29] = "north"; this._casKeywords[30] = "west"; this._casKeywords[31] = "south"; this._casKeywords[32] = "give"; this._casKeywords[33] = "hideobject"; this._casKeywords[34] = "hidechar"; this._casKeywords[35] = "showobject"; this._casKeywords[36] = "showchar"; this._casKeywords[37] = "collectable"; this._casKeywords[38] = "collecatbles"; this._casKeywords[39] = "command"; this._casKeywords[40] = "use"; this._casKeywords[41] = "hidden"; this._casKeywords[42] = "script"; this._casKeywords[43] = "font"; this._casKeywords[44] = "default"; this._casKeywords[45] = "fontname"; this._casKeywords[46] = "fontsize"; this._casKeywords[47] = "startscript"; this._casKeywords[48] = "nointro"; this._casKeywords[49] = "indescription"; this._casKeywords[50] = "description"; this._casKeywords[51] = "function"; this._casKeywords[52] = "setvar"; this._casKeywords[53] = "for"; this._casKeywords[54] = "error"; this._casKeywords[55] = "synonyms"; this._casKeywords[56] = "beforeturn"; this._casKeywords[57] = "afterturn"; this._casKeywords[58] = "invisible"; this._casKeywords[59] = "nodebug"; this._casKeywords[60] = "suffix"; this._casKeywords[61] = "startin"; this._casKeywords[62] = "northeast"; this._casKeywords[63] = "northwest"; this._casKeywords[64] = "southeast"; this._casKeywords[65] = "southwest"; this._casKeywords[66] = "items"; this._casKeywords[67] = "examine"; this._casKeywords[68] = "detail"; this._casKeywords[69] = "drop"; this._casKeywords[70] = "everywhere"; this._casKeywords[71] = "nowhere"; this._casKeywords[72] = "on"; this._casKeywords[73] = "anything"; this._casKeywords[74] = "article"; this._casKeywords[75] = "gain"; this._casKeywords[76] = "properties"; this._casKeywords[77] = "type"; this._casKeywords[78] = "action"; this._casKeywords[79] = "displaytype"; this._casKeywords[80] = "override"; this._casKeywords[81] = "enabled"; this._casKeywords[82] = "disabled"; this._casKeywords[83] = "variable"; this._casKeywords[84] = "value"; this._casKeywords[85] = "display"; this._casKeywords[86] = "nozero"; this._casKeywords[87] = "onchange"; this._casKeywords[88] = "timer"; this._casKeywords[89] = "alt"; this._casKeywords[90] = "lib"; this._casKeywords[91] = "up"; this._casKeywords[92] = "down"; this._casKeywords[93] = "gametype"; this._casKeywords[94] = "singleplayer"; this._casKeywords[95] = "multiplayer"; this._casKeywords[96] = "verb"; this._casKeywords[97] = "menu"; this._casKeywords[98] = "container"; this._casKeywords[99] = "surface"; this._casKeywords[100] = "transparent"; this._casKeywords[101] = "opened"; this._casKeywords[102] = "parent"; this._casKeywords[103] = "open"; this._casKeywords[104] = "close"; this._casKeywords[105] = "add"; this._casKeywords[106] = "remove"; this._casKeywords[107] = "list"; this._casKeywords[108] = "empty"; this._casKeywords[109] = "closed"; this._casKeywords[110] = "options"; this._casKeywords[111] = "abbreviations"; this._casKeywords[112] = "locked"; this._casKeywords[150] = "do"; this._casKeywords[151] = "if"; this._casKeywords[152] = "got"; this._casKeywords[153] = "then"; this._casKeywords[154] = "else"; this._casKeywords[155] = "has"; this._casKeywords[156] = "say"; this._casKeywords[157] = "playwav"; this._casKeywords[158] = "lose"; this._casKeywords[159] = "msg"; this._casKeywords[160] = "not"; this._casKeywords[161] = "playerlose"; this._casKeywords[162] = "playerwin"; this._casKeywords[163] = "ask"; this._casKeywords[164] = "goto"; this._casKeywords[165] = "set"; this._casKeywords[166] = "show"; this._casKeywords[167] = "choice"; this._casKeywords[168] = "choose"; this._casKeywords[169] = "is"; this._casKeywords[170] = "setstring"; this._casKeywords[171] = "displaytext"; this._casKeywords[172] = "exec"; this._casKeywords[173] = "pause"; this._casKeywords[174] = "clear"; this._casKeywords[175] = "debug"; this._casKeywords[176] = "enter"; this._casKeywords[177] = "movechar"; this._casKeywords[178] = "moveobject"; this._casKeywords[179] = "revealchar"; this._casKeywords[180] = "revealobject"; this._casKeywords[181] = "concealchar"; this._casKeywords[182] = "concealobject"; this._casKeywords[183] = "mailto"; this._casKeywords[184] = "and"; this._casKeywords[185] = "or"; this._casKeywords[186] = "outputoff"; this._casKeywords[187] = "outputon"; this._casKeywords[188] = "here"; this._casKeywords[189] = "playmidi"; this._casKeywords[190] = "drop"; this._casKeywords[191] = "helpmsg"; this._casKeywords[192] = "helpdisplaytext"; this._casKeywords[193] = "helpclear"; this._casKeywords[194] = "helpclose"; this._casKeywords[195] = "hide"; this._casKeywords[196] = "show"; this._casKeywords[197] = "move"; this._casKeywords[198] = "conceal"; this._casKeywords[199] = "reveal"; this._casKeywords[200] = "numeric"; this._casKeywords[201] = "string"; this._casKeywords[202] = "collectable"; this._casKeywords[203] = "property"; this._casKeywords[204] = "create"; this._casKeywords[205] = "exit"; this._casKeywords[206] = "doaction"; this._casKeywords[207] = "close"; this._casKeywords[208] = "each"; this._casKeywords[209] = "in"; this._casKeywords[210] = "repeat"; this._casKeywords[211] = "while"; this._casKeywords[212] = "until"; this._casKeywords[213] = "timeron"; this._casKeywords[214] = "timeroff"; this._casKeywords[215] = "stop"; this._casKeywords[216] = "panes"; this._casKeywords[217] = "on"; this._casKeywords[218] = "off"; this._casKeywords[219] = "return"; this._casKeywords[220] = "playmod"; this._casKeywords[221] = "modvolume"; this._casKeywords[222] = "clone"; this._casKeywords[223] = "shellexe"; this._casKeywords[224] = "background"; this._casKeywords[225] = "foreground"; this._casKeywords[226] = "wait"; this._casKeywords[227] = "picture"; this._casKeywords[228] = "nospeak"; this._casKeywords[229] = "animate"; this._casKeywords[230] = "persist"; this._casKeywords[231] = "inc"; this._casKeywords[232] = "dec"; this._casKeywords[233] = "flag"; this._casKeywords[234] = "dontprocess"; this._casKeywords[235] = "destroy"; this._casKeywords[236] = "beforesave"; this._casKeywords[237] = "onload"; this._casKeywords[238] = "playmp3"; this._casKeywords[239] = "extract"; this._casKeywords[240] = "shell"; this._casKeywords[241] = "popup"; this._casKeywords[242] = "select"; this._casKeywords[243] = "case"; this._casKeywords[244] = "lock"; this._casKeywords[245] = "unlock"; this._casKeywords[252] = "!startcat"; this._casKeywords[253] = "!endcat"; this._casKeywords[254] = "!unknown"; this._casKeywords[255] = "!cr"; } LoadLibraries(onSuccess: Callback, onFailure: Callback, start: number = this._lines.length - 1) { var libFoundThisSweep = false; var libFileName: string; var libraryList: string[] = []; var numLibraries: number = 0; var libraryAlreadyIncluded: boolean = false; var self = this; for (var i = start; i >= 1; i--) { // We search for includes backwards as a game might include // some-general.lib and then something-specific.lib which needs // something-general; if we include something-specific first, // then something-general afterwards, something-general's startscript // gets executed before something-specific's, as we execute the // lib startscripts backwards as well if (self.BeginsWith(self._lines[i], "!include ")) { libFileName = self.GetSimpleParameter(self._lines[i]); //Clear !include statement self._lines[i] = ""; libraryAlreadyIncluded = false; self.LogASLError("Including library '" + libFileName + "'...", LogType.Init); for (var j = 1; j <= numLibraries; j++) { if (LCase(libFileName) == LCase(libraryList[j])) { libraryAlreadyIncluded = true; break; } } if (libraryAlreadyIncluded) { self.LogASLError(" - Library already included.", LogType.Init); } else { numLibraries = numLibraries + 1; if (!libraryList) libraryList = []; libraryList[numLibraries] = libFileName; libFoundThisSweep = true; self.LogASLError(" - Searching for " + libFileName + " (game path)", LogType.Init); var loadLibrary = function (libCode: string[]) { self.LogASLError(" - Found library, opening...", LogType.Init); libCode = libCode.map(function (line: string) { return self.RemoveTabs(line).trim(); }); self.LoadLibrary(libCode); // continue scanning for libraries self.LoadLibraries(onSuccess, onFailure, i-1); }; var onLibSuccess = function (data: string) { var libCode = data.split("\n"); loadLibrary(libCode); }; var onLibFailure = function () { // File was not found; try standard Quest libraries (stored at the end of asl4.ts) self.LogASLError(" - Library not found in game path.", LogType.Init); self.LogASLError(" - Searching for " + libFileName + " (standard libraries)", LogType.Init); var libCode = self.GetLibraryLines(libFileName); if (libCode) { loadLibrary(libCode); } else { self.LogASLError("Library not found.", LogType.FatalError); onFailure(); } }; this.GetFileData(libFileName, onLibSuccess, onLibFailure); break; } } } if (!libFoundThisSweep) { if (start == this._lines.length - 1) { onSuccess(); } else { this.LoadLibraries(onSuccess, onFailure); } } } LoadLibrary(libCode: string[]) { var self = this; var libLines: number = libCode.length - 1; var ignoreMode: boolean = false; var inDefGameBlock: number = 0; var gameLine: number = 0; var inDefSynBlock: number = 0; var synLine: number = 0; var inDefTypeBlock: number = 0; var typeBlockName: string; var typeLine: number = 0; var libVer = -1; if (libCode[1] == "!library") { for (var c = 1; c <= libLines; c++) { if (self.BeginsWith(libCode[c], "!asl-version ")) { libVer = parseInt(self.GetSimpleParameter(libCode[c])); break; } } } else { //Old library libVer = 100; } if (libVer == -1) { self.LogASLError(" - Library has no asl-version information.", LogType.LibraryWarningError); libVer = 200; } ignoreMode = false; for (var c = 1; c <= libLines; c++) { if (self.BeginsWith(libCode[c], "!include ")) { // Quest only honours !include in a library for asl-version // 311 or later, as it ignored them in versions < 3.11 if (libVer >= 311) { self.AddLine(libCode[c]); } } else if (Left(libCode[c], 1) != "!" && Left(libCode[c], 1) != "'" && !ignoreMode) { self.AddLine(libCode[c]); } else { if (libCode[c] == "!addto game") { inDefGameBlock = 0; for (var d = 1; d <= UBound(self._lines); d++) { if (self.BeginsWith(self._lines[d], "define game ")) { inDefGameBlock = 1; } else if (self.BeginsWith(self._lines[d], "define ")) { if (inDefGameBlock != 0) { inDefGameBlock = inDefGameBlock + 1; } } else if (self._lines[d] == "end define" && inDefGameBlock == 1) { gameLine = d; break; } else if (self._lines[d] == "end define") { if (inDefGameBlock != 0) { inDefGameBlock = inDefGameBlock - 1; } } } do { c = c + 1; if (!self.BeginsWith(libCode[c], "!end")) { // startscript lines in a library are prepended // with "lib" internally so they are executed // before any startscript specified by the // calling ASL file, for asl-versions 311 and // later. // similarly, commands in a library. NB: without this, lib // verbs have lower precedence than game verbs anyway. Also // lib commands have lower precedence than game commands. We // only need this code so that game verbs have a higher // precedence than lib commands. // we also need it so that lib verbs have a higher // precedence than lib commands. var lineToAdd: string; if (libVer >= 311 && self.BeginsWith(libCode[c], "startscript ")) { lineToAdd = "lib " + libCode[c]; } else if (libVer >= 392 && (self.BeginsWith(libCode[c], "command ") || self.BeginsWith(libCode[c], "verb "))) { lineToAdd = "lib " + libCode[c]; } else { lineToAdd = libCode[c]; } self._lines.splice(gameLine, 0, lineToAdd); gameLine = gameLine + 1; } } while (!(self.BeginsWith(libCode[c], "!end"))); } else if (libCode[c] == "!addto synonyms") { inDefSynBlock = 0; for (var d = 1; d <= UBound(self._lines); d++) { if (self._lines[d] == "define synonyms") { inDefSynBlock = 1; } else if (self._lines[d] == "end define" && inDefSynBlock == 1) { synLine = d; d = UBound(self._lines); } } if (inDefSynBlock == 0) { //No "define synonyms" block in game - so add it self.AddLine("define synonyms"); self.AddLine("end define"); synLine = UBound(self._lines); } do { c = c + 1; if (!self.BeginsWith(libCode[c], "!end")) { if (!self._lines) self._lines = []; for (var d = UBound(self._lines); d >= synLine + 1; d--) { self._lines[d] = self._lines[d - 1]; } self._lines[synLine] = libCode[c]; synLine = synLine + 1; } } while (!(self.BeginsWith(libCode[c], "!end"))); } else if (self.BeginsWith(libCode[c], "!addto type ")) { inDefTypeBlock = 0; typeBlockName = LCase(self.GetSimpleParameter(libCode[c])); for (var d = 1; d <= UBound(self._lines); d++) { if (LCase(self._lines[d]) == "define type <" + typeBlockName + ">") { inDefTypeBlock = 1; } else if (self._lines[d] == "end define" && inDefTypeBlock == 1) { typeLine = d; d = UBound(self._lines); } } if (inDefTypeBlock == 0) { //No "define type (whatever)" block in game - so add it self.AddLine("define type <" + typeBlockName + ">"); self.AddLine("end define"); typeLine = UBound(self._lines); } do { c = c + 1; if (c > libLines) { break; } if (!self.BeginsWith(libCode[c], "!end")) { if (!self._lines) self._lines = []; for (var d = UBound(self._lines); d >= typeLine + 1; d--) { self._lines[d] = self._lines[d - 1]; } self._lines[typeLine] = libCode[c]; typeLine = typeLine + 1; } } while (!(self.BeginsWith(libCode[c], "!end"))); } else if (libCode[c] == "!library") { //ignore } else if (self.BeginsWith(libCode[c], "!asl-version ")) { //ignore } else if (self.BeginsWith(libCode[c], "'")) { //ignore } else if (self.BeginsWith(libCode[c], "!QDK")) { ignoreMode = true; } else if (self.BeginsWith(libCode[c], "!end")) { ignoreMode = false; } } } }; async ParseFile(filename: string, onSuccess: Callback, onFailure: Callback): Promise<void> { var hasErrors: boolean = false; var skipCheck: boolean = false; var defineCount: number = 0; var curLine: number = 0; this._defineBlockParams = {}; var self = this; var doParse = function () { skipCheck = false; var lastSlashPos: number = 0; var slashPos: number = 0; var curPos = 1; do { slashPos = InStrFrom(curPos, filename, "\\"); if (slashPos == 0) slashPos = InStrFrom(curPos, filename, "/"); if (slashPos != 0) { lastSlashPos = slashPos; } curPos = slashPos + 1; } while (!(slashPos == 0)); var filenameNoPath = LCase(Mid(filename, lastSlashPos + 1)); // Very early versions of Quest didn't perform very good syntax checking of ASL files, so this is // for compatibility with games which have non-fatal errors in them. skipCheck = (self._skipCheckFile.indexOf(filenameNoPath) !== -1) if (filenameNoPath == "musicvf1.cas") { self._useStaticFrameForPictures = true; } //RemoveComments called within ConvertMultiLines self.ConvertMultiLines(); if (!skipCheck) { if (!self.CheckSections()) { onFailure(); return; } } self._numberSections = 1; for (var i = 1; i <= self._lines.length - 1; i++) { // find section beginning with 'define' if (self.BeginsWith(self._lines[i], "define")) { // Now, go through until we reach an 'end define'. However, if we // encounter another 'define' there is a nested define. So, if we // encounter 'define' we increment the definecount. When we find an // 'end define' we decrement it. When definecount is zero, we have // found the end of the section. defineCount = 1; // Don't count the current line - we know it begins with 'define'... curLine = i + 1; do { if (self.BeginsWith(self._lines[curLine], "define")) { defineCount = defineCount + 1; } else if (self.BeginsWith(self._lines[curLine], "end define")) { defineCount = defineCount - 1; } curLine = curLine + 1; } while (!(defineCount == 0)); curLine = curLine - 1; // Now, we know that the define section begins at i and ends at // curline. Remember where the section begins and ends: if (!self._defineBlocks) self._defineBlocks = []; self._defineBlocks[self._numberSections] = new DefineBlock(); self._defineBlocks[self._numberSections].StartLine = i; self._defineBlocks[self._numberSections].EndLine = curLine; self._numberSections = self._numberSections + 1; i = curLine; } } self._numberSections = self._numberSections - 1; var gotGameBlock = false; for (var i = 1; i <= self._numberSections; i++) { if (self.BeginsWith(self._lines[self._defineBlocks[i].StartLine], "define game ")) { gotGameBlock = true; break; } } if (!gotGameBlock) { self._openErrorReport = self._openErrorReport + "No 'define game' block.\n"; onFailure(); return; } self.ConvertMultiLineSections(); hasErrors = self.ConvertFriendlyIfs(); if (!hasErrors) { hasErrors = self.ErrorCheck(); } if (hasErrors) { throw "Errors found in game file."; } onSuccess(); }; var loadLibrariesAndParseFile = function () { // Add libraries to end of _lines, then parse the result self.LoadLibraries(doParse, onFailure); }; // Parses file and returns the positions of each main // 'define' block. Supports nested defines. // TODO: Handle zip files //if (LCase(Right(filename, 4)) == ".zip") { // this._originalFilename = filename; // filename = GetUnzippedFile(filename); // this._gamePath = System.IO.Path.GetDirectoryName(filename); //} if (LCase(Right(filename, 4)) == ".asl" || LCase(Right(filename, 4)) == ".txt") { var self = this; this.GetFileData(filename, function (fileData: string) { var aslLines: string[] = fileData.replace(/\r\n/g, "\n").split("\n"); self._lines = []; self._lines[0] = ""; for (var l = 1; l <= aslLines.length; l++) { self._lines[l] = self.RemoveTabs(aslLines[l - 1]).trim(); } loadLibrariesAndParseFile(); }, onFailure); } else if (LCase(Right(filename, 4)) == ".cas") { this.LogASLError("Loading CAS"); await this.LoadCASFile(filename); loadLibrariesAndParseFile(); } else { throw "Unrecognized file extension"; } } LogASLError(err: string, type: LogType = LogType.Misc): void { if (type == LogType.FatalError) { err = "FATAL ERROR: " + err; } else if (type == LogType.WarningError) { err = "ERROR: " + err; } else if (type == LogType.LibraryWarningError) { err = "WARNING ERROR (LIBRARY): " + err; } else if (type == LogType.Init) { err = "INIT: " + err; } else if (type == LogType.Warning) { err = "WARNING: " + err; } else if (type == LogType.UserError) { err = "ERROR (REQUESTED): " + err; } else if (type == LogType.InternalError) { err = "INTERNAL ERROR: " + err; } console.log(err); } async GetParameter(s: string, ctx: Context, convertStringVariables: boolean = true): Promise<string> { // Returns the parameters between < and > in a string var newParam: string; var startPos: number = 0; var endPos: number = 0; startPos = InStr(s, "<"); endPos = InStr(s, ">"); if (startPos == 0 || endPos == 0) { this.LogASLError("Expected parameter in '" + this.ReportErrorLine(s) + "'", LogType.WarningError); return ""; } var retrParam = Mid(s, startPos + 1, (endPos - startPos) - 1); if (convertStringVariables) { if (this._gameAslVersion >= 320) { newParam = await this.ConvertParameter( await this.ConvertParameter( await this.ConvertParameter(retrParam, "#", ConvertType.Strings, ctx), "%", ConvertType.Numeric, ctx), "$", ConvertType.Functions, ctx); } else { if (Left(retrParam, 9) != "~Internal") { newParam = await this.ConvertParameter( await this.ConvertParameter( await this.ConvertParameter( await this.ConvertParameter(retrParam, "#", ConvertType.Strings, ctx), "%", ConvertType.Numeric, ctx), "~", ConvertType.Collectables, ctx), "$", ConvertType.Functions, ctx); } else { newParam = retrParam; } } } else { newParam = retrParam; } return this.EvaluateInlineExpressions(newParam); } GetSimpleParameter(s: string): string { // Returns the parameters between < and > in a string var newParam: string; var startPos: number = 0; var endPos: number = 0; startPos = InStr(s, "<"); endPos = InStr(s, ">"); if (startPos == 0 || endPos == 0) { this.LogASLError("Expected parameter in '" + this.ReportErrorLine(s) + "'", LogType.WarningError); return ""; } return Mid(s, startPos + 1, (endPos - startPos) - 1); } AddLine(line: string): void { //Adds a line to the game script if (!this._lines || this._lines.length == 0) this._lines = [""]; this._lines.push(line); } async LoadCASFile(filename: string): Promise<void> { var endLineReached: boolean = false; var exitTheLoop: boolean = false; var textMode: boolean = false; var casVersion: number = 0; var startCat: number; var endCatPos: number = 0; var chkVer: string; var j: number = 0; var curLin: string; var textData: Uint8Array; var cpos: number = 0; var nextLinePos: number = 0; var c: string; var tl: string; var ckw: number; var d: number; this._lines = []; var fileData = await this.GetCASFileData(filename); chkVer = String.fromCharCode.apply(null, fileData.slice(0, 7)); if (chkVer == "QCGF001") { casVersion = 1; } else if (chkVer == "QCGF002") { casVersion = 2; } else if (chkVer == "QCGF003") { casVersion = 3; } else { throw "Invalid or corrupted CAS file."; } if (casVersion == 3) { startCat = 252; // !startcat } for (var i = 8; i < fileData.length; i++) { if (casVersion == 3 && fileData[i] == startCat) { // Read catalog this._startCatPos = i; endCatPos = fileData.indexOf(253 /* !endcat */, j); this.ReadCatalog(fileData.slice(j + 1, endCatPos)); this._resourceFile = filename; this._resourceOffset = endCatPos + 1; i = fileData.length; this._casFileData = fileData; } else { curLin = ""; endLineReached = false; if (textMode) { textData = fileData.slice(i - 1, fileData.indexOf(253, i)); cpos = 1; var finished = false; if (textData.length > 0) { do { nextLinePos = textData.indexOf(0, cpos); if (nextLinePos == -1) { nextLinePos = textData.length + 1; finished = true; } tl = this.DecryptString(textData.slice(cpos, nextLinePos)); this.AddLine(tl); cpos = nextLinePos + 1; } while (!(finished)); } textMode = false; i = fileData.indexOf(253, i); } j = i; do { ckw = fileData[j]; c = this.ConvertCasKeyword(ckw); if (c == "\n") { endLineReached = true; } else { if (Left(c, 1) != "!") { curLin = curLin + c + " "; } else { if (c == "!quote") { exitTheLoop = false; curLin = curLin + "<"; do { j = j + 1; d = fileData[j]; if (d != 0) { curLin = curLin + this.DecryptItem(d); } else { curLin = curLin + "> "; exitTheLoop = true; } } while (!(exitTheLoop)); } else if (c == "!unknown") { exitTheLoop = false; do { j = j + 1; d = fileData[j]; if (d != 254) { curLin = curLin + Chr(d); } else { exitTheLoop = true; } } while (!(exitTheLoop)); curLin = curLin + " "; } } } j = j + 1; } while (!(endLineReached)); this.AddLine(Trim(curLin)); if (this.BeginsWith(curLin, "define text") || (casVersion >= 2 && (this.BeginsWith(curLin, "define synonyms") || this.BeginsWith(curLin, "define type") || this.BeginsWith(curLin, "define menu")))) { textMode = true; } //j is already at correct place, but i will be //incremented - so put j back one or we will miss a //character. i = j - 1; } } } RemoveTabs(s: string): string { return s.replace(/\t/g, " "); } DoAddRemove(childId: number, parentId: number, add: boolean, ctx: Context): void { if (add) { this.AddToObjectProperties("parent=" + this._objs[parentId].ObjectName, childId, ctx); this._objs[childId].ContainerRoom = this._objs[parentId].ContainerRoom; } else { this.AddToObjectProperties("not parent", childId, ctx); } if (this._gameAslVersion >= 410) { // Putting something in a container implicitly makes that // container "seen". Otherwise we could try to "look at" the // object we just put in the container and have disambigution fail! this.AddToObjectProperties("seen", parentId, ctx); } this.UpdateVisibilityInContainers(ctx, this._objs[parentId].ObjectName); } async DoLook(id: number, ctx: Context, showExamineError: boolean = false, showDefaultDescription: boolean = true): Promise<void> { var objectContents: string; var foundLook = false; // First, set the "seen" property, and for ASL >= 391, update visibility for any // object that is contained by this object. if (this._gameAslVersion >= 391) { this.AddToObjectProperties("seen", id, ctx); this.UpdateVisibilityInContainers(ctx, this._objs[id].ObjectName); } // First look for action, then look // for property, then check define // section: var lookLine: string; var o = this._objs[id]; for (var i = 1; i <= o.NumberActions; i++) { if (o.Actions[i].ActionName == "look") { foundLook = true; await this.ExecuteScript(o.Actions[i].Script, ctx); break; } } if (!foundLook) { for (var i = 1; i <= o.NumberProperties; i++) { if (o.Properties[i].PropertyName == "look") { // do this odd RetrieveParameter stuff to convert any variables await this.Print(await this.GetParameter("<" + o.Properties[i].PropertyValue + ">", ctx), ctx); foundLook = true; break; } } } if (!foundLook) { for (var i = o.DefinitionSectionStart; i <= o.DefinitionSectionEnd; i++) { if (this.BeginsWith(this._lines[i], "look ")) { lookLine = Trim(this.GetEverythingAfter(this._lines[i], "look ")); if (Left(lookLine, 1) == "<") { await this.Print(await this.GetParameter(this._lines[i], ctx), ctx); } else { await this.ExecuteScript(lookLine, ctx, id); } foundLook = true; } } } if (this._gameAslVersion >= 391) { objectContents = await this.ListContents(id, ctx); } else { objectContents = ""; } if (!foundLook && showDefaultDescription) { var err: PlayerError; if (showExamineError) { err = PlayerError.DefaultExamine; } else { err = PlayerError.DefaultLook; } // Print "Nothing out of the ordinary" or whatever, but only if we're not going to list // any contents. if (objectContents == "") { await this.PlayerErrorMessage(err, ctx); } } if (objectContents != "" && objectContents != "<script>") { await this.Print(objectContents, ctx); } } async DoOpenClose(id: number, open: boolean, showLook: boolean, ctx: Context): Promise<void> { if (open) { this.AddToObjectProperties("opened", id, ctx); if (showLook) { await this.DoLook(id, ctx, null, false); } } else { this.AddToObjectProperties("not opened", id, ctx); } this.UpdateVisibilityInContainers(ctx, this._objs[id].ObjectName); } EvaluateInlineExpressions(s: string): string { // Evaluates in-line expressions e.g. msg <Hello, did you know that 2 + 2 = {2+2}?> if (this._gameAslVersion < 391) { return s; } var bracePos: number = 0; var curPos = 1; var resultLine = ""; do { bracePos = InStrFrom(curPos, s, "{"); if (bracePos != 0) { resultLine = resultLine + Mid(s, curPos, bracePos - curPos); if (Mid(s, bracePos, 2) == "{{") { // {{ = { curPos = bracePos + 2; resultLine = resultLine + "{"; } else { var EndBracePos = InStrFrom(bracePos + 1, s, "}"); if (EndBracePos == 0) { this.LogASLError("Expected } in '" + s + "'", LogType.WarningError); return "<ERROR>"; } else { var expression = Mid(s, bracePos + 1, EndBracePos - bracePos - 1); var expResult = this.ExpressionHandler(expression); if (expResult.Success != ExpressionSuccess.OK) { this.LogASLError("Error evaluating expression in <" + s + "> - " + expResult.Message); return "<ERROR>"; } resultLine = resultLine + expResult.Result; curPos = EndBracePos + 1; } } } else { resultLine = resultLine + Mid(s, curPos); } } while (!(bracePos == 0 || curPos > Len(s))); // Above, we only bothered checking for {{. But for consistency, also }} = }. So let's do that: curPos = 1; do { bracePos = InStrFrom(curPos, resultLine, "}}"); if (bracePos != 0) { resultLine = Left(resultLine, bracePos) + Mid(resultLine, bracePos + 2); curPos = bracePos + 1; } } while (!(bracePos == 0 || curPos > Len(resultLine))); return resultLine; } async ExecAddRemove(cmd: string, ctx: Context): Promise<void> { var childId: number = 0; var childName: string; var doAdd: boolean = false; var sepPos: number = 0; var parentId: number = 0; var sepLen: number = 0; var parentName: string; var verb: string = ""; var action: string; var foundAction: boolean = false; var actionScript: string = ""; var propertyExists: boolean = false; var textToPrint: string; var isContainer: boolean = false; var gotObject: boolean = false; var childLength: number = 0; var noParentSpecified = false; if (this.BeginsWith(cmd, "put ")) { verb = "put"; doAdd = true; sepPos = InStr(cmd, " on "); sepLen = 4; if (sepPos == 0) { sepPos = InStr(cmd, " in "); sepLen = 4; } if (sepPos == 0) { sepPos = InStr(cmd, " onto "); sepLen = 6; } } else if (this.BeginsWith(cmd, "add ")) { verb = "add"; doAdd = true; sepPos = InStr(cmd, " to "); sepLen = 4; } else if (this.BeginsWith(cmd, "remove ")) { verb = "remove"; doAdd = false; sepPos = InStr(cmd, " from "); sepLen = 6; } if (sepPos == 0) { noParentSpecified = true; sepPos = Len(cmd) + 1; } childLength = sepPos - (Len(verb) + 2); if (childLength < 0) { await this.PlayerErrorMessage(PlayerError.BadCommand, ctx); this._badCmdBefore = verb; return; } childName = Trim(Mid(cmd, Len(verb) + 2, childLength)); gotObject = false; if (this._gameAslVersion >= 392 && doAdd) { childId = await this.Disambiguate(childName, this._currentRoom + ";inventory", ctx); if (childId > 0) { if (this._objs[childId].ContainerRoom == "inventory") { gotObject = true; } else { // Player is not carrying the object they referred to. So, first take the object. await this.Print("(first taking " + this._objs[childId].Article + ")", ctx); // Try to take the object ctx.AllowRealNamesInCommand = true; await this.ExecCommand("take " + this._objs[childId].ObjectName, ctx, false, null, true); if (this._objs[childId].ContainerRoom == "inventory") { gotObject = true; } } if (!gotObject) { this._badCmdBefore = verb; return; } } else { if (childId != -2) { await this.PlayerErrorMessage(PlayerError.NoItem, ctx); } this._badCmdBefore = verb; return; } } else { childId = await this.Disambiguate(childName, "inventory;" + this._currentRoom, ctx); if (childId <= 0) { if (childId != -2) { await this.PlayerErrorMessage(PlayerError.BadThing, ctx); } this._badCmdBefore = verb; return; } } if (noParentSpecified && doAdd) { await this.SetStringContents("quest.error.article", this._objs[childId].Article, ctx); await this.PlayerErrorMessage(PlayerError.BadPut, ctx); return; } if (doAdd) { action = "add"; } else { action = "remove"; } if (!noParentSpecified) { parentName = Trim(Mid(cmd, sepPos + sepLen)); parentId = await this.Disambiguate(parentName, this._currentRoom + ";inventory", ctx); if (parentId <= 0) { if (parentId != -2) { await this.PlayerErrorMessage(PlayerError.BadThing, ctx); } this._badCmdBefore = Left(cmd, sepPos + sepLen); return; } } else { // Assume the player was referring to the parent that the object is already in, // if it is even in an object already if (!this.IsYes(this.GetObjectProperty("parent", childId, true, false))) { await this.PlayerErrorMessage(PlayerError.CantRemove, ctx); return; } parentId = this.GetObjectIdNoAlias(this.GetObjectProperty("parent", childId, false, true)); } // Check if parent is a container isContainer = this.IsYes(this.GetObjectProperty("container", parentId, true, false)); if (!isContainer) { if (doAdd) { await this.PlayerErrorMessage(PlayerError.CantPut, ctx); } else { await this.PlayerErrorMessage(PlayerError.CantRemove, ctx); } return; } // Check object is already held by that parent if (this.IsYes(this.GetObjectProperty("parent", childId, true, false))) { if (doAdd && LCase(this.GetObjectProperty("parent", childId, false, false)) == LCase(this._objs[parentId].ObjectName)) { await this.PlayerErrorMessage(PlayerError.AlreadyPut, ctx); } } // Check parent and child are accessible to player var canAccessObject = this.PlayerCanAccessObject(childId); if (!canAccessObject.CanAccessObject) { if (doAdd) { await this.PlayerErrorMessage_ExtendInfo(PlayerError.CantPut, ctx, canAccessObject.ErrorMsg); } else { await this.PlayerErrorMessage_ExtendInfo(PlayerError.CantRemove, ctx, canAccessObject.ErrorMsg); } return; } var canAccessParent = this.PlayerCanAccessObject(parentId); if (!canAccessParent.CanAccessObject) { if (doAdd) { await this.PlayerErrorMessage_ExtendInfo(PlayerError.CantPut, ctx, canAccessParent.ErrorMsg); } else { await this.PlayerErrorMessage_ExtendInfo(PlayerError.CantRemove, ctx, canAccessParent.ErrorMsg); } return; } // Check if parent is a closed container if (!this.IsYes(this.GetObjectProperty("surface", parentId, true, false)) && !this.IsYes(this.GetObjectProperty("opened", parentId, true, false))) { // Not a surface and not open, so can't add to this closed container. if (doAdd) { await this.PlayerErrorMessage(PlayerError.CantPut, ctx); } else { await this.PlayerErrorMessage(PlayerError.CantRemove, ctx); } return; } // Now check if it can be added to (or removed from) // First check for an action var o = this._objs[parentId]; for (var i = 1; i <= o.NumberActions; i++) { if (LCase(o.Actions[i].ActionName) == action) { foundAction = true; actionScript = o.Actions[i].Script; break; } } if (foundAction) { await this.SetStringContents("quest." + LCase(action) + ".object.name", this._objs[childId].ObjectName, ctx); await this.ExecuteScript(actionScript, ctx, parentId); } else { // Now check for a property propertyExists = this.IsYes(this.GetObjectProperty(action, parentId, true, false)); if (!propertyExists) { // Show error message if (doAdd) { await this.PlayerErrorMessage(PlayerError.CantPut, ctx); } else { await this.PlayerErrorMessage(PlayerError.CantRemove, ctx); } } else { textToPrint = this.GetObjectProperty(action, parentId, false, false); if (textToPrint == "") { // Show default message if (doAdd) { await this.PlayerErrorMessage(PlayerError.DefaultPut, ctx); } else { await this.PlayerErrorMessage(PlayerError.DefaultRemove, ctx); } } else { await this.Print(textToPrint, ctx); } this.DoAddRemove(childId, parentId, doAdd, ctx); } } } ExecAddRemoveScript(parameter: string, add: boolean, ctx: Context): void { var childId: number = 0; var parentId: number = 0; var commandName: string; var childName: string; var parentName: string = ""; var scp: number = 0; if (add) { commandName = "add"; } else { commandName = "remove"; } scp = InStr(parameter, ";"); if (scp == 0 && add) { this.LogASLError("No parent specified in '" + commandName + " <" + parameter + ">", LogType.WarningError); return; } if (scp != 0) { childName = LCase(Trim(Left(parameter, scp - 1))); parentName = LCase(Trim(Mid(parameter, scp + 1))); } else { childName = LCase(Trim(parameter)); } childId = this.GetObjectIdNoAlias(childName); if (childId == 0) { this.LogASLError("Invalid child object name specified in '" + commandName + " <" + parameter + ">", LogType.WarningError); return; } if (scp != 0) { parentId = this.GetObjectIdNoAlias(parentName); if (parentId == 0) { this.LogASLError("Invalid parent object name specified in '" + commandName + " <" + parameter + ">", LogType.WarningError); return; } this.DoAddRemove(childId, parentId, add, ctx); } else { this.AddToObjectProperties("not parent", childId, ctx); this.UpdateVisibilityInContainers(ctx, this._objs[parentId].ObjectName); } } async ExecOpenClose(cmd: string, ctx: Context): Promise<void> { var id: number = 0; var name: string; var doOpen: boolean = false; var isOpen: boolean = false; var foundAction: boolean = false; var action: string = ""; var actionScript: string = ""; var propertyExists: boolean = false; var textToPrint: string; var isContainer: boolean = false; if (this.BeginsWith(cmd, "open ")) { action = "open"; doOpen = true; } else if (this.BeginsWith(cmd, "close ")) { action = "close"; doOpen = false; } name = this.GetEverythingAfter(cmd, action + " "); id = await this.Disambiguate(name, this._currentRoom + ";inventory", ctx); if (id <= 0) { if (id != -2) { await this.PlayerErrorMessage(PlayerError.BadThing, ctx); } this._badCmdBefore = action; return; } // Check if it's even a container isContainer = this.IsYes(this.GetObjectProperty("container", id, true, false)); if (!isContainer) { if (doOpen) { await this.PlayerErrorMessage(PlayerError.CantOpen, ctx); } else { await this.PlayerErrorMessage(PlayerError.CantClose, ctx); } return; } // Check if it's already open (or closed) isOpen = this.IsYes(this.GetObjectProperty("opened", id, true, false)); if (doOpen && isOpen) { // Object is already open await this.PlayerErrorMessage(PlayerError.AlreadyOpen, ctx); return; } else if (!doOpen && !isOpen) { // Object is already closed await this.PlayerErrorMessage(PlayerError.AlreadyClosed, ctx); return; } // Check if it's accessible, i.e. check it's not itself inside another closed container var canAccessObject = this.PlayerCanAccessObject(id); if (!canAccessObject.CanAccessObject) { if (doOpen) { await this.PlayerErrorMessage_ExtendInfo(PlayerError.CantOpen, ctx, canAccessObject.ErrorMsg); } else { await this.PlayerErrorMessage_ExtendInfo(PlayerError.CantClose, ctx, canAccessObject.ErrorMsg); } return; } // Now check if it can be opened (or closed) // First check for an action var o = this._objs[id]; for (var i = 1; i <= o.NumberActions; i++) { if (LCase(o.Actions[i].ActionName) == action) { foundAction = true; actionScript = o.Actions[i].Script; break; } } if (foundAction) { await this.ExecuteScript(actionScript, ctx, id); } else { // Now check for a property propertyExists = this.IsYes(this.GetObjectProperty(action, id, true, false)); if (!propertyExists) { // Show error message if (doOpen) { await this.PlayerErrorMessage(PlayerError.CantOpen, ctx); } else { await this.PlayerErrorMessage(PlayerError.CantClose, ctx); } } else { textToPrint = this.GetObjectProperty(action, id, false, false); if (textToPrint == "") { // Show default message if (doOpen) { await this.PlayerErrorMessage(PlayerError.DefaultOpen, ctx); } else { await this.PlayerErrorMessage(PlayerError.DefaultClose, ctx); } } else { await this.Print(textToPrint, ctx); } await this.DoOpenClose(id, doOpen, true, ctx); } } } async ExecuteSelectCase(script: string, ctx: Context): Promise<void> { // ScriptLine passed will look like this: // select case <whatever> do <!intprocX> // with all the case statements in the intproc. var afterLine = this.GetAfterParameter(script); if (!this.BeginsWith(afterLine, "do <!intproc")) { this.LogASLError("No case block specified for '" + script + "'", LogType.WarningError); return; } var blockName = await this.GetParameter(afterLine, ctx); var block = this.DefineBlockParam("procedure", blockName); var checkValue = await this.GetParameter(script, ctx); var caseMatch = false; for (var i = block.StartLine + 1; i <= block.EndLine - 1; i++) { // Go through all the cases until we find the one that matches if (this._lines[i] != "") { if (!this.BeginsWith(this._lines[i], "case ")) { this.LogASLError("Invalid line in 'select case' block: '" + this._lines[i] + "'", LogType.WarningError); } else { var caseScript = ""; if (this.BeginsWith(this._lines[i], "case else ")) { caseMatch = true; caseScript = this.GetEverythingAfter(this._lines[i], "case else "); } else { var thisCase = await this.GetParameter(this._lines[i], ctx); var finished = false; do { var SCP = InStr(thisCase, ";"); if (SCP == 0) { SCP = Len(thisCase) + 1; finished = true; } var condition = Trim(Left(thisCase, SCP - 1)); if (condition == checkValue) { caseScript = this.GetAfterParameter(this._lines[i]); caseMatch = true; finished = true; } else { thisCase = Mid(thisCase, SCP + 1); } } while (!(finished)); } if (caseMatch) { await this.ExecuteScript(caseScript, ctx); return; } } } } } async ExecVerb(cmd: string, ctx: Context, libCommands: boolean = false): Promise<boolean> { var gameBlock: DefineBlock; var foundVerb = false; var verbProperty: string = ""; var script: string = ""; var verbsList: string; var thisVerb: string = ""; var scp: number = 0; var id: number = 0; var verbObject: string = ""; var verbTag: string; var thisScript: string = ""; if (!libCommands) { verbTag = "verb "; } else { verbTag = "lib verb "; } gameBlock = this.GetDefineBlock("game"); for (var i = gameBlock.StartLine + 1; i <= gameBlock.EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], verbTag)) { verbsList = await this.GetParameter(this._lines[i], ctx); // The property or action the verb uses is either after a colon, // or it's the first (or only) verb on the line. var colonPos = InStr(verbsList, ":"); if (colonPos != 0) { verbProperty = LCase(Trim(Mid(verbsList, colonPos + 1))); verbsList = Trim(Left(verbsList, colonPos - 1)); } else { scp = InStr(verbsList, ";"); if (scp == 0) { verbProperty = LCase(verbsList); } else { verbProperty = LCase(Trim(Left(verbsList, scp - 1))); } } // Now let's see if this matches: do { scp = InStr(verbsList, ";"); if (scp == 0) { thisVerb = LCase(verbsList); } else { thisVerb = LCase(Trim(Left(verbsList, scp - 1))); } if (this.BeginsWith(cmd, thisVerb + " ")) { foundVerb = true; verbObject = this.GetEverythingAfter(cmd, thisVerb + " "); script = Trim(Mid(this._lines[i], InStr(this._lines[i], ">") + 1)); } if (scp != 0) { verbsList = Trim(Mid(verbsList, scp + 1)); } } while (!(scp == 0 || Trim(verbsList) == "" || foundVerb)); if (foundVerb) { break; } } } if (foundVerb) { id = await this.Disambiguate(verbObject, "inventory;" + this._currentRoom, ctx); if (id < 0) { if (id != -2) { await this.PlayerErrorMessage(PlayerError.BadThing, ctx); } this._badCmdBefore = thisVerb; } else { await this.SetStringContents("quest.error.article", this._objs[id].Article, ctx); var foundAction = false; // Now see if this object has the relevant action or property var o = this._objs[id]; for (var i = 1; i <= o.NumberActions; i++) { if (LCase(o.Actions[i].ActionName) == verbProperty) { foundAction = true; thisScript = o.Actions[i].Script; break; } } if (thisScript != "") { // Avoid an RTE "this array is fixed or temporarily locked" await this.ExecuteScript(thisScript, ctx, id); } if (!foundAction) { // Check properties for a message for (var i = 1; i <= o.NumberProperties; i++) { if (LCase(o.Properties[i].PropertyName) == verbProperty) { foundAction = true; await this.Print(o.Properties[i].PropertyValue, ctx); break; } } } if (!foundAction) { // Execute the default script from the verb definition await this.ExecuteScript(script, ctx); } } } return foundVerb; } ExpressionHandler(expr: string): ExpressionResult { var openBracketPos: number = 0; var endBracketPos: number = 0; var res: ExpressionResult = new ExpressionResult(); // Find brackets, recursively call ExpressionHandler do { openBracketPos = InStr(expr, "("); if (openBracketPos != 0) { // Find equivalent closing bracket var BracketCount = 1; endBracketPos = 0; for (var i = openBracketPos + 1; i <= Len(expr); i++) { if (Mid(expr, i, 1) == "(") { BracketCount = BracketCount + 1; } else if (Mid(expr, i, 1) == ")") { BracketCount = BracketCount - 1; } if (BracketCount == 0) { endBracketPos = i; break; } } if (endBracketPos != 0) { var NestedResult = this.ExpressionHandler(Mid(expr, openBracketPos + 1, endBracketPos - openBracketPos - 1)); if (NestedResult.Success != ExpressionSuccess.OK) { res.Success = NestedResult.Success; res.Message = NestedResult.Message; return res; } expr = Left(expr, openBracketPos - 1) + " " + NestedResult.Result + " " + Mid(expr, endBracketPos + 1); } else { res.Message = "Missing closing bracket"; res.Success = ExpressionSuccess.Fail; return res; } } } while (!(openBracketPos == 0)); // Split expression into elements, e.g.: // 2 + 3 * 578.2 / 36 // E O E O EEEEE O EE where E=Element, O=Operator var numElements = 1; var elements: string[]; elements = ["", ""]; var numOperators = 0; var operators: string[] = []; var newElement: boolean = false; var obscuredExpr = this.ObscureNumericExps(expr); for (var i = 1; i <= Len(expr); i++) { switch (Mid(obscuredExpr, i, 1)) { case "+": case "*": case "/": newElement = true; break; case "-": // A minus often means subtraction, so it's a new element. But sometimes // it just denotes a negative number. In this case, the current element will // be empty. if (Trim(elements[numElements]) == "") { newElement = false; } else { newElement = true; } break; default: newElement = false; break; } if (newElement) { numElements = numElements + 1; elements[numElements] = ""; numOperators = numOperators + 1; operators[numOperators] = Mid(expr, i, 1); } else { elements[numElements] = elements[numElements] + Mid(expr, i, 1); } } // Check Elements are numeric, and trim spaces for (var i = 1; i <= numElements; i++) { elements[i] = Trim(elements[i]); if (!IsNumeric(elements[i])) { res.Message = "Syntax error evaluating expression - non-numeric element '" + elements[i] + "'"; res.Success = ExpressionSuccess.Fail; return res; } } var opNum = 0; do { // Go through the Operators array to find next calculation to perform for (var i = 1; i <= numOperators; i++) { if (operators[i] == "/" || operators[i] == "*") { opNum = i; break; } } if (opNum == 0) { for (var i = 1; i <= numOperators; i++) { if (operators[i] == "+" || operators[i] == "-") { opNum = i; break; } } } // If OpNum is still 0, there are no calculations left to do. if (opNum != 0) { var val1 = parseFloat(elements[opNum]); var val2 = parseFloat(elements[opNum + 1]); var result: number = 0; switch (operators[opNum]) { case "/": if (val2 == 0) { res.Message = "Division by zero"; res.Success = ExpressionSuccess.Fail; return res; } result = val1 / val2; break; case "*": result = val1 * val2; break; case "+": result = val1 + val2; break; case "-": result = val1 - val2; break; } elements[opNum] = (result).toString(); // Remove this operator, and Elements(OpNum+1) from the arrays for (var i = opNum; i <= numOperators - 1; i++) { operators[i] = operators[i + 1]; } for (var i = opNum + 1; i <= numElements - 1; i++) { elements[i] = elements[i + 1]; } numOperators = numOperators - 1; numElements = numElements - 1; if (!operators) operators = []; if (!elements) elements = []; } } while (!(opNum == 0 || numOperators == 0)); res.Success = ExpressionSuccess.OK; res.Result = elements[1]; return res; } async ListContents(id: number, ctx: Context): Promise<string> { // Returns a formatted list of the contents of a container. // If the list action causes a script to be run instead, ListContents // returns "<script>" var contentsIDs: number[] = []; if (!this.IsYes(this.GetObjectProperty("container", id, true, false))) { return ""; } if (!this.IsYes(this.GetObjectProperty("opened", id, true, false)) && !this.IsYes(this.GetObjectProperty("transparent", id, true, false)) && !this.IsYes(this.GetObjectProperty("surface", id, true, false))) { // Container is closed, so return "list closed" property if there is one. if (await this.DoAction(id, "list closed", ctx, false)) { return "<script>"; } else { return this.GetObjectProperty("list closed", id, false, false); } } // populate contents string var numContents = 0; for (var i = 1; i <= this._numberObjs; i++) { if (this._objs[i].Exists && this._objs[i].Visible) { if (LCase(this.GetObjectProperty("parent", i, false, false)) == LCase(this._objs[id].ObjectName)) { numContents = numContents + 1; if (!contentsIDs) contentsIDs = []; contentsIDs[numContents] = i; } } } var contents = ""; if (numContents > 0) { // Check if list property is set. if (await this.DoAction(id, "list", ctx, false)) { return "<script>"; } if (this.IsYes(this.GetObjectProperty("list", id, true, false))) { // Read header, if any var listString = this.GetObjectProperty("list", id, false, false); var displayList = true; if (listString != "") { if (Right(listString, 1) == ":") { contents = Left(listString, Len(listString) - 1) + " "; } else { // If header doesn't end in a colon, then the header is the only text to print contents = listString; displayList = false; } } else { contents = UCase(Left(this._objs[id].Article, 1)) + Mid(this._objs[id].Article, 2) + " contains "; } if (displayList) { for (var i = 1; i <= numContents; i++) { if (i > 1) { if (i < numContents) { contents = contents + ", "; } else { contents = contents + " and "; } } var o = this._objs[contentsIDs[i]]; if (o.Prefix != "") { contents = contents + o.Prefix; } if (o.ObjectAlias != "") { contents = contents + "|b" + o.ObjectAlias + "|xb"; } else { contents = contents + "|b" + o.ObjectName + "|xb"; } if (o.Suffix != "") { contents = contents + " " + o.Suffix; } } } return contents + "."; } // The "list" property is not set, so do not list contents. return ""; } // Container is empty, so return "list empty" property if there is one. if (await this.DoAction(id, "list empty", ctx, false)) { return "<script>"; } else { return this.GetObjectProperty("list empty", id, false, false); } } ObscureNumericExps(s: string): string { // Obscures + or - next to E in Double-type variables with exponents // e.g. 2.345E+20 becomes 2.345EX20 // This stops huge numbers breaking parsing of maths functions var ep: number = 0; var result = s; var pos = 1; do { ep = InStrFrom(pos, result, "E"); if (ep != 0) { result = Left(result, ep) + "X" + Mid(result, ep + 2); pos = ep + 2; } } while (!(ep == 0)); return result; } ProcessListInfo(line: string, id: number): void { var listInfo: TextAction = new TextAction(); var propName: string = ""; if (this.BeginsWith(line, "list closed <")) { listInfo.Type = TextActionType.Text; listInfo.Data = this.GetSimpleParameter(line); propName = "list closed"; } else if (Trim(line) == "list closed off") { // default for list closed is off anyway return; } else if (this.BeginsWith(line, "list closed")) { listInfo.Type = TextActionType.Script; listInfo.Data = this.GetEverythingAfter(line, "list closed"); propName = "list closed"; } else if (this.BeginsWith(line, "list empty <")) { listInfo.Type = TextActionType.Text; listInfo.Data = this.GetSimpleParameter(line); propName = "list empty"; } else if (Trim(line) == "list empty off") { // default for list empty is off anyway return; } else if (this.BeginsWith(line, "list empty")) { listInfo.Type = TextActionType.Script; listInfo.Data = this.GetEverythingAfter(line, "list empty"); propName = "list empty"; } else if (Trim(line) == "list off") { this.AddToObjectProperties("not list", id, this._nullContext); return; } else if (this.BeginsWith(line, "list <")) { listInfo.Type = TextActionType.Text; listInfo.Data = this.GetSimpleParameter(line); propName = "list"; } else if (this.BeginsWith(line, "list ")) { listInfo.Type = TextActionType.Script; listInfo.Data = this.GetEverythingAfter(line, "list "); propName = "list"; } if (propName != "") { if (listInfo.Type == TextActionType.Text) { this.AddToObjectProperties(propName + "=" + listInfo.Data, id, this._nullContext); } else { this.AddToObjectActions("<" + propName + "> " + listInfo.Data, id); } } } GetHTMLColour(colour: string, defaultColour: string): string { // Converts a Quest foreground or background colour setting into an HTML colour colour = LCase(colour); if (colour == "" || colour == "0") { colour = defaultColour; } switch (colour) { case "white": return "FFFFFF"; case "black": return "000000"; case "blue": return "0000FF"; case "yellow": return "FFFF00"; case "red": return "FF0000"; case "green": return "00FF00"; default: return colour; } } async DestroyExit(exitData: string, ctx: Context): Promise<void> { var fromRoom: string = ""; var toRoom: string = ""; var roomId: number = 0; var exitId: number = 0; var scp = InStr(exitData, ";"); if (scp == 0) { this.LogASLError("No exit name specified in 'destroy exit <" + exitData + ">'"); return; } var roomExit: RoomExit; if (this._gameAslVersion >= 410) { roomExit = this.FindExit(exitData); if (roomExit == null) { this.LogASLError("Can't find exit in 'destroy exit <" + exitData + ">'"); return; } roomExit.GetParent().RemoveExit(roomExit); } else { fromRoom = LCase(Trim(Left(exitData, scp - 1))); toRoom = Trim(Mid(exitData, scp + 1)); // Find From Room: var found = false; for (var i = 1; i <= this._numberRooms; i++) { if (LCase(this._rooms[i].RoomName) == fromRoom) { found = true; roomId = i; break; } } if (!found) { this.LogASLError("No such room '" + fromRoom + "'"); return; } found = false; var r = this._rooms[roomId]; for (var i = 1; i <= r.NumberPlaces; i++) { if (r.Places[i].PlaceName == toRoom) { exitId = i; found = true; break; } } if (found) { for (var i = exitId; i <= r.NumberPlaces - 1; i++) { r.Places[i] = r.Places[i + 1]; } if (!r.Places) r.Places = []; r.NumberPlaces = r.NumberPlaces - 1; } } // Update quest.* vars and obj list await this.ShowRoomInfo(this._currentRoom, ctx, true); this.UpdateObjectList(ctx); this.AddToChangeLog("room " + fromRoom, "destroy exit " + toRoom); } DoClear(): void { this._player.ClearScreen(); } async ExecuteFlag(line: string, ctx: Context): Promise<void> { var propertyString: string = ""; if (this.BeginsWith(line, "on ")) { propertyString = await this.GetParameter(line, ctx); } else if (this.BeginsWith(line, "off ")) { propertyString = "not " + await this.GetParameter(line, ctx); } // Game object always has ObjID 1 this.AddToObjectProperties(propertyString, 1, ctx); } ExecuteIfFlag(flag: string): boolean { // Game ObjID is 1 return this.GetObjectProperty(flag, 1, true) == "yes"; } async ExecuteIncDec(line: string, ctx: Context): Promise<void> { var variable: string; var change: number = 0; var param = await this.GetParameter(line, ctx); var sc = InStr(param, ";"); if (sc == 0) { change = 1; variable = param; } else { change = Val(Mid(param, sc + 1)); variable = Trim(Left(param, sc - 1)); } var value = this.GetNumericContents(variable, ctx, true); if (value <= -32766) { value = 0; } if (this.BeginsWith(line, "inc ")) { value = value + change; } else if (this.BeginsWith(line, "dec ")) { value = value - change; } var arrayIndex = this.GetArrayIndex(variable, ctx); await this.SetNumericVariableContents(arrayIndex.Name, value, ctx, arrayIndex.Index); } ExtractFile(file: string): string { var length: number = 0; var startPos: number = 0; var extracted: boolean = false; var resId: number = 0; if (this._resourceFile == "") { return ""; } // Find file in catalog var found = false; for (var i = 1; i <= this._numResources; i++) { if (LCase(file) == LCase(this._resources[i].ResourceName)) { found = true; startPos = this._resources[i].ResourceStart + this._resourceOffset; length = this._resources[i].ResourceLength; extracted = this._resources[i].Extracted; resId = i; break; } } if (!found) { this.LogASLError("Unable to extract '" + file + "' - not present in resources.", LogType.WarningError); return null; } // TODO: Extract file from CAS //var fileName = System.IO.Path.Combine(this._tempFolder, file); //System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(fileName)); if (!extracted) { // Extract file from cached CAS data //var fileData = Mid(this._casFileData, startPos, length); // Write file to temp dir //System.IO.File.WriteAllText(fileName, fileData, System.Text.Encoding.GetEncoding(1252)); this._resources[resId].Extracted = true; } //return fileName; return null; } AddObjectAction(id: number, name: string, script: string, noUpdate: boolean = false): void { // Use NoUpdate in e.g. AddToGiveInfo, otherwise ObjectActionUpdate will call // AddToGiveInfo again leading to a big loop var actionNum: number = 0; var foundExisting = false; var o = this._objs[id]; for (var i = 1; i <= o.NumberActions; i++) { if (o.Actions[i].ActionName == name) { foundExisting = true; actionNum = i; break; } } if (!foundExisting) { o.NumberActions = o.NumberActions + 1; if (!o.Actions) o.Actions = []; o.Actions[o.NumberActions] = new ActionType(); actionNum = o.NumberActions; } o.Actions[actionNum].ActionName = name; o.Actions[actionNum].Script = script; this.ObjectActionUpdate(id, name, script, noUpdate); } AddToChangeLog(appliesTo: string, changeData: string): void { this._gameChangeData.NumberChanges = this._gameChangeData.NumberChanges + 1; if (!this._gameChangeData.ChangeData) this._gameChangeData.ChangeData = []; this._gameChangeData.ChangeData[this._gameChangeData.NumberChanges] = new ChangeType(); this._gameChangeData.ChangeData[this._gameChangeData.NumberChanges].AppliesTo = appliesTo; this._gameChangeData.ChangeData[this._gameChangeData.NumberChanges].Change = changeData; } AddToObjectChangeLog(appliesToType: AppliesTo, appliesTo: string, element: string, changeData: string): void { var changeLog: ChangeLog; // NOTE: We're only actually ever using the object changelog. // Rooms only get logged for creating rooms and creating/destroying exits, so we don't // need the refactored ChangeLog component for those. switch (appliesToType) { case AppliesTo.Object: changeLog = this._changeLogObjects; break; case AppliesTo.Room: changeLog = this._changeLogRooms; break; default: throw "New ArgumentOutOfRangeException()"; } changeLog.AddItem(appliesTo, element, changeData); } AddToGiveInfo(id: number, giveData: string): void { var giveType: GiveType; var actionName: string; var actionScript: string; var o = this._objs[id]; if (this.BeginsWith(giveData, "to ")) { giveData = this.GetEverythingAfter(giveData, "to "); if (this.BeginsWith(giveData, "anything ")) { o.GiveToAnything = this.GetEverythingAfter(giveData, "anything "); this.AddObjectAction(id, "give to anything", o.GiveToAnything, true); return; } else { giveType = GiveType.GiveToSomething; actionName = "give to "; } } else { if (this.BeginsWith(giveData, "anything ")) { o.GiveAnything = this.GetEverythingAfter(giveData, "anything "); this.AddObjectAction(id, "give anything", o.GiveAnything, true); return; } else { giveType = GiveType.GiveSomethingTo; actionName = "give "; } } if (Left(Trim(giveData), 1) == "<") { var name = this.GetSimpleParameter(giveData); var dataId: number = 0; actionName = actionName + "'" + name + "'"; var found = false; for (var i = 1; i <= o.NumberGiveData; i++) { if (o.GiveData[i].GiveType == giveType && LCase(o.GiveData[i].GiveObject) == LCase(name)) { dataId = i; found = true; break; } } if (!found) { o.NumberGiveData = o.NumberGiveData + 1; if (!o.GiveData) o.GiveData = []; o.GiveData[o.NumberGiveData] = new GiveDataType(); dataId = o.NumberGiveData; } var EP = InStr(giveData, ">"); o.GiveData[dataId].GiveType = giveType; o.GiveData[dataId].GiveObject = name; o.GiveData[dataId].GiveScript = Mid(giveData, EP + 2); actionScript = o.GiveData[dataId].GiveScript; this.AddObjectAction(id, actionName, actionScript, true); } } AddToObjectActions(actionInfo: string, id: number) { var actionNum: number = 0; var foundExisting = false; var name = LCase(this.GetSimpleParameter(actionInfo)); var ep = InStr(actionInfo, ">"); if (ep == Len(actionInfo)) { this.LogASLError("No script given for '" + name + "' action data", LogType.WarningError); return; } var script = Trim(Mid(actionInfo, ep + 1)); var o = this._objs[id]; for (var i = 1; i <= o.NumberActions; i++) { if (o.Actions[i].ActionName == name) { foundExisting = true; actionNum = i; break; } } if (!foundExisting) { o.NumberActions = o.NumberActions + 1; if (!o.Actions) o.Actions = []; o.Actions[o.NumberActions] = new ActionType(); actionNum = o.NumberActions; } o.Actions[actionNum].ActionName = name; o.Actions[actionNum].Script = script; this.ObjectActionUpdate(id, name, script); } AddToObjectAltNames(altNames: string, id: number): void { var o = this._objs[id]; do { var endPos = InStr(altNames, ";"); if (endPos == 0) { endPos = Len(altNames) + 1; } var curName = Trim(Left(altNames, endPos - 1)); if (curName != "") { o.NumberAltNames = o.NumberAltNames + 1; if (!o.AltNames) o.AltNames = []; o.AltNames[o.NumberAltNames] = curName; } altNames = Mid(altNames, endPos + 1); } while (!(Trim(altNames) == "")); } AddToObjectProperties(propertyInfo: string, id: number, ctx: Context): void { if (id == 0) { return null; } if (Right(propertyInfo, 1) != ";") { propertyInfo = propertyInfo + ";"; } do { var scp = InStr(propertyInfo, ";"); var info = Left(propertyInfo, scp - 1); propertyInfo = Trim(Mid(propertyInfo, scp + 1)); var name: string; var value: string; var num: number = 0; if (info == "") { break; } var ep = InStr(info, "="); if (ep != 0) { name = Trim(Left(info, ep - 1)); value = Trim(Mid(info, ep + 1)); } else { name = info; value = ""; } var falseProperty = false; if (this.BeginsWith(name, "not ") && value == "") { falseProperty = true; name = this.GetEverythingAfter(name, "not "); } var o = this._objs[id]; var found = false; for (var i = 1; i <= o.NumberProperties; i++) { if (LCase(o.Properties[i].PropertyName) == LCase(name)) { found = true; num = i; i = o.NumberProperties; } } if (!found) { o.NumberProperties = o.NumberProperties + 1; if (!o.Properties) o.Properties = []; o.Properties[o.NumberProperties] = new PropertyType(); num = o.NumberProperties; } if (falseProperty) { o.Properties[num].PropertyName = ""; } else { o.Properties[num].PropertyName = name; o.Properties[num].PropertyValue = value; } this.AddToObjectChangeLog(AppliesTo.Object, this._objs[id].ObjectName, name, "properties " + info); switch (name) { case "alias": if (o.IsRoom) { this._rooms[o.CorresRoomId].RoomAlias = value; } else { o.ObjectAlias = value; } if (this._gameFullyLoaded) { this.UpdateObjectList(ctx); this.UpdateInventory(ctx); } break; case "prefix": if (o.IsRoom) { this._rooms[o.CorresRoomId].Prefix = value; } else { if (value != "") { o.Prefix = value + " "; } else { o.Prefix = ""; } } break; case "indescription": if (o.IsRoom) { this._rooms[o.CorresRoomId].InDescription = value; } break; case "description": if (o.IsRoom) { this._rooms[o.CorresRoomId].Description.Data = value; this._rooms[o.CorresRoomId].Description.Type = TextActionType.Text; } break; case "look": if (o.IsRoom) { this._rooms[o.CorresRoomId].Look = value; } break; case "suffix": o.Suffix = value; break; case "displaytype": o.DisplayType = value; if (this._gameFullyLoaded) { this.UpdateObjectList(ctx); } break; case "gender": o.Gender = value; break; case "article": o.Article = value; break; case "detail": o.Detail = value; break; case "hidden": if (falseProperty) { o.Exists = true; } else { o.Exists = false; } if (this._gameFullyLoaded) { this.UpdateObjectList(ctx); } break; case "invisible": if (falseProperty) { o.Visible = true; } else { o.Visible = false; } if (this._gameFullyLoaded) { this.UpdateObjectList(ctx); } break; case "take": if (this._gameAslVersion >= 392) { if (falseProperty) { o.Take.Type = TextActionType.Nothing; } else { if (value == "") { o.Take.Type = TextActionType.Default; } else { o.Take.Type = TextActionType.Text; o.Take.Data = value; } } } break; } } while (Len(Trim(propertyInfo)) != 0); } AddToUseInfo(id: number, useData: string): void { var useType: UseType; var o = this._objs[id]; if (this.BeginsWith(useData, "on ")) { useData = this.GetEverythingAfter(useData, "on "); if (this.BeginsWith(useData, "anything ")) { o.UseOnAnything = this.GetEverythingAfter(useData, "anything "); return; } else { useType = UseType.UseOnSomething; } } else { if (this.BeginsWith(useData, "anything ")) { o.UseAnything = this.GetEverythingAfter(useData, "anything "); return; } else { useType = UseType.UseSomethingOn; } } if (Left(Trim(useData), 1) == "<") { var objectName = this.GetSimpleParameter(useData); var dataId: number = 0; var found = false; for (var i = 1; i <= o.NumberUseData; i++) { if (o.UseData[i].UseType == useType && LCase(o.UseData[i].UseObject) == LCase(objectName)) { dataId = i; found = true; break; } } if (!found) { o.NumberUseData = o.NumberUseData + 1; if (!o.UseData) o.UseData = []; o.UseData[o.NumberUseData] = new UseDataType(); dataId = o.NumberUseData; } var ep = InStr(useData, ">"); o.UseData[dataId].UseType = useType; o.UseData[dataId].UseObject = objectName; o.UseData[dataId].UseScript = Mid(useData, ep + 2); } else { o.Use = Trim(useData); } } CapFirst(s: string): string { return UCase(Left(s, 1)) + Mid(s, 2); } async ConvertVarsIn(s: string, ctx: Context): Promise<string> { return await this.GetParameter("<" + s + ">", ctx); } DisambObjHere(ctx: Context, id: number, firstPlace: string, twoPlaces: boolean = false, secondPlace: string = "", isExit: boolean = false): boolean { var isSeen: boolean = false; var onlySeen = false; if (firstPlace == "game") { firstPlace = ""; if (secondPlace == "seen") { twoPlaces = false; secondPlace = ""; onlySeen = true; var roomObjId = this._rooms[this.GetRoomId(this._objs[id].ContainerRoom, ctx)].ObjId; if (this._objs[id].ContainerRoom == "inventory") { isSeen = true; } else { if (this.IsYes(this.GetObjectProperty("visited", roomObjId, true, false))) { isSeen = true; } else { if (this.IsYes(this.GetObjectProperty("seen", id, true, false))) { isSeen = true; } } } } } if (((!twoPlaces && (LCase(this._objs[id].ContainerRoom) == LCase(firstPlace) || firstPlace == "")) || (twoPlaces && (LCase(this._objs[id].ContainerRoom) == LCase(firstPlace) || LCase(this._objs[id].ContainerRoom) == LCase(secondPlace)))) && this._objs[id].Exists && this._objs[id].IsExit == isExit) { if (!onlySeen) { return true; } return isSeen; } return false; } ExecClone(cloneString: string, ctx: Context): void { var id: number = 0; var newName: string; var cloneTo: string; var scp = InStr(cloneString, ";"); if (scp == 0) { this.LogASLError("No new object name specified in 'clone <" + cloneString + ">", LogType.WarningError); return; } else { var objectToClone = Trim(Left(cloneString, scp - 1)); id = this.GetObjectIdNoAlias(objectToClone); var SC2 = InStrFrom(scp + 1, cloneString, ";"); if (SC2 == 0) { cloneTo = this._objs[id].ContainerRoom; newName = Trim(Mid(cloneString, scp + 1)); } else { cloneTo = Trim(Mid(cloneString, SC2 + 1)); newName = Trim(Mid(cloneString, scp + 1, (SC2 - scp) - 1)); } } this._numberObjs = this._numberObjs + 1; if (!this._objs) this._objs = []; this._objs[this._numberObjs] = new ObjectType(); this._objs[this._numberObjs] = this._objs[id]; this._objs[this._numberObjs].ContainerRoom = cloneTo; this._objs[this._numberObjs].ObjectName = newName; if (this._objs[id].IsRoom) { // This is a room so create the corresponding room as well this._numberRooms = this._numberRooms + 1; if (!this._rooms) this._rooms = []; this._rooms[this._numberRooms] = new RoomType(); this._rooms[this._numberRooms] = this._rooms[this._objs[id].CorresRoomId]; this._rooms[this._numberRooms].RoomName = newName; this._rooms[this._numberRooms].ObjId = this._numberObjs; this._objs[this._numberObjs].CorresRoom = newName; this._objs[this._numberObjs].CorresRoomId = this._numberRooms; this.AddToChangeLog("room " + newName, "create"); } else { this.AddToChangeLog("object " + newName, "create " + this._objs[this._numberObjs].ContainerRoom); } this.UpdateObjectList(ctx); } async ExecOops(correction: string, ctx: Context): Promise<void> { if (this._badCmdBefore != "") { if (this._badCmdAfter == "") { await this.ExecCommand(this._badCmdBefore + " " + correction, ctx, false); } else { await this.ExecCommand(this._badCmdBefore + " " + correction + " " + this._badCmdAfter, ctx, false); } } } ExecType(typeData: string, ctx: Context): void { var id: number = 0; var found: boolean = false; var scp = InStr(typeData, ";"); if (scp == 0) { this.LogASLError("No type name given in 'type <" + typeData + ">'"); return; } var objName = Trim(Left(typeData, scp - 1)); var typeName = Trim(Mid(typeData, scp + 1)); for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ObjectName) == LCase(objName)) { found = true; id = i; break; } } if (!found) { this.LogASLError("No such object in 'type <" + typeData + ">'"); return; } var o = this._objs[id]; o.NumberTypesIncluded = o.NumberTypesIncluded + 1; if (!o.TypesIncluded) o.TypesIncluded = []; o.TypesIncluded[o.NumberTypesIncluded] = typeName; var propertyData = this.GetPropertiesInType(typeName); this.AddToObjectProperties(propertyData.Properties, id, ctx); for (var i = 1; i <= propertyData.NumberActions; i++) { this.AddObjectAction(id, propertyData.Actions[i].ActionName, propertyData.Actions[i].Script); } // New as of Quest 4.0. Fixes bug that "if type" would fail for any // parent types included by the "type" command. for (var i = 1; i <= propertyData.NumberTypesIncluded; i++) { o.NumberTypesIncluded = o.NumberTypesIncluded + 1; if (!o.TypesIncluded) o.TypesIncluded = []; o.TypesIncluded[o.NumberTypesIncluded] = propertyData.TypesIncluded[i]; } } ExecuteIfAction(actionData: string): boolean { var id: number = 0; var scp = InStr(actionData, ";"); if (scp == 0) { this.LogASLError("No action name given in condition 'action <" + actionData + ">' ...", LogType.WarningError); return false; } var objName = Trim(Left(actionData, scp - 1)); var actionName = Trim(Mid(actionData, scp + 1)); var found = false; for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ObjectName) == LCase(objName)) { found = true; id = i; break; } } if (!found) { this.LogASLError("No such object '" + objName + "' in condition 'action <" + actionData + ">' ...", LogType.WarningError); return false; } var o = this._objs[id]; for (var i = 1; i <= o.NumberActions; i++) { if (LCase(o.Actions[i].ActionName) == LCase(actionName)) { return true; } } return false; } ExecuteIfType(typeData: string): boolean { var id: number = 0; var scp = InStr(typeData, ";"); if (scp == 0) { this.LogASLError("No type name given in condition 'type <" + typeData + ">' ...", LogType.WarningError); return false; } var objName = Trim(Left(typeData, scp - 1)); var typeName = Trim(Mid(typeData, scp + 1)); var found = false; for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ObjectName) == LCase(objName)) { found = true; id = i; break; } } if (!found) { this.LogASLError("No such object '" + objName + "' in condition 'type <" + typeData + ">' ...", LogType.WarningError); return false; } var o = this._objs[id]; for (var i = 1; i <= o.NumberTypesIncluded; i++) { if (LCase(o.TypesIncluded[i]) == LCase(typeName)) { return true; } } return false; } GetArrayIndex(varName: string, ctx: Context): ArrayResult { var result: ArrayResult = new ArrayResult(); if (InStr(varName, "[") == 0 || InStr(varName, "]") == 0) { result.Name = varName; return result; } var beginPos = InStr(varName, "["); var endPos = InStr(varName, "]"); var data = Mid(varName, beginPos + 1, (endPos - beginPos) - 1); if (IsNumeric(data)) { result.Index = parseInt(data); } else { result.Index = this.GetNumericContents(data, ctx); } result.Name = Left(varName, beginPos - 1); return result; } async Disambiguate(name: string, containedIn: string, ctx: Context, isExit: boolean = false): Promise<number> { // Returns object ID being referred to by player. // Returns -1 if object doesn't exist, calling function // then expected to print relevant error. // Returns -2 if "it" meaningless, prints own error. // If it returns an object ID, it also sets quest.lastobject to the name // of the object referred to. // If ctx.AllowRealNamesInCommand is True, will allow an object's real // name to be used even when the object has an alias - this is used when // Disambiguate has been called after an "exec" command to prevent the // player having to choose an object from the disambiguation menu twice var numberCorresIds = 0; var idNumbers: number[] = []; var firstPlace: string; var secondPlace: string = ""; var twoPlaces: boolean = false; var descriptionText: string[]; var validNames: string[]; var numValidNames: number = 0; name = Trim(name); await this.SetStringContents("quest.lastobject", "", ctx); if (InStr(containedIn, ";") != 0) { var scp = InStr(containedIn, ";"); twoPlaces = true; firstPlace = Trim(Left(containedIn, scp - 1)); secondPlace = Trim(Mid(containedIn, scp + 1)); } else { twoPlaces = false; firstPlace = containedIn; } if (ctx.AllowRealNamesInCommand) { for (var i = 1; i <= this._numberObjs; i++) { if (this.DisambObjHere(ctx, i, firstPlace, twoPlaces, secondPlace)) { if (LCase(this._objs[i].ObjectName) == LCase(name)) { await this.SetStringContents("quest.lastobject", this._objs[i].ObjectName, ctx); return i; } } } } // If player uses "it", "them" etc. as name: if (name == "it" || name == "them" || name == "this" || name == "those" || name == "these" || name == "that") { await this.SetStringContents("quest.error.pronoun", name, ctx); if (this._lastIt != 0 && this._lastItMode == ItType.Inanimate && this.DisambObjHere(ctx, this._lastIt, firstPlace, twoPlaces, secondPlace)) { await this.SetStringContents("quest.lastobject", this._objs[this._lastIt].ObjectName, ctx); return this._lastIt; } else { await this.PlayerErrorMessage(PlayerError.BadPronoun, ctx); return -2; } } else if (name == "him") { await this.SetStringContents("quest.error.pronoun", name, ctx); if (this._lastIt != 0 && this._lastItMode == ItType.Male && this.DisambObjHere(ctx, this._lastIt, firstPlace, twoPlaces, secondPlace)) { await this.SetStringContents("quest.lastobject", this._objs[this._lastIt].ObjectName, ctx); return this._lastIt; } else { await this.PlayerErrorMessage(PlayerError.BadPronoun, ctx); return -2; } } else if (name == "her") { await this.SetStringContents("quest.error.pronoun", name, ctx); if (this._lastIt != 0 && this._lastItMode == ItType.Female && this.DisambObjHere(ctx, this._lastIt, firstPlace, twoPlaces, secondPlace)) { await this.SetStringContents("quest.lastobject", this._objs[this._lastIt].ObjectName, ctx); return this._lastIt; } else { await this.PlayerErrorMessage(PlayerError.BadPronoun, ctx); return -2; } } this._thisTurnIt = 0; if (this.BeginsWith(name, "the ")) { name = this.GetEverythingAfter(name, "the "); } for (var i = 1; i <= this._numberObjs; i++) { if (this.DisambObjHere(ctx, i, firstPlace, twoPlaces, secondPlace, isExit)) { numValidNames = this._objs[i].NumberAltNames + 1; validNames = []; validNames[1] = this._objs[i].ObjectAlias; for (var j = 1; j <= this._objs[i].NumberAltNames; j++) { validNames[j + 1] = this._objs[i].AltNames[j]; } for (var j = 1; j <= numValidNames; j++) { if (((LCase(validNames[j]) == LCase(name)) || ("the " + LCase(name) == LCase(validNames[j])))) { numberCorresIds = numberCorresIds + 1; if (!idNumbers) idNumbers = []; idNumbers[numberCorresIds] = i; j = numValidNames; } } } } if (this._gameAslVersion >= 391 && numberCorresIds == 0 && this._useAbbreviations && Len(name) > 0) { // Check for abbreviated object names for (var i = 1; i <= this._numberObjs; i++) { if (this.DisambObjHere(ctx, i, firstPlace, twoPlaces, secondPlace, isExit)) { var thisName: string; if (this._objs[i].ObjectAlias != "") { thisName = LCase(this._objs[i].ObjectAlias); } else { thisName = LCase(this._objs[i].ObjectName); } if (this._gameAslVersion >= 410) { if (this._objs[i].Prefix != "") { thisName = Trim(LCase(this._objs[i].Prefix)) + " " + thisName; } if (this._objs[i].Suffix != "") { thisName = thisName + " " + Trim(LCase(this._objs[i].Suffix)); } } if (InStr(" " + thisName, " " + LCase(name)) != 0) { numberCorresIds = numberCorresIds + 1; if (!idNumbers) idNumbers = []; idNumbers[numberCorresIds] = i; } } } } if (numberCorresIds == 1) { await this.SetStringContents("quest.lastobject", this._objs[idNumbers[1]].ObjectName, ctx); this._thisTurnIt = idNumbers[1]; switch (this._objs[idNumbers[1]].Article) { case "him": this._thisTurnItMode = ItType.Male; break; case "her": this._thisTurnItMode = ItType.Female; break; default: this._thisTurnItMode = ItType.Inanimate; break; } return idNumbers[1]; } else if (numberCorresIds > 1) { descriptionText = []; var question = "Please select which " + name + " you mean:"; await this.Print("- |i" + question + "|xi", ctx); var menuItems: StringDictionary = {}; for (var i = 1; i <= numberCorresIds; i++) { descriptionText[i] = this._objs[idNumbers[i]].Detail; if (descriptionText[i] == "") { if (this._objs[idNumbers[i]].Prefix == "") { descriptionText[i] = this._objs[idNumbers[i]].ObjectAlias; } else { descriptionText[i] = this._objs[idNumbers[i]].Prefix + this._objs[idNumbers[i]].ObjectAlias; } } menuItems[i.toString()] = descriptionText[i]; } var mnu: MenuData = new MenuData(question, menuItems, false); var response: string = await this.ShowMenu(mnu); this._choiceNumber = parseInt(response); await this.SetStringContents("quest.lastobject", this._objs[idNumbers[this._choiceNumber]].ObjectName, ctx); this._thisTurnIt = idNumbers[this._choiceNumber]; switch (this._objs[idNumbers[this._choiceNumber]].Article) { case "him": this._thisTurnItMode = ItType.Male; break; case "her": this._thisTurnItMode = ItType.Female; break; default: this._thisTurnItMode = ItType.Inanimate; break; } await this.Print("- " + descriptionText[this._choiceNumber] + "|n", ctx); return idNumbers[this._choiceNumber]; } this._thisTurnIt = this._lastIt; await this.SetStringContents("quest.error.object", name, ctx); return -1; } async DisplayStatusVariableInfo(id: number, type: VarType, ctx: Context): Promise<string> { var displayData: string = ""; var ep: number = 0; if (type == VarType.String) { displayData = await this.ConvertVarsIn(this._stringVariable[id].DisplayString, ctx); ep = InStr(displayData, "!"); if (ep != 0) { displayData = Left(displayData, ep - 1) + this._stringVariable[id].VariableContents[0] + Mid(displayData, ep + 1); } } else if (type == VarType.Numeric) { if (this._numericVariable[id].NoZeroDisplay && Val(this._numericVariable[id].VariableContents[0]) == 0) { return ""; } displayData = await this.ConvertVarsIn(this._numericVariable[id].DisplayString, ctx); ep = InStr(displayData, "!"); if (ep != 0) { displayData = Left(displayData, ep - 1) + this._numericVariable[id].VariableContents[0] + Mid(displayData, ep + 1); } if (InStr(displayData, "*") > 0) { var firstStar = InStr(displayData, "*"); var secondStar = InStrFrom(firstStar + 1, displayData, "*"); var beforeStar = Left(displayData, firstStar - 1); var afterStar = Mid(displayData, secondStar + 1); var betweenStar = Mid(displayData, firstStar + 1, (secondStar - firstStar) - 1); if (parseFloat(this._numericVariable[id].VariableContents[0]) != 1) { displayData = beforeStar + betweenStar + afterStar; } else { displayData = beforeStar + afterStar; } } } return displayData; } async DoAction(id: number, action: string, ctx: Context, logError: boolean = true): Promise<boolean> { var found: boolean = false; var script: string = ""; var o = this._objs[id]; for (var i = 1; i <= o.NumberActions; i++) { if (o.Actions[i].ActionName == LCase(action)) { found = true; script = o.Actions[i].Script; break; } } if (!found) { if (logError) { this.LogASLError("No such action '" + action + "' defined for object '" + o.ObjectName + "'"); } return false; } var newCtx: Context = this.CopyContext(ctx); newCtx.CallingObjectId = id; await this.ExecuteScript(script, newCtx, id); return true; } HasAction(id: number, action: string): boolean { var o = this._objs[id]; for (var i = 1; i <= o.NumberActions; i++) { if (o.Actions[i].ActionName == LCase(action)) { return true; } } return false; } async ExecForEach(scriptLine: string, ctx: Context): Promise<void> { var inLocation: string; var scriptToRun: string; var isExit: boolean = false; var isRoom: boolean = false; if (this.BeginsWith(scriptLine, "object ")) { scriptLine = this.GetEverythingAfter(scriptLine, "object "); if (!this.BeginsWith(scriptLine, "in ")) { this.LogASLError("Expected 'in' in 'for each object " + this.ReportErrorLine(scriptLine) + "'", LogType.WarningError); return; } } else if (this.BeginsWith(scriptLine, "exit ")) { scriptLine = this.GetEverythingAfter(scriptLine, "exit "); if (!this.BeginsWith(scriptLine, "in ")) { this.LogASLError("Expected 'in' in 'for each exit " + this.ReportErrorLine(scriptLine) + "'", LogType.WarningError); return; } isExit = true; } else if (this.BeginsWith(scriptLine, "room ")) { scriptLine = this.GetEverythingAfter(scriptLine, "room "); if (!this.BeginsWith(scriptLine, "in ")) { this.LogASLError("Expected 'in' in 'for each room " + this.ReportErrorLine(scriptLine) + "'", LogType.WarningError); return; } isRoom = true; } else { this.LogASLError("Unknown type in 'for each " + this.ReportErrorLine(scriptLine) + "'", LogType.WarningError); return; } scriptLine = this.GetEverythingAfter(scriptLine, "in "); if (this.BeginsWith(scriptLine, "game ")) { inLocation = ""; scriptToRun = this.GetEverythingAfter(scriptLine, "game "); } else { inLocation = LCase(await this.GetParameter(scriptLine, ctx)); var bracketPos = InStr(scriptLine, ">"); scriptToRun = Trim(Mid(scriptLine, bracketPos + 1)); } for (var i = 1; i <= this._numberObjs; i++) { if (inLocation == "" || LCase(this._objs[i].ContainerRoom) == inLocation) { if (this._objs[i].IsRoom == isRoom && this._objs[i].IsExit == isExit) { await this.SetStringContents("quest.thing", this._objs[i].ObjectName, ctx); await this.ExecuteScript(scriptToRun, ctx); } } } } async ExecuteAction(data: string, ctx: Context): Promise<void> { var actionName: string; var script: string; var actionNum: number = 0; var id: number = 0; var foundExisting = false; var foundObject = false; var param = await this.GetParameter(data, ctx); var scp = InStr(param, ";"); if (scp == 0) { this.LogASLError("No action name specified in 'action " + data + "'", LogType.WarningError); return; } var objName = Trim(Left(param, scp - 1)); actionName = Trim(Mid(param, scp + 1)); var ep = InStr(data, ">"); if (ep == Len(Trim(data))) { script = ""; } else { script = Trim(Mid(data, ep + 1)); } for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ObjectName) == LCase(objName)) { foundObject = true; id = i; break; } } if (!foundObject) { this.LogASLError("No such object '" + objName + "' in 'action " + data + "'", LogType.WarningError); return; } var o = this._objs[id]; for (var i = 1; i <= o.NumberActions; i++) { if (o.Actions[i].ActionName == actionName) { foundExisting = true; actionNum = i; break; } } if (!foundExisting) { o.NumberActions = o.NumberActions + 1; if (!o.Actions) o.Actions = []; o.Actions[o.NumberActions] = new ActionType(); actionNum = o.NumberActions; } o.Actions[actionNum].ActionName = actionName; o.Actions[actionNum].Script = script; this.ObjectActionUpdate(id, actionName, script); } async ExecuteCondition(condition: string, ctx: Context): Promise<boolean> { var result: boolean = false; var thisNot: boolean = false; if (this.BeginsWith(condition, "not ")) { thisNot = true; condition = this.GetEverythingAfter(condition, "not "); } else { thisNot = false; } if (this.BeginsWith(condition, "got ")) { result = this.ExecuteIfGot(await this.GetParameter(condition, ctx)); } else if (this.BeginsWith(condition, "has ")) { result = this.ExecuteIfHas(await this.GetParameter(condition, ctx)); } else if (this.BeginsWith(condition, "ask ")) { result = await this.ExecuteIfAsk(await this.GetParameter(condition, ctx)); } else if (this.BeginsWith(condition, "is ")) { result = this.ExecuteIfIs(await this.GetParameter(condition, ctx)); } else if (this.BeginsWith(condition, "here ")) { result = this.ExecuteIfHere(await this.GetParameter(condition, ctx), ctx); } else if (this.BeginsWith(condition, "exists ")) { result = this.ExecuteIfExists(await this.GetParameter(condition, ctx), false); } else if (this.BeginsWith(condition, "real ")) { result = this.ExecuteIfExists(await this.GetParameter(condition, ctx), true); } else if (this.BeginsWith(condition, "property ")) { result = this.ExecuteIfProperty(await this.GetParameter(condition, ctx)); } else if (this.BeginsWith(condition, "action ")) { result = this.ExecuteIfAction(await this.GetParameter(condition, ctx)); } else if (this.BeginsWith(condition, "type ")) { result = this.ExecuteIfType(await this.GetParameter(condition, ctx)); } else if (this.BeginsWith(condition, "flag ")) { result = this.ExecuteIfFlag(await this.GetParameter(condition, ctx)); } if (thisNot) { result = !result; } return result; } async ExecuteConditions(list: string, ctx: Context): Promise<boolean> { var conditions: string[]; var numConditions = 0; var operations: string[]; var obscuredConditionList = this.ObliterateParameters(list); var pos = 1; var isFinalCondition = false; do { numConditions = numConditions + 1; if (!conditions) conditions = []; if (!operations) operations = []; var nextCondition = "AND"; var nextConditionPos = InStrFrom(pos, obscuredConditionList, "and "); if (nextConditionPos == 0) { nextConditionPos = InStrFrom(pos, obscuredConditionList, "or "); nextCondition = "OR"; } if (nextConditionPos == 0) { nextConditionPos = Len(obscuredConditionList) + 2; isFinalCondition = true; nextCondition = "FINAL"; } var thisCondition = Trim(Mid(list, pos, nextConditionPos - pos - 1)); conditions[numConditions] = thisCondition; operations[numConditions] = nextCondition; // next condition starts from space after and/or pos = InStrFrom(nextConditionPos, obscuredConditionList, " "); } while (!(isFinalCondition)); operations[0] = "AND"; var result = true; for (var i = 1; i <= numConditions; i++) { var thisResult = await this.ExecuteCondition(conditions[i], ctx); if (operations[i - 1] == "AND") { result = thisResult && result; } else if (operations[i - 1] == "OR") { result = thisResult || result; } } return result; } async ExecuteCreate(data: string, ctx: Context): Promise<void> { var newName: string; if (this.BeginsWith(data, "room ")) { newName = await this.GetParameter(data, ctx); this._numberRooms = this._numberRooms + 1; if (!this._rooms) this._rooms = []; this._rooms[this._numberRooms] = new RoomType(); this._rooms[this._numberRooms].RoomName = newName; this._numberObjs = this._numberObjs + 1; if (!this._objs) this._objs = []; this._objs[this._numberObjs] = new ObjectType(); this._objs[this._numberObjs].ObjectName = newName; this._objs[this._numberObjs].IsRoom = true; this._objs[this._numberObjs].CorresRoom = newName; this._objs[this._numberObjs].CorresRoomId = this._numberRooms; this._rooms[this._numberRooms].ObjId = this._numberObjs; this.AddToChangeLog("room " + newName, "create"); if (this._gameAslVersion >= 410) { this.AddToObjectProperties(this._defaultRoomProperties.Properties, this._numberObjs, ctx); for (var j = 1; j <= this._defaultRoomProperties.NumberActions; j++) { this.AddObjectAction(this._numberObjs, this._defaultRoomProperties.Actions[j].ActionName, this._defaultRoomProperties.Actions[j].Script); } this._rooms[this._numberRooms].Exits = new RoomExits(this); this._rooms[this._numberRooms].Exits.SetObjId(this._rooms[this._numberRooms].ObjId); } } else if (this.BeginsWith(data, "object ")) { var paramData = await this.GetParameter(data, ctx); var scp = InStr(paramData, ";"); var containerRoom: string; if (scp == 0) { newName = paramData; containerRoom = ""; } else { newName = Trim(Left(paramData, scp - 1)); containerRoom = Trim(Mid(paramData, scp + 1)); } this._numberObjs = this._numberObjs + 1; if (!this._objs) this._objs = []; this._objs[this._numberObjs] = new ObjectType(); var o = this._objs[this._numberObjs]; o.ObjectName = newName; o.ObjectAlias = newName; o.ContainerRoom = containerRoom; o.Exists = true; o.Visible = true; o.Gender = "it"; o.Article = "it"; this.AddToChangeLog("object " + newName, "create " + this._objs[this._numberObjs].ContainerRoom); if (this._gameAslVersion >= 410) { this.AddToObjectProperties(this._defaultProperties.Properties, this._numberObjs, ctx); for (var j = 1; j <= this._defaultProperties.NumberActions; j++) { this.AddObjectAction(this._numberObjs, this._defaultProperties.Actions[j].ActionName, this._defaultProperties.Actions[j].Script); } } if (!this._gameLoading) { this.UpdateObjectList(ctx); } } else if (this.BeginsWith(data, "exit ")) { await this.ExecuteCreateExit(data, ctx); } } async ExecuteCreateExit(data: string, ctx: Context): Promise<void> { var scrRoom: string; var destRoom: string = ""; var destId: number = 0; var exitData = this.GetEverythingAfter(data, "exit "); var newName = await this.GetParameter(data, ctx); var scp = InStr(newName, ";"); if (this._gameAslVersion < 410) { if (scp == 0) { this.LogASLError("No exit destination given in 'create exit " + exitData + "'", LogType.WarningError); return; } } if (scp == 0) { scrRoom = Trim(newName); } else { scrRoom = Trim(Left(newName, scp - 1)); } var srcId = this.GetRoomId(scrRoom, ctx); if (srcId == 0) { this.LogASLError("No such room '" + scrRoom + "'", LogType.WarningError); return; } if (this._gameAslVersion < 410) { // only do destination room check for ASL <410, as can now have scripts on dynamically // created exits, so the destination doesn't necessarily have to exist. destRoom = Trim(Mid(newName, scp + 1)); if (destRoom != "") { destId = this.GetRoomId(destRoom, ctx); if (destId == 0) { this.LogASLError("No such room '" + destRoom + "'", LogType.WarningError); return; } } } // If it's a "go to" exit, check if it already exists: var exists = false; if (this.BeginsWith(exitData, "<")) { if (this._gameAslVersion >= 410) { exists = !!this._rooms[srcId].Exits.GetPlaces()[destRoom]; } else { for (var i = 1; i <= this._rooms[srcId].NumberPlaces; i++) { if (LCase(this._rooms[srcId].Places[i].PlaceName) == LCase(destRoom)) { exists = true; break; } } } if (exists) { this.LogASLError("Exit from '" + scrRoom + "' to '" + destRoom + "' already exists", LogType.WarningError); return; } } var paramPos = InStr(exitData, "<"); var saveData: string; if (paramPos == 0) { saveData = exitData; } else { saveData = Left(exitData, paramPos - 1); // We do this so the changelog doesn't contain unconverted variable names saveData = saveData + "<" + await this.GetParameter(exitData, ctx) + ">"; } this.AddToChangeLog("room " + this._rooms[srcId].RoomName, "exit " + saveData); var r = this._rooms[srcId]; if (this._gameAslVersion >= 410) { await r.Exits.AddExitFromCreateScript(exitData, ctx); } else { if (this.BeginsWith(exitData, "north ")) { r.North.Data = destRoom; r.North.Type = TextActionType.Text; } else if (this.BeginsWith(exitData, "south ")) { r.South.Data = destRoom; r.South.Type = TextActionType.Text; } else if (this.BeginsWith(exitData, "east ")) { r.East.Data = destRoom; r.East.Type = TextActionType.Text; } else if (this.BeginsWith(exitData, "west ")) { r.West.Data = destRoom; r.West.Type = TextActionType.Text; } else if (this.BeginsWith(exitData, "northeast ")) { r.NorthEast.Data = destRoom; r.NorthEast.Type = TextActionType.Text; } else if (this.BeginsWith(exitData, "northwest ")) { r.NorthWest.Data = destRoom; r.NorthWest.Type = TextActionType.Text; } else if (this.BeginsWith(exitData, "southeast ")) { r.SouthEast.Data = destRoom; r.SouthEast.Type = TextActionType.Text; } else if (this.BeginsWith(exitData, "southwest ")) { r.SouthWest.Data = destRoom; r.SouthWest.Type = TextActionType.Text; } else if (this.BeginsWith(exitData, "up ")) { r.Up.Data = destRoom; r.Up.Type = TextActionType.Text; } else if (this.BeginsWith(exitData, "down ")) { r.Down.Data = destRoom; r.Down.Type = TextActionType.Text; } else if (this.BeginsWith(exitData, "out ")) { r.Out.Text = destRoom; } else if (this.BeginsWith(exitData, "<")) { r.NumberPlaces = r.NumberPlaces + 1; if (!r.Places) r.Places = []; r.Places[r.NumberPlaces] = new PlaceType(); r.Places[r.NumberPlaces].PlaceName = destRoom; } else { this.LogASLError("Invalid direction in 'create exit " + exitData + "'", LogType.WarningError); } } if (!this._gameLoading) { // Update quest.doorways variables await this.ShowRoomInfo(this._currentRoom, ctx, true); this.UpdateObjectList(ctx); if (this._gameAslVersion < 410) { if (this._currentRoom == this._rooms[srcId].RoomName) { await this.UpdateDoorways(srcId, ctx); } else if (this._currentRoom == this._rooms[destId].RoomName) { await this.UpdateDoorways(destId, ctx); } } else { // Don't have DestID in ASL410 CreateExit code, so just UpdateDoorways // for current room anyway. await this.UpdateDoorways(this.GetRoomId(this._currentRoom, ctx), ctx); } } } async ExecDrop(obj: string, ctx: Context): Promise<void> { var found: boolean = false; var parentId: number = 0; var id: number = 0; id = await this.Disambiguate(obj, "inventory", ctx); if (id > 0) { found = true; } else { found = false; } if (!found) { if (id != -2) { if (this._gameAslVersion >= 391) { await this.PlayerErrorMessage(PlayerError.NoItem, ctx); } else { await this.PlayerErrorMessage(PlayerError.BadDrop, ctx); } } this._badCmdBefore = "drop"; return; } // If object is inside a container, it must be removed before it can be dropped. var isInContainer = false; if (this._gameAslVersion >= 391) { if (this.IsYes(this.GetObjectProperty("parent", id, true, false))) { isInContainer = true; var parent = this.GetObjectProperty("parent", id, false, false); parentId = this.GetObjectIdNoAlias(parent); } } var dropFound = false; var dropStatement: string = ""; for (var i = this._objs[id].DefinitionSectionStart; i <= this._objs[id].DefinitionSectionEnd; i++) { if (this.BeginsWith(this._lines[i], "drop ")) { dropStatement = this.GetEverythingAfter(this._lines[i], "drop "); dropFound = true; break; } } await this.SetStringContents("quest.error.article", this._objs[id].Article, ctx); if (!dropFound || this.BeginsWith(dropStatement, "everywhere")) { if (isInContainer) { // So, we want to drop an object that's in a container or surface. So first // we have to remove the object from that container. var parentDisplayName: string; if (this._objs[parentId].ObjectAlias != "") { parentDisplayName = this._objs[parentId].ObjectAlias; } else { parentDisplayName = this._objs[parentId].ObjectName; } await this.Print("(first removing " + this._objs[id].Article + " from " + parentDisplayName + ")", ctx); // Try to remove the object ctx.AllowRealNamesInCommand = true; await this.ExecCommand("remove " + this._objs[id].ObjectName, ctx, false, null, true); if (this.GetObjectProperty("parent", id, false, false) != "") { // removing the object failed return; } } } if (!dropFound) { await this.PlayerErrorMessage(PlayerError.DefaultDrop, ctx); await this.PlayerItem(this._objs[id].ObjectName, false, ctx); } else { if (this.BeginsWith(dropStatement, "everywhere")) { await this.PlayerItem(this._objs[id].ObjectName, false, ctx); if (InStr(dropStatement, "<") != 0) { await this.Print(await this.GetParameter(dropStatement, ctx), ctx); } else { await this.PlayerErrorMessage(PlayerError.DefaultDrop, ctx); } } else if (this.BeginsWith(dropStatement, "nowhere")) { if (InStr(dropStatement, "<") != 0) { await this.Print(await this.GetParameter(dropStatement, ctx), ctx); } else { await this.PlayerErrorMessage(PlayerError.CantDrop, ctx); } } else { await this.ExecuteScript(dropStatement, ctx); } } } async ExecExamine(command: string, ctx: Context): Promise<void> { var item = LCase(Trim(this.GetEverythingAfter(command, "examine "))); if (item == "") { await this.PlayerErrorMessage(PlayerError.BadExamine, ctx); this._badCmdBefore = "examine"; return; } var id = await this.Disambiguate(item, this._currentRoom + ";inventory", ctx); if (id <= 0) { if (id != -2) { await this.PlayerErrorMessage(PlayerError.BadThing, ctx); } this._badCmdBefore = "examine"; return; } var o = this._objs[id]; // Find "examine" action: for (var i = 1; i <= o.NumberActions; i++) { if (o.Actions[i].ActionName == "examine") { await this.ExecuteScript(o.Actions[i].Script, ctx, id); return; } } // Find "examine" property: for (var i = 1; i <= o.NumberProperties; i++) { if (o.Properties[i].PropertyName == "examine") { await this.Print(o.Properties[i].PropertyValue, ctx); return; } } // Find "examine" tag: for (var i = o.DefinitionSectionStart + 1; i <= this._objs[id].DefinitionSectionEnd - 1; i++) { if (this.BeginsWith(this._lines[i], "examine ")) { var action = Trim(this.GetEverythingAfter(this._lines[i], "examine ")); if (Left(action, 1) == "<") { await this.Print(await this.GetParameter(this._lines[i], ctx), ctx); } else { await this.ExecuteScript(action, ctx, id); } return; } } await this.DoLook(id, ctx, true); } ExecMoveThing(data: string, type: Thing, ctx: Context): void { var scp = InStr(data, ";"); var name = Trim(Left(data, scp - 1)); var place = Trim(Mid(data, scp + 1)); this.MoveThing(name, place, type, ctx); } ExecProperty(data: string, ctx: Context): void { var id: number = 0; var found: boolean = false; var scp = InStr(data, ";"); if (scp == 0) { this.LogASLError("No property data given in 'property <" + data + ">'", LogType.WarningError); return; } var name = Trim(Left(data, scp - 1)); var properties = Trim(Mid(data, scp + 1)); for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ObjectName) == LCase(name)) { found = true; id = i; break; } } if (!found) { this.LogASLError("No such object in 'property <" + data + ">'", LogType.WarningError); return; } this.AddToObjectProperties(properties, id, ctx); } async ExecuteDo(procedureName: string, ctx: Context): Promise<void> { var newCtx: Context = this.CopyContext(ctx); var numParameters = 0; var useNewCtx: boolean = false; if (this._gameAslVersion >= 392 && Left(procedureName, 8) == "!intproc") { // If "do" procedure is run in a new context, context info is not passed to any nested // script blocks in braces. useNewCtx = false; } else { useNewCtx = true; } if (this._gameAslVersion >= 284) { var obp = InStr(procedureName, "("); var cbp: number = 0; if (obp != 0) { cbp = InStrFrom(obp + 1, procedureName, ")"); } if (obp != 0 && cbp != 0) { var parameters = Mid(procedureName, obp + 1, (cbp - obp) - 1); procedureName = Left(procedureName, obp - 1); parameters = parameters + ";"; var pos = 1; do { numParameters = numParameters + 1; var scp = InStrFrom(pos, parameters, ";"); newCtx.NumParameters = numParameters; if (!newCtx.Parameters) newCtx.Parameters = []; newCtx.Parameters[numParameters] = Trim(Mid(parameters, pos, scp - pos)); pos = scp + 1; } while (!(pos >= Len(parameters))); } } var block = this.DefineBlockParam("procedure", procedureName); if (block.StartLine == 0 && block.EndLine == 0) { this.LogASLError("No such procedure " + procedureName, LogType.WarningError); } else { for (var i = block.StartLine + 1; i <= block.EndLine - 1; i++) { if (!useNewCtx) { await this.ExecuteScript(this._lines[i], ctx); } else { await this.ExecuteScript(this._lines[i], newCtx); ctx.DontProcessCommand = newCtx.DontProcessCommand; } } } } async ExecuteDoAction(data: string, ctx: Context): Promise<void> { var id: number = 0; var scp = InStr(data, ";"); if (scp == 0) { this.LogASLError("No action name specified in 'doaction <" + data + ">'"); return; } var objName = LCase(Trim(Left(data, scp - 1))); var actionName = Trim(Mid(data, scp + 1)); var found = false; for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ObjectName) == objName) { found = true; id = i; break; } } if (!found) { this.LogASLError("No such object '" + objName + "'"); return; } await this.DoAction(id, actionName, ctx); } ExecuteIfHere(obj: string, ctx: Context): boolean { if (this._gameAslVersion <= 281) { for (var i = 1; i <= this._numberChars; i++) { if (this._chars[i].ContainerRoom == this._currentRoom && this._chars[i].Exists) { if (LCase(obj) == LCase(this._chars[i].ObjectName)) { return true; } } } } for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ContainerRoom) == LCase(this._currentRoom) && this._objs[i].Exists) { if (LCase(obj) == LCase(this._objs[i].ObjectName)) { return true; } } } return false; } ExecuteIfExists(obj: string, realOnly: boolean): boolean { var result: boolean = false; var errorReport = false; var scp: number = 0; if (InStr(obj, ";") != 0) { scp = InStr(obj, ";"); if (LCase(Trim(Mid(obj, scp + 1))) == "report") { errorReport = true; } obj = Left(obj, scp - 1); } var found = false; if (this._gameAslVersion < 281) { for (var i = 1; i <= this._numberChars; i++) { if (LCase(obj) == LCase(this._chars[i].ObjectName)) { result = this._chars[i].Exists; found = true; break; } } } if (!found) { for (var i = 1; i <= this._numberObjs; i++) { if (LCase(obj) == LCase(this._objs[i].ObjectName)) { result = this._objs[i].Exists; found = true; break; } } } if (!found && errorReport) { this.LogASLError("No such character/object '" + obj + "'.", LogType.UserError); } if (!found) { result = false; } if (realOnly) { return found; } return result; } ExecuteIfProperty(data: string): boolean { var id: number = 0; var scp = InStr(data, ";"); if (scp == 0) { this.LogASLError("No property name given in condition 'property <" + data + ">' ...", LogType.WarningError); return false; } var objName = Trim(Left(data, scp - 1)); var propertyName = Trim(Mid(data, scp + 1)); var found = false; for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ObjectName) == LCase(objName)) { found = true; id = i; break; } } if (!found) { this.LogASLError("No such object '" + objName + "' in condition 'property <" + data + ">' ...", LogType.WarningError); return false; } return this.GetObjectProperty(propertyName, id, true) == "yes"; } async ExecuteRepeat(data: string, ctx: Context): Promise<void> { var repeatWhileTrue: boolean = false; var repeatScript: string = ""; var bracketPos: number = 0; var afterBracket: string; var foundScript = false; if (this.BeginsWith(data, "while ")) { repeatWhileTrue = true; data = this.GetEverythingAfter(data, "while "); } else if (this.BeginsWith(data, "until ")) { repeatWhileTrue = false; data = this.GetEverythingAfter(data, "until "); } else { this.LogASLError("Expected 'until' or 'while' in 'repeat " + this.ReportErrorLine(data) + "'", LogType.WarningError); return; } var pos = 1; do { bracketPos = InStrFrom(pos, data, ">"); afterBracket = Trim(Mid(data, bracketPos + 1)); if ((!this.BeginsWith(afterBracket, "and ")) && (!this.BeginsWith(afterBracket, "or "))) { repeatScript = afterBracket; foundScript = true; } else { pos = bracketPos + 1; } } while (!(foundScript || afterBracket == "")); var conditions = Trim(Left(data, bracketPos)); var finished = false; do { if (await this.ExecuteConditions(conditions, ctx) == repeatWhileTrue) { await this.ExecuteScript(repeatScript, ctx); } else { finished = true; } } while (!(finished || this._gameFinished)); } ExecuteSetCollectable(param: string, ctx: Context): void { var val: number = 0; var id: number = 0; var scp = InStr(param, ";"); var name = Trim(Left(param, scp - 1)); var newVal = Trim(Right(param, Len(param) - scp)); var found = false; for (var i = 1; i <= this._numCollectables; i++) { if (this._collectables[i].Name == name) { id = i; found = true; break; } } if (!found) { this.LogASLError("No such collectable '" + param + "'", LogType.WarningError); return; } var op = Left(newVal, 1); var newValue = Trim(Right(newVal, Len(newVal) - 1)); if (IsNumeric(newValue)) { val = Val(newValue); } else { val = this.GetCollectableAmount(newValue); } if (op == "+") { this._collectables[id].Value = this._collectables[id].Value + val; } else if (op == "-") { this._collectables[id].Value = this._collectables[id].Value - val; } else if (op == "=") { this._collectables[id].Value = val; } this.CheckCollectable(id); this.UpdateItems(ctx); this.UpdateCollectables(); } async ExecuteWait(waitLine: string, ctx: Context): Promise<void> { if (waitLine != "") { await this.Print(await this.GetParameter(waitLine, ctx), ctx); } else { if (this._gameAslVersion >= 410) { await this.PlayerErrorMessage(PlayerError.DefaultWait, ctx); } else { await this.Print("|nPress a key to continue...", ctx); } } await this.DoWait(); } InitFileData(fileData: string): void { this._fileData = fileData; this._fileDataPos = 1; } GetNextChunk(): string { var nullPos = InStrFrom(this._fileDataPos, this._fileData, Chr(0)); var result = Mid(this._fileData, this._fileDataPos, nullPos - this._fileDataPos); if (nullPos < Len(this._fileData)) { this._fileDataPos = nullPos + 1; } return result; } GetFileDataChars(count: number): string { var result = Mid(this._fileData, this._fileDataPos, count); this._fileDataPos = this._fileDataPos + count; return result; } GetObjectActions(actionInfo: string): ActionType { var name = LCase(this.GetSimpleParameter(actionInfo)); var ep = InStr(actionInfo, ">"); if (ep == Len(actionInfo)) { this.LogASLError("No script given for '" + name + "' action data", LogType.WarningError); return new ActionType(); } var script = Trim(Mid(actionInfo, ep + 1)); var result: ActionType = new ActionType(); result.ActionName = name; result.Script = script; return result; } async GetObjectId(name: string, ctx: Context, room: string = ""): Promise<number> { var id: number = 0; var found = false; if (this.BeginsWith(name, "the ")) { name = this.GetEverythingAfter(name, "the "); } for (var i = 1; i <= this._numberObjs; i++) { if ((LCase(this._objs[i].ObjectName) == LCase(name) || LCase(this._objs[i].ObjectName) == "the " + LCase(name)) && (LCase(this._objs[i].ContainerRoom) == LCase(room) || room == "") && this._objs[i].Exists) { id = i; found = true; break; } } if (!found && this._gameAslVersion >= 280) { id = await this.Disambiguate(name, room, ctx); if (id > 0) { found = true; } } if (found) { return id; } return -1; } GetObjectIdNoAlias(name: string): number { for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ObjectName) == LCase(name)) { return i; } } return 0; } GetObjectProperty(name: string, id: number, existsOnly: boolean = false, logError: boolean = true): string { var result: string = ""; var found = false; var o = this._objs[id]; for (var i = 1; i <= o.NumberProperties; i++) { if (LCase(o.Properties[i].PropertyName) == LCase(name)) { found = true; result = o.Properties[i].PropertyValue; break; } } if (existsOnly) { if (found) { return "yes"; } return "no"; } if (found) { return result; } if (logError) { this.LogASLError("Object '" + this._objs[id].ObjectName + "' has no property '" + name + "'", LogType.WarningError); return "!"; } return ""; } GetPropertiesInType(type: string, err: boolean = true): PropertiesActions { var blockId: number = 0; var propertyList: PropertiesActions = new PropertiesActions(); var found = false; for (var i = 1; i <= this._numberSections; i++) { if (this.BeginsWith(this._lines[this._defineBlocks[i].StartLine], "define type")) { if (LCase(this.GetSimpleParameter(this._lines[this._defineBlocks[i].StartLine])) == LCase(type)) { blockId = i; found = true; break; } } } if (!found) { if (err) { this.LogASLError("No such type '" + type + "'", LogType.WarningError); } return new PropertiesActions(); } for (var i = this._defineBlocks[blockId].StartLine + 1; i <= this._defineBlocks[blockId].EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], "type ")) { var typeName = LCase(this.GetSimpleParameter(this._lines[i])); var newProperties = this.GetPropertiesInType(typeName); propertyList.Properties = propertyList.Properties + newProperties.Properties; if (!propertyList.Actions) propertyList.Actions = []; for (var j = propertyList.NumberActions + 1; j <= propertyList.NumberActions + newProperties.NumberActions; j++) { propertyList.Actions[j] = new ActionType(); propertyList.Actions[j].ActionName = newProperties.Actions[j - propertyList.NumberActions].ActionName; propertyList.Actions[j].Script = newProperties.Actions[j - propertyList.NumberActions].Script; } propertyList.NumberActions = propertyList.NumberActions + newProperties.NumberActions; // Add this type name to the TypesIncluded list... propertyList.NumberTypesIncluded = propertyList.NumberTypesIncluded + 1; if (!propertyList.TypesIncluded) propertyList.TypesIncluded = []; propertyList.TypesIncluded[propertyList.NumberTypesIncluded] = typeName; // and add the names of the types included by it... if (!propertyList.TypesIncluded) propertyList.TypesIncluded = []; for (var j = propertyList.NumberTypesIncluded + 1; j <= propertyList.NumberTypesIncluded + newProperties.NumberTypesIncluded; j++) { propertyList.TypesIncluded[j] = newProperties.TypesIncluded[j - propertyList.NumberTypesIncluded]; } propertyList.NumberTypesIncluded = propertyList.NumberTypesIncluded + newProperties.NumberTypesIncluded; } else if (this.BeginsWith(this._lines[i], "action ")) { propertyList.NumberActions = propertyList.NumberActions + 1; if (!propertyList.Actions) propertyList.Actions = []; propertyList.Actions[propertyList.NumberActions] = this.GetObjectActions(this.GetEverythingAfter(this._lines[i], "action ")); } else if (this.BeginsWith(this._lines[i], "properties ")) { propertyList.Properties = propertyList.Properties + this.GetSimpleParameter(this._lines[i]) + ";"; } else if (Trim(this._lines[i]) != "") { propertyList.Properties = propertyList.Properties + this._lines[i] + ";"; } } return propertyList; } GetRoomId(name: string, ctx: Context): number { if (InStr(name, "[") > 0) { var idx = this.GetArrayIndex(name, ctx); name = name + Trim(Str(idx.Index)); } for (var i = 1; i <= this._numberRooms; i++) { if (LCase(this._rooms[i].RoomName) == LCase(name)) { return i; } } return 0; } GetTextOrScript(textScript: string): TextAction { var result = new TextAction(); textScript = Trim(textScript); if (Left(textScript, 1) == "<") { result.Type = TextActionType.Text; result.Data = this.GetSimpleParameter(textScript); } else { result.Type = TextActionType.Script; result.Data = textScript; } return result; } GetThingNumber(name: string, room: string, type: Thing): number { // Returns the number in the Chars() or _objs() array of the specified char/obj if (type == Thing.Character) { for (var i = 1; i <= this._numberChars; i++) { if ((room != "" && LCase(this._chars[i].ObjectName) == LCase(name) && LCase(this._chars[i].ContainerRoom) == LCase(room)) || (room == "" && LCase(this._chars[i].ObjectName) == LCase(name))) { return i; } } } else if (type == Thing.Object) { for (var i = 1; i <= this._numberObjs; i++) { if ((room != "" && LCase(this._objs[i].ObjectName) == LCase(name) && LCase(this._objs[i].ContainerRoom) == LCase(room)) || (room == "" && LCase(this._objs[i].ObjectName) == LCase(name))) { return i; } } } return -1; } GetThingBlock(name: string, room: string, type: Thing): DefineBlock { // Returns position where specified char/obj is defined in ASL code var result = new DefineBlock(); if (type == Thing.Character) { for (var i = 1; i <= this._numberChars; i++) { if (LCase(this._chars[i].ObjectName) == LCase(name) && LCase(this._chars[i].ContainerRoom) == LCase(room)) { result.StartLine = this._chars[i].DefinitionSectionStart; result.EndLine = this._chars[i].DefinitionSectionEnd; return result; } } } else if (type == Thing.Object) { for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ObjectName) == LCase(name) && LCase(this._objs[i].ContainerRoom) == LCase(room)) { result.StartLine = this._objs[i].DefinitionSectionStart; result.EndLine = this._objs[i].DefinitionSectionEnd; return result; } } } result.StartLine = 0; result.EndLine = 0; return result; } MakeRestoreData(): string { var data: string[] = []; var objectData: ChangeType[] = []; var roomData: ChangeType[] = []; var numObjectData: number = 0; var numRoomData: number = 0; // <<< FILE HEADER DATA >>> var header = "QUEST300" + Chr(0) + this.GetOriginalFilenameForQSG() + Chr(0); data.push(header); // The start point for encrypted data is after the filename var start = header.length + 1; data.push(this._currentRoom + Chr(0)); // Organise Change Log for (var i = 1; i <= this._gameChangeData.NumberChanges; i++) { if (this.BeginsWith(this._gameChangeData.ChangeData[i].AppliesTo, "object ")) { numObjectData = numObjectData + 1; if (!objectData) objectData = []; objectData[numObjectData] = new ChangeType(); objectData[numObjectData] = this._gameChangeData.ChangeData[i]; } else if (this.BeginsWith(this._gameChangeData.ChangeData[i].AppliesTo, "room ")) { numRoomData = numRoomData + 1; if (!roomData) roomData = []; roomData[numRoomData] = new ChangeType(); roomData[numRoomData] = this._gameChangeData.ChangeData[i]; } } // <<< OBJECT CREATE/CHANGE DATA >>> data.push(Trim(Str(numObjectData + Object.keys(this._changeLogObjects.Changes).length)) + Chr(0)); for (var i = 1; i <= numObjectData; i++) { data.push(this.GetEverythingAfter(objectData[i].AppliesTo, "object ") + Chr(0) + objectData[i].Change + Chr(0)); } Object.keys(this._changeLogObjects.Changes).forEach(function (key) { var appliesTo = Split(key, "#")[0]; var changeData = this._changeLogObjects.Changes[key]; data.push(appliesTo + Chr(0) + changeData + Chr(0)); }, this); // <<< OBJECT EXIST/VISIBLE/ROOM DATA >>> data.push(Trim(Str(this._numberObjs)) + Chr(0)); for (var i = 1; i <= this._numberObjs; i++) { var exists: string; var visible: string; if (this._objs[i].Exists) { exists = Chr(1); } else { exists = Chr(0); } if (this._objs[i].Visible) { visible = Chr(1); } else { visible = Chr(0); } data.push(this._objs[i].ObjectName + Chr(0) + exists + visible + this._objs[i].ContainerRoom + Chr(0)); } // <<< ROOM CREATE/CHANGE DATA >>> data.push(Trim(Str(numRoomData)) + Chr(0)); for (var i = 1; i <= numRoomData; i++) { data.push(this.GetEverythingAfter(roomData[i].AppliesTo, "room ") + Chr(0) + roomData[i].Change + Chr(0)); } // <<< TIMER STATE DATA >>> data.push(Trim(Str(this._numberTimers)) + Chr(0)); for (var i = 1; i <= this._numberTimers; i++) { var t = this._timers[i]; data.push(t.TimerName + Chr(0)); if (t.TimerActive) { data.push(Chr(1)); } else { data.push(Chr(0)); } data.push(Trim(Str(t.TimerInterval)) + Chr(0)); data.push(Trim(Str(t.TimerTicks)) + Chr(0)); } // <<< STRING VARIABLE DATA >>> data.push(Trim(Str(this._numberStringVariables)) + Chr(0)); for (var i = 1; i <= this._numberStringVariables; i++) { var s = this._stringVariable[i]; data.push(s.VariableName + Chr(0) + Trim(Str(s.VariableUBound)) + Chr(0)); for (var j = 0; j <= s.VariableUBound; j++) { data.push(s.VariableContents[j] + Chr(0)); } } // <<< NUMERIC VARIABLE DATA >>> data.push(Trim(Str(this._numberNumericVariables)) + Chr(0)); for (var i = 1; i <= this._numberNumericVariables; i++) { var n = this._numericVariable[i]; data.push(n.VariableName + Chr(0) + Trim(Str(n.VariableUBound)) + Chr(0)); for (var j = 0; j <= n.VariableUBound; j++) { data.push(n.VariableContents[j] + Chr(0)); } } // Now encrypt data var dataString: string; var newFileData: string[] = []; dataString = data.join(""); newFileData.push(Left(dataString, start - 1)); for (var i = start; i <= Len(dataString); i++) { newFileData.push(Chr(255 - Asc(Mid(dataString, i, 1)))); } return newFileData.join(""); } MoveThing(name: string, room: string, type: Thing, ctx: Context): void { var oldRoom: string = ""; var id = this.GetThingNumber(name, "", type); if (InStr(room, "[") > 0) { var idx = this.GetArrayIndex(room, ctx); room = room + Trim(Str(idx.Index)); } if (type == Thing.Character) { this._chars[id].ContainerRoom = room; } else if (type == Thing.Object) { oldRoom = this._objs[id].ContainerRoom; this._objs[id].ContainerRoom = room; } if (this._gameAslVersion >= 391) { // If this object contains other objects, move them too for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this.GetObjectProperty("parent", i, false, false)) == LCase(name)) { this.MoveThing(this._objs[i].ObjectName, room, type, ctx); } } } this.UpdateObjectList(ctx); if (this.BeginsWith(LCase(room), "inventory") || this.BeginsWith(LCase(oldRoom), "inventory")) { this.UpdateInventory(ctx); } } async ConvertParameter(parameter: string, convertChar: string, action: ConvertType, ctx: Context): Promise<string> { // Returns a string with functions, string and // numeric variables executed or converted as // appropriate, read for display/etc. var result: string = ""; var pos = 1; var finished = false; do { var varPos = InStrFrom(pos, parameter, convertChar); if (varPos == 0) { varPos = Len(parameter) + 1; finished = true; } var currentBit = Mid(parameter, pos, varPos - pos); result = result + currentBit; if (!finished) { var nextPos = InStrFrom(varPos + 1, parameter, convertChar); if (nextPos == 0) { this.LogASLError("Line parameter <" + parameter + "> has missing " + convertChar, LogType.WarningError); return "<ERROR>"; } var varName = Mid(parameter, varPos + 1, (nextPos - 1) - varPos); if (varName == "") { result = result + convertChar; } else { if (action == ConvertType.Strings) { result = result + this.GetStringContents(varName, ctx); } else if (action == ConvertType.Functions) { varName = this.EvaluateInlineExpressions(varName); result = result + await this.DoFunction(varName, ctx); } else if (action == ConvertType.Numeric) { result = result + Trim(Str(this.GetNumericContents(varName, ctx))); } else if (action == ConvertType.Collectables) { result = result + Trim(Str(this.GetCollectableAmount(varName))); } } pos = nextPos + 1; } } while (!(finished)); return result; } async DoFunction(data: string, ctx: Context): Promise<string> { var name: string; var parameter: string; var intFuncResult: string = ""; var intFuncExecuted = false; var paramPos = InStr(data, "("); if (paramPos != 0) { name = Trim(Left(data, paramPos - 1)); var endParamPos = InStrRev(data, ")"); if (endParamPos == 0) { this.LogASLError("Expected ) in $" + data + "$", LogType.WarningError); return ""; } parameter = Mid(data, paramPos + 1, (endParamPos - paramPos) - 1); } else { name = data; parameter = ""; } var block: DefineBlock; block = this.DefineBlockParam("function", name); if (block.StartLine == 0 && block.EndLine == 0) { //Function does not exist; try an internal function. intFuncResult = await this.DoInternalFunction(name, parameter, ctx); if (intFuncResult == "__NOTDEFINED") { this.LogASLError("No such function '" + name + "'", LogType.WarningError); return "[ERROR]"; } else { intFuncExecuted = true; } } if (intFuncExecuted) { return intFuncResult; } else { var newCtx: Context = this.CopyContext(ctx); var numParameters = 0; var pos = 1; if (parameter != "") { parameter = parameter + ";"; do { numParameters = numParameters + 1; var scp = InStrFrom(pos, parameter, ";"); var parameterData = Trim(Mid(parameter, pos, scp - pos)); await this.SetStringContents("quest.function.parameter." + Trim(Str(numParameters)), parameterData, ctx); newCtx.NumParameters = numParameters; if (!newCtx.Parameters) newCtx.Parameters = []; newCtx.Parameters[numParameters] = parameterData; pos = scp + 1; } while (!(pos >= Len(parameter))); await this.SetStringContents("quest.function.numparameters", Trim(Str(numParameters)), ctx); } else { await this.SetStringContents("quest.function.numparameters", "0", ctx); newCtx.NumParameters = 0; } var result: string = ""; for (var i = block.StartLine + 1; i <= block.EndLine - 1; i++) { await this.ExecuteScript(this._lines[i], newCtx); result = newCtx.FunctionReturnValue; } return result; } } async DoInternalFunction(name: string, parameter: string, ctx: Context): Promise<string> { var parameters: string[]; var untrimmedParameters: string[]; var objId: number = 0; var numParameters = 0; var pos = 1; if (parameter != "") { parameter = parameter + ";"; do { numParameters = numParameters + 1; var scp = InStrFrom(pos, parameter, ";"); if (!parameters) parameters = []; if (!untrimmedParameters) untrimmedParameters = []; untrimmedParameters[numParameters] = Mid(parameter, pos, scp - pos); parameters[numParameters] = Trim(untrimmedParameters[numParameters]); pos = scp + 1; } while (!(pos >= Len(parameter))); // Remove final ";" parameter = Left(parameter, Len(parameter) - 1); } else { numParameters = 1; parameters = []; untrimmedParameters = []; parameters[1] = ""; untrimmedParameters[1] = ""; } var param2: string; var param3: string; if (name == "displayname") { objId = await this.GetObjectId(parameters[1], ctx); if (objId == -1) { this.LogASLError("Object '" + parameters[1] + "' does not exist", LogType.WarningError); return "!"; } else { return this._objs[await this.GetObjectId(parameters[1], ctx)].ObjectAlias; } } else if (name == "numberparameters") { return Trim(Str(ctx.NumParameters)); } else if (name == "parameter") { if (numParameters == 0) { this.LogASLError("No parameter number specified for $parameter$ function", LogType.WarningError); return ""; } else { if (Val(parameters[1]) > ctx.NumParameters) { this.LogASLError("No parameter number " + parameters[1] + " sent to this function", LogType.WarningError); return ""; } else { return Trim(ctx.Parameters[parseInt(parameters[1])]); } } } else if (name == "gettag") { // Deprecated return await this.FindStatement(this.DefineBlockParam("room", parameters[1]), parameters[2]); } else if (name == "objectname") { return this._objs[ctx.CallingObjectId].ObjectName; } else if (name == "locationof") { for (var i = 1; i <= this._numberChars; i++) { if (LCase(this._chars[i].ObjectName) == LCase(parameters[1])) { return this._chars[i].ContainerRoom; } } for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ObjectName) == LCase(parameters[1])) { return this._objs[i].ContainerRoom; } } } else if (name == "lengthof") { return Str(Len(untrimmedParameters[1])); } else if (name == "left") { if (Val(parameters[2]) < 0) { this.LogASLError("Invalid function call in '$Left$(" + parameters[1] + "; " + parameters[2] + ")$'", LogType.WarningError); return "!"; } else { return Left(parameters[1], parseInt(parameters[2])); } } else if (name == "right") { if (Val(parameters[2]) < 0) { this.LogASLError("Invalid function call in '$Right$(" + parameters[1] + "; " + parameters[2] + ")$'", LogType.WarningError); return "!"; } else { return Right(parameters[1], parseInt(parameters[2])); } } else if (name == "mid") { if (numParameters == 3) { if (Val(parameters[2]) < 0) { this.LogASLError("Invalid function call in '$Mid$(" + parameters[1] + "; " + parameters[2] + "; " + parameters[3] + ")$'", LogType.WarningError); return "!"; } else { return Mid(parameters[1], parseInt(parameters[2]), parseInt(parameters[3])); } } else if (numParameters == 2) { if (Val(parameters[2]) < 0) { this.LogASLError("Invalid function call in '$Mid$(" + parameters[1] + "; " + parameters[2] + ")$'", LogType.WarningError); return "!"; } else { return Mid(parameters[1], parseInt(parameters[2])); } } this.LogASLError("Invalid function call to '$Mid$(...)$'", LogType.WarningError); return ""; } else if (name == "rand") { return Str(Math.random() * (parseFloat(parameters[2]) - parseFloat(parameters[1]) + 1) + parseFloat(parameters[1])); } else if (name == "instr") { if (numParameters == 3) { param3 = ""; if (InStr(parameters[3], "_") != 0) { for (var i = 1; i <= Len(parameters[3]); i++) { if (Mid(parameters[3], i, 1) == "_") { param3 = param3 + " "; } else { param3 = param3 + Mid(parameters[3], i, 1); } } } else { param3 = parameters[3]; } if (Val(parameters[1]) <= 0) { this.LogASLError("Invalid function call in '$instr(" + parameters[1] + "; " + parameters[2] + "; " + parameters[3] + ")$'", LogType.WarningError); return "!"; } else { return Trim(Str(InStrFrom(parseInt(parameters[1]), parameters[2], param3))); } } else if (numParameters == 2) { param2 = ""; if (InStr(parameters[2], "_") != 0) { for (var i = 1; i <= Len(parameters[2]); i++) { if (Mid(parameters[2], i, 1) == "_") { param2 = param2 + " "; } else { param2 = param2 + Mid(parameters[2], i, 1); } } } else { param2 = parameters[2]; } return Trim(Str(InStr(parameters[1], param2))); } this.LogASLError("Invalid function call to '$Instr$(...)$'", LogType.WarningError); return ""; } else if (name == "ucase") { return UCase(parameters[1]); } else if (name == "lcase") { return LCase(parameters[1]); } else if (name == "capfirst") { return UCase(Left(parameters[1], 1)) + Mid(parameters[1], 2); } else if (name == "symbol") { if (parameters[1] == "lt") { return "<"; } else if (parameters[1] == "gt") { return ">"; } else { return "!"; } } else if (name == "loadmethod") { return this._gameLoadMethod; } else if (name == "timerstate") { for (var i = 1; i <= this._numberTimers; i++) { if (LCase(this._timers[i].TimerName) == LCase(parameters[1])) { if (this._timers[i].TimerActive) { return "1"; } else { return "0"; } } } this.LogASLError("No such timer '" + parameters[1] + "'", LogType.WarningError); return "!"; } else if (name == "timerinterval") { for (var i = 1; i <= this._numberTimers; i++) { if (LCase(this._timers[i].TimerName) == LCase(parameters[1])) { return Str(this._timers[i].TimerInterval); } } this.LogASLError("No such timer '" + parameters[1] + "'", LogType.WarningError); return "!"; } else if (name == "ubound") { for (var i = 1; i <= this._numberNumericVariables; i++) { if (LCase(this._numericVariable[i].VariableName) == LCase(parameters[1])) { return Trim(Str(this._numericVariable[i].VariableUBound)); } } for (var i = 1; i <= this._numberStringVariables; i++) { if (LCase(this._stringVariable[i].VariableName) == LCase(parameters[1])) { return Trim(Str(this._stringVariable[i].VariableUBound)); } } this.LogASLError("No such variable '" + parameters[1] + "'", LogType.WarningError); return "!"; } else if (name == "objectproperty") { var FoundObj = false; for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ObjectName) == LCase(parameters[1])) { FoundObj = true; objId = i; i = this._numberObjs; } } if (!FoundObj) { this.LogASLError("No such object '" + parameters[1] + "'", LogType.WarningError); return "!"; } else { return this.GetObjectProperty(parameters[2], objId); } } else if (name == "getobjectname") { if (numParameters == 3) { objId = await this.Disambiguate(parameters[1], parameters[2] + ";" + parameters[3], ctx); } else if (numParameters == 2) { objId = await this.Disambiguate(parameters[1], parameters[2], ctx); } else { objId = await this.Disambiguate(parameters[1], this._currentRoom + ";inventory", ctx); } if (objId <= -1) { this.LogASLError("No object found with display name '" + parameters[1] + "'", LogType.WarningError); return "!"; } else { return this._objs[objId].ObjectName; } } else if (name == "thisobject") { return this._objs[ctx.CallingObjectId].ObjectName; } else if (name == "thisobjectname") { return this._objs[ctx.CallingObjectId].ObjectAlias; } else if (name == "speechenabled") { return "1"; } else if (name == "removeformatting") { return this.RemoveFormatting(parameter); } else if (name == "findexit" && this._gameAslVersion >= 410) { var e = this.FindExit(parameter); if (e == null) { return ""; } else { return this._objs[e.GetObjId()].ObjectName; } } return "__NOTDEFINED"; } async ExecFor(line: string, ctx: Context): Promise<void> { // See if this is a "for each" loop: if (this.BeginsWith(line, "each ")) { await this.ExecForEach(this.GetEverythingAfter(line, "each "), ctx); return; } // Executes a for loop, of form: // for <variable; startvalue; endvalue> script var endValue: number = 0; var stepValue: number = 0; var forData = await this.GetParameter(line, ctx); // Extract individual components: var scp1 = InStr(forData, ";"); var scp2 = InStrFrom(scp1 + 1, forData, ";"); var scp3 = InStrFrom(scp2 + 1, forData, ";"); var counterVariable = Trim(Left(forData, scp1 - 1)); var startValue = parseInt(Mid(forData, scp1 + 1, (scp2 - 1) - scp1)); if (scp3 != 0) { endValue = parseInt(Mid(forData, scp2 + 1, (scp3 - 1) - scp2)); stepValue = parseInt(Mid(forData, scp3 + 1)); } else { endValue = parseInt(Mid(forData, scp2 + 1)); stepValue = 1; } var loopScript = Trim(Mid(line, InStr(line, ">") + 1)); for (var i = startValue; stepValue > 0 ? i <= endValue : i >= endValue; i = i + stepValue) { await this.SetNumericVariableContents(counterVariable, i, ctx); await this.ExecuteScript(loopScript, ctx); i = this.GetNumericContents(counterVariable, ctx); } } async ExecSetVar(varInfo: string, ctx: Context): Promise<void> { // Sets variable contents from a script parameter. // Eg <var1;7> sets numeric variable var1 // to 7 var scp = InStr(varInfo, ";"); var varName = Trim(Left(varInfo, scp - 1)); var varCont = Trim(Mid(varInfo, scp + 1)); var idx = this.GetArrayIndex(varName, ctx); if (IsNumeric(idx.Name)) { this.LogASLError("Invalid numeric variable name '" + idx.Name + "' - variable names cannot be numeric", LogType.WarningError); return; } try { if (this._gameAslVersion >= 391) { var expResult = this.ExpressionHandler(varCont); if (expResult.Success == ExpressionSuccess.OK) { varCont = expResult.Result; } else { varCont = "0"; this.LogASLError("Error setting numeric variable <" + varInfo + "> : " + expResult.Message, LogType.WarningError); } } else { var obscuredVarInfo = this.ObscureNumericExps(varCont); var opPos = InStr(obscuredVarInfo, "+"); if (opPos == 0) { opPos = InStr(obscuredVarInfo, "*"); } if (opPos == 0) { opPos = InStr(obscuredVarInfo, "/"); } if (opPos == 0) { opPos = InStrFrom(2, obscuredVarInfo, "-"); } if (opPos != 0) { var op = Mid(varCont, opPos, 1); var num1 = Val(Left(varCont, opPos - 1)); var num2 = Val(Mid(varCont, opPos + 1)); switch (op) { case "+": varCont = Str(num1 + num2); break; case "-": varCont = Str(num1 - num2); break; case "*": varCont = Str(num1 * num2); break; case "/": if (num2 != 0) { varCont = Str(num1 / num2); } else { this.LogASLError("Division by zero - The result of this operation has been set to zero.", LogType.WarningError); varCont = "0"; } break; } } } await this.SetNumericVariableContents(idx.Name, Val(varCont), ctx, idx.Index); } catch (e) { this.LogASLError("Error setting variable '" + idx.Name + "' to '" + varCont + "'", LogType.WarningError); } } ExecuteIfGot(item: string): boolean { if (this._gameAslVersion >= 280) { for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ObjectName) == LCase(item)) { return this._objs[i].ContainerRoom == "inventory" && this._objs[i].Exists; } } this.LogASLError("No object '" + item + "' defined.", LogType.WarningError); return false; } for (var i = 1; i <= this._numberItems; i++) { if (LCase(this._items[i].Name) == LCase(item)) { return this._items[i].Got; } } this.LogASLError("Item '" + item + "' not defined.", LogType.WarningError); return false; } ExecuteIfHas(condition: string): boolean { var checkValue: number = 0; var colNum: number = 0; var scp = InStr(condition, ";"); var name = Trim(Left(condition, scp - 1)); var newVal = Trim(Right(condition, Len(condition) - scp)); var found = false; for (var i = 1; i <= this._numCollectables; i++) { if (this._collectables[i].Name == name) { colNum = i; found = true; break; } } if (!found) { this.LogASLError("No such collectable in " + condition, LogType.WarningError); return false; } var op = Left(newVal, 1); var newValue = Trim(Right(newVal, Len(newVal) - 1)); if (IsNumeric(newValue)) { checkValue = Val(newValue); } else { checkValue = this.GetCollectableAmount(newValue); } if (op == "+") { return this._collectables[colNum].Value > checkValue; } else if (op == "-") { return this._collectables[colNum].Value < checkValue; } else if (op == "=") { return this._collectables[colNum].Value == checkValue; } return false; } ExecuteIfIs(condition: string): boolean { var value1: string; var value2: string; var op: string; var expectNumerics: boolean = false; var expResult: ExpressionResult; var scp = InStr(condition, ";"); if (scp == 0) { this.LogASLError("Expected second parameter in 'is " + condition + "'", LogType.WarningError); return false; } var scp2 = InStrFrom(scp + 1, condition, ";"); if (scp2 == 0) { // Only two parameters => standard "=" op = "="; value1 = Trim(Left(condition, scp - 1)); value2 = Trim(Mid(condition, scp + 1)); } else { value1 = Trim(Left(condition, scp - 1)); op = Trim(Mid(condition, scp + 1, (scp2 - scp) - 1)); value2 = Trim(Mid(condition, scp2 + 1)); } if (this._gameAslVersion >= 391) { // Evaluate expressions in Value1 and Value2 expResult = this.ExpressionHandler(value1); if (expResult.Success == ExpressionSuccess.OK) { value1 = expResult.Result; } expResult = this.ExpressionHandler(value2); if (expResult.Success == ExpressionSuccess.OK) { value2 = expResult.Result; } } var result = false; switch (op) { case "=": if (LCase(value1) == LCase(value2)) { result = true; } expectNumerics = false; break; case "!=": if (LCase(value1) != LCase(value2)) { result = true; } expectNumerics = false; break; case "gt": if (Val(value1) > Val(value2)) { result = true; } expectNumerics = true; break; case "lt": if (Val(value1) < Val(value2)) { result = true; } expectNumerics = true; break; case "gt=": if (Val(value1) >= Val(value2)) { result = true; } expectNumerics = true; break; case "lt=": if (Val(value1) <= Val(value2)) { result = true; } expectNumerics = true; break; default: this.LogASLError("Unrecognised comparison condition in 'is " + condition + "'", LogType.WarningError); break; } if (expectNumerics) { if (!(IsNumeric(value1) && IsNumeric(value2))) { this.LogASLError("Expected numeric comparison comparing '" + value1 + "' and '" + value2 + "'", LogType.WarningError); } } return result; } GetNumericContents(name: string, ctx: Context, noError: boolean = false): number { var numNumber: number = 0; var arrayIndex: number = 0; var exists = false; // First, see if the variable already exists. If it // does, get its contents. If not, generate an error. if (InStr(name, "[") != 0 && InStr(name, "]") != 0) { var op = InStr(name, "["); var cp = InStr(name, "]"); var arrayIndexData = Mid(name, op + 1, (cp - op) - 1); if (IsNumeric(arrayIndexData)) { arrayIndex = parseInt(arrayIndexData); } else { arrayIndex = this.GetNumericContents(arrayIndexData, ctx); } name = Left(name, op - 1); } else { arrayIndex = 0; } if (this._numberNumericVariables > 0) { for (var i = 1; i <= this._numberNumericVariables; i++) { if (LCase(this._numericVariable[i].VariableName) == LCase(name)) { numNumber = i; exists = true; break; } } } if (!exists) { if (!noError) { this.LogASLError("No numeric variable '" + name + "' defined.", LogType.WarningError); } return -32767; } if (arrayIndex > this._numericVariable[numNumber].VariableUBound) { if (!noError) { this.LogASLError("Array index of '" + name + "[" + Trim(Str(arrayIndex)) + "]' too big.", LogType.WarningError); } return -32766; } // Now, set the contents return Val(this._numericVariable[numNumber].VariableContents[arrayIndex]); } async PlayerErrorMessage(e: PlayerError, ctx: Context): Promise<void> { await this.Print(await this.GetErrorMessage(e, ctx), ctx); } async PlayerErrorMessage_ExtendInfo(e: PlayerError, ctx: Context, extraInfo: string): Promise<void> { var message = await this.GetErrorMessage(e, ctx); if (extraInfo != "") { if (Right(message, 1) == ".") { message = Left(message, Len(message) - 1); } message = message + " - " + extraInfo + "."; } await this.Print(message, ctx); } async GetErrorMessage(e: PlayerError, ctx: Context): Promise<string> { return await this.ConvertParameter( await this.ConvertParameter( await this.ConvertParameter(this._playerErrorMessageString[e], "%", ConvertType.Numeric, ctx), "$", ConvertType.Functions, ctx), "#", ConvertType.Strings, ctx); } PlayMedia(filename: string, sync: boolean = false, looped: boolean = false): void { if (filename.length == 0) { this._player.StopSound(); //TODO: Handle sync parameter } else { if (looped && sync) { sync = false; } // Can't loop and sync at the same time, that would just hang! this._player.PlaySound(filename, sync, looped); } } PlayWav(parameter: string): void { var params: string[] = parameter.split(";").map(function (p) { return p.trim(); }); var filename = params[0]; var looped = (params.indexOf("loop") != -1); var sync = (params.indexOf("sync") != -1); if (filename.length > 0 && InStr(filename, ".") == 0) { filename = filename + ".wav"; } this.PlayMedia(filename, sync, looped); } async RestoreGameData(fileData: string): Promise<void> { var appliesTo: string; var data: string = ""; var objId: number = 0; var timerNum: number = 0; var varUbound: number = 0; var found: boolean = false; var numStoredData: number = 0; var storedData: ChangeType[] = []; var decryptedFile: string[] = []; // Decrypt file for (var i = 1; i <= Len(fileData); i++) { decryptedFile.push(Chr(255 - Asc(Mid(fileData, i, 1)))); } this._fileData = decryptedFile.join(""); this._currentRoom = this.GetNextChunk(); // OBJECTS var numData = parseInt(this.GetNextChunk()); var createdObjects: string[] = []; for (var i = 1; i <= numData; i++) { appliesTo = this.GetNextChunk(); data = this.GetNextChunk(); // As of Quest 4.0, properties and actions are put into StoredData while we load the file, // and then processed later. This is so any created rooms pick up their properties - otherwise // we try to set them before they've been created. if (this.BeginsWith(data, "properties ") || this.BeginsWith(data, "action ")) { numStoredData = numStoredData + 1; if (!storedData) storedData = []; storedData[numStoredData] = new ChangeType(); storedData[numStoredData].AppliesTo = appliesTo; storedData[numStoredData].Change = data; } else if (this.BeginsWith(data, "create ")) { var createData: string = appliesTo + ";" + this.GetEverythingAfter(data, "create "); // workaround bug where duplicate "create" entries appear in the restore data if (createdObjects.indexOf(createData) == -1) { await this.ExecuteCreate("object <" + createData + ">", this._nullContext); createdObjects.push(createData); } } else { this.LogASLError("QSG Error: Unrecognised item '" + appliesTo + "; " + data + "'", LogType.InternalError); } } numData = parseInt(this.GetNextChunk()); for (var i = 1; i <= numData; i++) { appliesTo = this.GetNextChunk(); data = this.GetFileDataChars(2); objId = this.GetObjectIdNoAlias(appliesTo); if (Left(data, 1) == Chr(1)) { this._objs[objId].Exists = true; } else { this._objs[objId].Exists = false; } if (Right(data, 1) == Chr(1)) { this._objs[objId].Visible = true; } else { this._objs[objId].Visible = false; } this._objs[objId].ContainerRoom = this.GetNextChunk(); } // ROOMS numData = parseInt(this.GetNextChunk()); for (var i = 1; i <= numData; i++) { appliesTo = this.GetNextChunk(); data = this.GetNextChunk(); if (this.BeginsWith(data, "exit ")) { await this.ExecuteCreate(data, this._nullContext); } else if (data == "create") { await this.ExecuteCreate("room <" + appliesTo + ">", this._nullContext); } else if (this.BeginsWith(data, "destroy exit ")) { await this.DestroyExit(appliesTo + "; " + this.GetEverythingAfter(data, "destroy exit "), this._nullContext); } } // Now go through and apply object properties and actions for (var i = 1; i <= numStoredData; i++) { var d = storedData[i]; if (this.BeginsWith(d.Change, "properties ")) { this.AddToObjectProperties(this.GetEverythingAfter(d.Change, "properties "), this.GetObjectIdNoAlias(d.AppliesTo), this._nullContext); } else if (this.BeginsWith(d.Change, "action ")) { this.AddToObjectActions(this.GetEverythingAfter(d.Change, "action "), this.GetObjectIdNoAlias(d.AppliesTo)); } } // TIMERS numData = parseInt(this.GetNextChunk()); for (var i = 1; i <= numData; i++) { found = false; appliesTo = this.GetNextChunk(); for (var j = 1; j <= this._numberTimers; j++) { if (this._timers[j].TimerName == appliesTo) { timerNum = j; found = true; break; } } if (found) { var t = this._timers[timerNum]; var thisChar: string = this.GetFileDataChars(1); if (thisChar == Chr(1)) { t.TimerActive = true; } else { t.TimerActive = false; } t.TimerInterval = parseInt(this.GetNextChunk()); t.TimerTicks = parseInt(this.GetNextChunk()); } } // STRING VARIABLES // Set this flag so we don't run any status variable onchange scripts while restoring this._gameIsRestoring = true; numData = parseInt(this.GetNextChunk()); for (var i = 1; i <= numData; i++) { appliesTo = this.GetNextChunk(); varUbound = parseInt(this.GetNextChunk()); if (varUbound == 0) { data = this.GetNextChunk(); await this.SetStringContents(appliesTo, data, this._nullContext); } else { for (var j = 0; j <= varUbound; j++) { data = this.GetNextChunk(); await this.SetStringContents(appliesTo, data, this._nullContext, j); } } } // NUMERIC VARIABLES numData = parseInt(this.GetNextChunk()); for (var i = 1; i <= numData; i++) { appliesTo = this.GetNextChunk(); varUbound = parseInt(this.GetNextChunk()); if (varUbound == 0) { data = this.GetNextChunk(); await this.SetNumericVariableContents(appliesTo, Val(data), this._nullContext); } else { for (var j = 0; j <= varUbound; j++) { data = this.GetNextChunk(); await this.SetNumericVariableContents(appliesTo, Val(data), this._nullContext, j); } } } this._gameIsRestoring = false; } SetBackground(col: string): void { this._player.SetBackground("#" + this.GetHTMLColour(col, "white")); } SetForeground(col: string): void { this._player.SetForeground("#" + this.GetHTMLColour(col, "black")); } SetDefaultPlayerErrorMessages(): void { this._playerErrorMessageString[PlayerError.BadCommand] = "I don't understand your command. Type HELP for a list of valid commands."; this._playerErrorMessageString[PlayerError.BadGo] = "I don't understand your use of 'GO' - you must either GO in some direction, or GO TO a place."; this._playerErrorMessageString[PlayerError.BadGive] = "You didn't say who you wanted to give that to."; this._playerErrorMessageString[PlayerError.BadCharacter] = "I can't see anybody of that name here."; this._playerErrorMessageString[PlayerError.NoItem] = "You don't have that."; this._playerErrorMessageString[PlayerError.ItemUnwanted] = "#quest.error.gender# doesn't want #quest.error.article#."; this._playerErrorMessageString[PlayerError.BadLook] = "You didn't say what you wanted to look at."; this._playerErrorMessageString[PlayerError.BadThing] = "I can't see that here."; this._playerErrorMessageString[PlayerError.DefaultLook] = "Nothing out of the ordinary."; this._playerErrorMessageString[PlayerError.DefaultSpeak] = "#quest.error.gender# says nothing."; this._playerErrorMessageString[PlayerError.BadItem] = "I can't see that anywhere."; this._playerErrorMessageString[PlayerError.DefaultTake] = "You pick #quest.error.article# up."; this._playerErrorMessageString[PlayerError.BadUse] = "You didn't say what you wanted to use that on."; this._playerErrorMessageString[PlayerError.DefaultUse] = "You can't use that here."; this._playerErrorMessageString[PlayerError.DefaultOut] = "There's nowhere you can go out to around here."; this._playerErrorMessageString[PlayerError.BadPlace] = "You can't go there."; this._playerErrorMessageString[PlayerError.DefaultExamine] = "Nothing out of the ordinary."; this._playerErrorMessageString[PlayerError.BadTake] = "You can't take #quest.error.article#."; this._playerErrorMessageString[PlayerError.CantDrop] = "You can't drop that here."; this._playerErrorMessageString[PlayerError.DefaultDrop] = "You drop #quest.error.article#."; this._playerErrorMessageString[PlayerError.BadDrop] = "You are not carrying such a thing."; this._playerErrorMessageString[PlayerError.BadPronoun] = "I don't know what '#quest.error.pronoun#' you are referring to."; this._playerErrorMessageString[PlayerError.BadExamine] = "You didn't say what you wanted to examine."; this._playerErrorMessageString[PlayerError.AlreadyOpen] = "It is already open."; this._playerErrorMessageString[PlayerError.AlreadyClosed] = "It is already closed."; this._playerErrorMessageString[PlayerError.CantOpen] = "You can't open that."; this._playerErrorMessageString[PlayerError.CantClose] = "You can't close that."; this._playerErrorMessageString[PlayerError.DefaultOpen] = "You open it."; this._playerErrorMessageString[PlayerError.DefaultClose] = "You close it."; this._playerErrorMessageString[PlayerError.BadPut] = "You didn't specify what you wanted to put #quest.error.article# on or in."; this._playerErrorMessageString[PlayerError.CantPut] = "You can't put that there."; this._playerErrorMessageString[PlayerError.DefaultPut] = "Done."; this._playerErrorMessageString[PlayerError.CantRemove] = "You can't remove that."; this._playerErrorMessageString[PlayerError.AlreadyPut] = "It is already there."; this._playerErrorMessageString[PlayerError.DefaultRemove] = "Done."; this._playerErrorMessageString[PlayerError.Locked] = "The exit is locked."; this._playerErrorMessageString[PlayerError.DefaultWait] = "Press a key to continue..."; this._playerErrorMessageString[PlayerError.AlreadyTaken] = "You already have that."; } SetFont(name: string): void { if (name == "") { name = this._defaultFontName; } this._player.SetFont(name); } async SetNumericVariableContents(name: string, content: number, ctx: Context, arrayIndex: number = 0): Promise<void> { var numNumber: number = 0; var exists = false; if (IsNumeric(name)) { this.LogASLError("Illegal numeric variable name '" + name + "' - check you didn't put % around the variable name in the ASL code", LogType.WarningError); return; } // First, see if variable already exists. If it does, // modify it. If not, create it. if (this._numberNumericVariables > 0) { for (var i = 1; i <= this._numberNumericVariables; i++) { if (LCase(this._numericVariable[i].VariableName) == LCase(name)) { numNumber = i; exists = true; break; } } } if (!exists) { this._numberNumericVariables = this._numberNumericVariables + 1; numNumber = this._numberNumericVariables; if (!this._numericVariable) this._numericVariable = []; this._numericVariable[numNumber] = new VariableType(); this._numericVariable[numNumber].VariableUBound = arrayIndex; } if (arrayIndex > this._numericVariable[numNumber].VariableUBound) { if (!this._numericVariable[numNumber].VariableContents) this._numericVariable[numNumber].VariableContents = []; this._numericVariable[numNumber].VariableUBound = arrayIndex; } // Now, set the contents this._numericVariable[numNumber].VariableName = name; if (!this._numericVariable[numNumber].VariableContents) this._numericVariable[numNumber].VariableContents = []; this._numericVariable[numNumber].VariableContents[arrayIndex] = (content).toString(); if (this._numericVariable[numNumber].OnChangeScript != "" && !this._gameIsRestoring) { var script = this._numericVariable[numNumber].OnChangeScript; await this.ExecuteScript(script, ctx); } if (this._numericVariable[numNumber].DisplayString != "") { await this.UpdateStatusVars(ctx); } } async SetOpenClose(name: string, open: boolean, ctx: Context): Promise<void> { var cmd: string; if (open) { cmd = "open"; } else { cmd = "close"; } var id = this.GetObjectIdNoAlias(name); if (id == 0) { this.LogASLError("Invalid object name specified in '" + cmd + " <" + name + ">", LogType.WarningError); return; } await this.DoOpenClose(id, open, false, ctx); } SetTimerState(name: string, state: boolean): void { for (var i = 1; i <= this._numberTimers; i++) { if (LCase(name) == LCase(this._timers[i].TimerName)) { this._timers[i].TimerActive = state; this._timers[i].BypassThisTurn = true; // don't trigger timer during the turn it was first enabled return null; } } this.LogASLError("No such timer '" + name + "'", LogType.WarningError); } async SetUnknownVariableType(variableData: string, ctx: Context): Promise<SetResult> { var scp = InStr(variableData, ";"); if (scp == 0) { return SetResult.Error; } var name = Trim(Left(variableData, scp - 1)); if (InStr(name, "[") != 0 && InStr(name, "]") != 0) { var pos = InStr(name, "["); name = Left(name, pos - 1); } for (var i = 1; i <= this._numberStringVariables; i++) { if (LCase(this._stringVariable[i].VariableName) == LCase(name)) { await this.ExecSetString(variableData, ctx); return SetResult.Found; } } for (var i = 1; i <= this._numberNumericVariables; i++) { if (LCase(this._numericVariable[i].VariableName) == LCase(name)) { await this.ExecSetVar(variableData, ctx); return SetResult.Found; } } for (var i = 1; i <= this._numCollectables; i++) { if (LCase(this._collectables[i].Name) == LCase(name)) { this.ExecuteSetCollectable(variableData, ctx); return SetResult.Found; } } return SetResult.Unfound; } async SetUpChoiceForm(blockName: string, ctx: Context): Promise<string> { // Returns script to execute from choice block var block = this.DefineBlockParam("selection", blockName); var prompt = this.FindStatement(block, "info"); var menuOptions: StringDictionary = {}; var menuScript: StringDictionary = {}; for (var i = block.StartLine + 1; i <= block.EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], "choice ")) { menuOptions[i.toString()] = await this.GetParameter(this._lines[i], ctx); menuScript[i.toString()] = Trim(Right(this._lines[i], Len(this._lines[i]) - InStr(this._lines[i], ">"))); } } await this.Print("- |i" + prompt + "|xi", ctx); var mnu: MenuData = new MenuData(prompt, menuOptions, false); var choice: string = await this.ShowMenu(mnu); await this.Print("- " + menuOptions[choice] + "|n", ctx); return menuScript[choice]; } SetUpDefaultFonts(): void { // Sets up default fonts var gameblock = this.GetDefineBlock("game"); this._defaultFontName = "Arial"; this._defaultFontSize = 9; for (var i = gameblock.StartLine + 1; i <= gameblock.EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], "default fontname ")) { var name = this.GetSimpleParameter(this._lines[i]); if (name != "") { this._defaultFontName = name; } } else if (this.BeginsWith(this._lines[i], "default fontsize ")) { var size = parseInt(this.GetSimpleParameter(this._lines[i])); if (size != 0) { this._defaultFontSize = size; } } } } SetUpDisplayVariables() { for (var i = this.GetDefineBlock("game").StartLine + 1; i <= this.GetDefineBlock("game").EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], "define variable ")) { var variable = new VariableType(); variable.VariableContents = []; variable.VariableName = this.GetSimpleParameter(this._lines[i]); variable.DisplayString = ""; variable.NoZeroDisplay = false; variable.OnChangeScript = ""; variable.VariableContents[0] = ""; variable.VariableUBound = 0; var type = "numeric"; do { i = i + 1; if (this.BeginsWith(this._lines[i], "type ")) { type = this.GetEverythingAfter(this._lines[i], "type "); if (type != "string" && type != "numeric") { this.LogASLError("Unrecognised variable type in variable '" + variable.VariableName + "' - type '" + type + "'", LogType.WarningError); break; } } else if (this.BeginsWith(this._lines[i], "onchange ")) { variable.OnChangeScript = this.GetEverythingAfter(this._lines[i], "onchange "); } else if (this.BeginsWith(this._lines[i], "display ")) { var displayString = this.GetEverythingAfter(this._lines[i], "display "); if (this.BeginsWith(displayString, "nozero ")) { variable.NoZeroDisplay = true; } variable.DisplayString = this.GetSimpleParameter(this._lines[i]); } else if (this.BeginsWith(this._lines[i], "value ")) { variable.VariableContents[0] = this.GetSimpleParameter(this._lines[i]); } } while (!(Trim(this._lines[i]) == "end define")); if (type == "string") { // Create string variable this._numberStringVariables = this._numberStringVariables + 1; var id = this._numberStringVariables; if (!this._stringVariable) this._stringVariable = []; this._stringVariable[id] = variable; this._numDisplayStrings = this._numDisplayStrings + 1; } else if (type == "numeric") { if (variable.VariableContents[0] == "") { variable.VariableContents[0] = (0).toString(); } this._numberNumericVariables = this._numberNumericVariables + 1; var iNumNumber = this._numberNumericVariables; if (!this._numericVariable) this._numericVariable = []; this._numericVariable[iNumNumber] = variable; this._numDisplayNumerics = this._numDisplayNumerics + 1; } } } } SetUpGameObject(): void { this._numberObjs = 1; this._objs = []; this._objs[1] = new ObjectType(); var o = this._objs[1]; o.ObjectName = "game"; o.ObjectAlias = ""; o.Visible = false; o.Exists = true; var nestBlock = 0; for (var i = this.GetDefineBlock("game").StartLine + 1; i <= this.GetDefineBlock("game").EndLine - 1; i++) { if (nestBlock == 0) { if (this.BeginsWith(this._lines[i], "define ")) { nestBlock = nestBlock + 1; } else if (this.BeginsWith(this._lines[i], "properties ")) { this.AddToObjectProperties(this.GetSimpleParameter(this._lines[i]), this._numberObjs, this._nullContext); } else if (this.BeginsWith(this._lines[i], "type ")) { o.NumberTypesIncluded = o.NumberTypesIncluded + 1; if (!o.TypesIncluded) o.TypesIncluded = []; o.TypesIncluded[o.NumberTypesIncluded] = this.GetSimpleParameter(this._lines[i]); var propertyData = this.GetPropertiesInType(this.GetSimpleParameter(this._lines[i])); this.AddToObjectProperties(propertyData.Properties, this._numberObjs, this._nullContext); for (var k = 1; k <= propertyData.NumberActions; k++) { this.AddObjectAction(this._numberObjs, propertyData.Actions[k].ActionName, propertyData.Actions[k].Script); } } else if (this.BeginsWith(this._lines[i], "action ")) { this.AddToObjectActions(this.GetEverythingAfter(this._lines[i], "action "), this._numberObjs); } } else { if (Trim(this._lines[i]) == "end define") { nestBlock = nestBlock - 1; } } } } SetUpOptions(): void { var opt: string; for (var i = this.GetDefineBlock("options").StartLine + 1; i <= this.GetDefineBlock("options").EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], "panes ")) { opt = LCase(Trim(this.GetEverythingAfter(this._lines[i], "panes "))); this._player.SetPanesVisible(opt); } else if (this.BeginsWith(this._lines[i], "abbreviations ")) { opt = LCase(Trim(this.GetEverythingAfter(this._lines[i], "abbreviations "))); if (opt == "off") { this._useAbbreviations = false; } else { this._useAbbreviations = true; } } } } SetUpRoomData(): void { var defaultProperties: PropertiesActions = new PropertiesActions(); // see if define type <defaultroom> exists: var defaultExists = false; for (var i = 1; i <= this._numberSections; i++) { if (Trim(this._lines[this._defineBlocks[i].StartLine]) == "define type <defaultroom>") { defaultExists = true; defaultProperties = this.GetPropertiesInType("defaultroom"); break; } } for (var i = 1; i <= this._numberSections; i++) { if (this.BeginsWith(this._lines[this._defineBlocks[i].StartLine], "define room ")) { this._numberRooms = this._numberRooms + 1; if (!this._rooms) this._rooms = []; this._rooms[this._numberRooms] = new RoomType(); this._numberObjs = this._numberObjs + 1; if (!this._objs) this._objs = []; this._objs[this._numberObjs] = new ObjectType(); var r = this._rooms[this._numberRooms]; r.RoomName = this.GetSimpleParameter(this._lines[this._defineBlocks[i].StartLine]); this._objs[this._numberObjs].ObjectName = r.RoomName; this._objs[this._numberObjs].IsRoom = true; this._objs[this._numberObjs].CorresRoom = r.RoomName; this._objs[this._numberObjs].CorresRoomId = this._numberRooms; r.ObjId = this._numberObjs; if (this._gameAslVersion >= 410) { r.Exits = new RoomExits(this); r.Exits.SetObjId(r.ObjId); } if (defaultExists) { this.AddToObjectProperties(defaultProperties.Properties, this._numberObjs, this._nullContext); for (var k = 1; k <= defaultProperties.NumberActions; k++) { this.AddObjectAction(this._numberObjs, defaultProperties.Actions[k].ActionName, defaultProperties.Actions[k].Script); } } for (var j = this._defineBlocks[i].StartLine + 1; j <= this._defineBlocks[i].EndLine - 1; j++) { if (this.BeginsWith(this._lines[j], "define ")) { //skip nested blocks var nestedBlock = 1; do { j = j + 1; if (this.BeginsWith(this._lines[j], "define ")) { nestedBlock = nestedBlock + 1; } else if (Trim(this._lines[j]) == "end define") { nestedBlock = nestedBlock - 1; } } while (!(nestedBlock == 0)); } if (this._gameAslVersion >= 280 && this.BeginsWith(this._lines[j], "alias ")) { r.RoomAlias = this.GetSimpleParameter(this._lines[j]); this._objs[this._numberObjs].ObjectAlias = r.RoomAlias; if (this._gameAslVersion >= 350) { this.AddToObjectProperties("alias=" + r.RoomAlias, this._numberObjs, this._nullContext); } } else if (this._gameAslVersion >= 280 && this.BeginsWith(this._lines[j], "description ")) { r.Description = this.GetTextOrScript(this.GetEverythingAfter(this._lines[j], "description ")); if (this._gameAslVersion >= 350) { if (r.Description.Type == TextActionType.Script) { this.AddObjectAction(this._numberObjs, "description", r.Description.Data); } else { this.AddToObjectProperties("description=" + r.Description.Data, this._numberObjs, this._nullContext); } } } else if (this.BeginsWith(this._lines[j], "out ")) { r.Out.Text = this.GetSimpleParameter(this._lines[j]); r.Out.Script = Trim(Mid(this._lines[j], InStr(this._lines[j], ">") + 1)); if (this._gameAslVersion >= 350) { if (r.Out.Script != "") { this.AddObjectAction(this._numberObjs, "out", r.Out.Script); } this.AddToObjectProperties("out=" + r.Out.Text, this._numberObjs, this._nullContext); } } else if (this.BeginsWith(this._lines[j], "east ")) { r.East = this.GetTextOrScript(this.GetEverythingAfter(this._lines[j], "east ")); if (this._gameAslVersion >= 350) { if (r.East.Type == TextActionType.Script) { this.AddObjectAction(this._numberObjs, "east", r.East.Data); } else { this.AddToObjectProperties("east=" + r.East.Data, this._numberObjs, this._nullContext); } } } else if (this.BeginsWith(this._lines[j], "west ")) { r.West = this.GetTextOrScript(this.GetEverythingAfter(this._lines[j], "west ")); if (this._gameAslVersion >= 350) { if (r.West.Type == TextActionType.Script) { this.AddObjectAction(this._numberObjs, "west", r.West.Data); } else { this.AddToObjectProperties("west=" + r.West.Data, this._numberObjs, this._nullContext); } } } else if (this.BeginsWith(this._lines[j], "north ")) { r.North = this.GetTextOrScript(this.GetEverythingAfter(this._lines[j], "north ")); if (this._gameAslVersion >= 350) { if (r.North.Type == TextActionType.Script) { this.AddObjectAction(this._numberObjs, "north", r.North.Data); } else { this.AddToObjectProperties("north=" + r.North.Data, this._numberObjs, this._nullContext); } } } else if (this.BeginsWith(this._lines[j], "south ")) { r.South = this.GetTextOrScript(this.GetEverythingAfter(this._lines[j], "south ")); if (this._gameAslVersion >= 350) { if (r.South.Type == TextActionType.Script) { this.AddObjectAction(this._numberObjs, "south", r.South.Data); } else { this.AddToObjectProperties("south=" + r.South.Data, this._numberObjs, this._nullContext); } } } else if (this.BeginsWith(this._lines[j], "northeast ")) { r.NorthEast = this.GetTextOrScript(this.GetEverythingAfter(this._lines[j], "northeast ")); if (this._gameAslVersion >= 350) { if (r.NorthEast.Type == TextActionType.Script) { this.AddObjectAction(this._numberObjs, "northeast", r.NorthEast.Data); } else { this.AddToObjectProperties("northeast=" + r.NorthEast.Data, this._numberObjs, this._nullContext); } } } else if (this.BeginsWith(this._lines[j], "northwest ")) { r.NorthWest = this.GetTextOrScript(this.GetEverythingAfter(this._lines[j], "northwest ")); if (this._gameAslVersion >= 350) { if (r.NorthWest.Type == TextActionType.Script) { this.AddObjectAction(this._numberObjs, "northwest", r.NorthWest.Data); } else { this.AddToObjectProperties("northwest=" + r.NorthWest.Data, this._numberObjs, this._nullContext); } } } else if (this.BeginsWith(this._lines[j], "southeast ")) { r.SouthEast = this.GetTextOrScript(this.GetEverythingAfter(this._lines[j], "southeast ")); if (this._gameAslVersion >= 350) { if (r.SouthEast.Type == TextActionType.Script) { this.AddObjectAction(this._numberObjs, "southeast", r.SouthEast.Data); } else { this.AddToObjectProperties("southeast=" + r.SouthEast.Data, this._numberObjs, this._nullContext); } } } else if (this.BeginsWith(this._lines[j], "southwest ")) { r.SouthWest = this.GetTextOrScript(this.GetEverythingAfter(this._lines[j], "southwest ")); if (this._gameAslVersion >= 350) { if (r.SouthWest.Type == TextActionType.Script) { this.AddObjectAction(this._numberObjs, "southwest", r.SouthWest.Data); } else { this.AddToObjectProperties("southwest=" + r.SouthWest.Data, this._numberObjs, this._nullContext); } } } else if (this.BeginsWith(this._lines[j], "up ")) { r.Up = this.GetTextOrScript(this.GetEverythingAfter(this._lines[j], "up ")); if (this._gameAslVersion >= 350) { if (r.Up.Type == TextActionType.Script) { this.AddObjectAction(this._numberObjs, "up", r.Up.Data); } else { this.AddToObjectProperties("up=" + r.Up.Data, this._numberObjs, this._nullContext); } } } else if (this.BeginsWith(this._lines[j], "down ")) { r.Down = this.GetTextOrScript(this.GetEverythingAfter(this._lines[j], "down ")); if (this._gameAslVersion >= 350) { if (r.Down.Type == TextActionType.Script) { this.AddObjectAction(this._numberObjs, "down", r.Down.Data); } else { this.AddToObjectProperties("down=" + r.Down.Data, this._numberObjs, this._nullContext); } } } else if (this._gameAslVersion >= 280 && this.BeginsWith(this._lines[j], "indescription ")) { r.InDescription = this.GetSimpleParameter(this._lines[j]); if (this._gameAslVersion >= 350) { this.AddToObjectProperties("indescription=" + r.InDescription, this._numberObjs, this._nullContext); } } else if (this._gameAslVersion >= 280 && this.BeginsWith(this._lines[j], "look ")) { r.Look = this.GetSimpleParameter(this._lines[j]); if (this._gameAslVersion >= 350) { this.AddToObjectProperties("look=" + r.Look, this._numberObjs, this._nullContext); } } else if (this.BeginsWith(this._lines[j], "prefix ")) { r.Prefix = this.GetSimpleParameter(this._lines[j]); if (this._gameAslVersion >= 350) { this.AddToObjectProperties("prefix=" + r.Prefix, this._numberObjs, this._nullContext); } } else if (this.BeginsWith(this._lines[j], "script ")) { r.Script = this.GetEverythingAfter(this._lines[j], "script "); this.AddObjectAction(this._numberObjs, "script", r.Script); } else if (this.BeginsWith(this._lines[j], "command ")) { r.NumberCommands = r.NumberCommands + 1; if (!r.Commands) r.Commands = []; r.Commands[r.NumberCommands] = new UserDefinedCommandType(); r.Commands[r.NumberCommands].CommandText = this.GetSimpleParameter(this._lines[j]); r.Commands[r.NumberCommands].CommandScript = Trim(Mid(this._lines[j], InStr(this._lines[j], ">") + 1)); } else if (this.BeginsWith(this._lines[j], "place ")) { r.NumberPlaces = r.NumberPlaces + 1; if (!r.Places) r.Places = []; r.Places[r.NumberPlaces] = new PlaceType(); var placeData = this.GetSimpleParameter(this._lines[j]); var scp = InStr(placeData, ";"); if (scp == 0) { r.Places[r.NumberPlaces].PlaceName = placeData; } else { r.Places[r.NumberPlaces].PlaceName = Trim(Mid(placeData, scp + 1)); r.Places[r.NumberPlaces].Prefix = Trim(Left(placeData, scp - 1)); } r.Places[r.NumberPlaces].Script = Trim(Mid(this._lines[j], InStr(this._lines[j], ">") + 1)); } else if (this.BeginsWith(this._lines[j], "use ")) { r.NumberUse = r.NumberUse + 1; if (!r.Use) r.Use = []; r.Use[r.NumberUse] = new ScriptText(); r.Use[r.NumberUse].Text = this.GetSimpleParameter(this._lines[j]); r.Use[r.NumberUse].Script = Trim(Mid(this._lines[j], InStr(this._lines[j], ">") + 1)); } else if (this.BeginsWith(this._lines[j], "properties ")) { this.AddToObjectProperties(this.GetSimpleParameter(this._lines[j]), this._numberObjs, this._nullContext); } else if (this.BeginsWith(this._lines[j], "type ")) { this._objs[this._numberObjs].NumberTypesIncluded = this._objs[this._numberObjs].NumberTypesIncluded + 1; if (!this._objs[this._numberObjs].TypesIncluded) this._objs[this._numberObjs].TypesIncluded = []; this._objs[this._numberObjs].TypesIncluded[this._objs[this._numberObjs].NumberTypesIncluded] = this.GetSimpleParameter(this._lines[j]); var propertyData = this.GetPropertiesInType(this.GetSimpleParameter(this._lines[j])); this.AddToObjectProperties(propertyData.Properties, this._numberObjs, this._nullContext); for (var k = 1; k <= propertyData.NumberActions; k++) { this.AddObjectAction(this._numberObjs, propertyData.Actions[k].ActionName, propertyData.Actions[k].Script); } } else if (this.BeginsWith(this._lines[j], "action ")) { this.AddToObjectActions(this.GetEverythingAfter(this._lines[j], "action "), this._numberObjs); } else if (this.BeginsWith(this._lines[j], "beforeturn ")) { r.BeforeTurnScript = r.BeforeTurnScript + this.GetEverythingAfter(this._lines[j], "beforeturn ") + "\n"; } else if (this.BeginsWith(this._lines[j], "afterturn ")) { r.AfterTurnScript = r.AfterTurnScript + this.GetEverythingAfter(this._lines[j], "afterturn ") + "\n"; } } } } } SetUpSynonyms(): void { var block = this.GetDefineBlock("synonyms"); this._numberSynonyms = 0; if (block.StartLine == 0 && block.EndLine == 0) { return; } for (var i = block.StartLine + 1; i <= block.EndLine - 1; i++) { var eqp = InStr(this._lines[i], "="); if (eqp != 0) { var originalWordsList = Trim(Left(this._lines[i], eqp - 1)); var convertWord = Trim(Mid(this._lines[i], eqp + 1)); //Go through each word in OriginalWordsList (sep. //by ";"): originalWordsList = originalWordsList + ";"; var pos = 1; do { var endOfWord = InStrFrom(pos, originalWordsList, ";"); var thisWord = Trim(Mid(originalWordsList, pos, endOfWord - pos)); if (InStr(" " + convertWord + " ", " " + thisWord + " ") > 0) { // Recursive synonym this.LogASLError("Recursive synonym detected: '" + thisWord + "' converting to '" + convertWord + "'", LogType.WarningError); } else { this._numberSynonyms = this._numberSynonyms + 1; if (!this._synonyms) this._synonyms = []; this._synonyms[this._numberSynonyms] = new SynonymType(); this._synonyms[this._numberSynonyms].OriginalWord = thisWord; this._synonyms[this._numberSynonyms].ConvertTo = convertWord; } pos = endOfWord + 1; } while (!(pos >= Len(originalWordsList))); } } } SetUpTimers(): void { for (var i = 1; i <= this._numberSections; i++) { if (this.BeginsWith(this._lines[this._defineBlocks[i].StartLine], "define timer ")) { this._numberTimers = this._numberTimers + 1; if (!this._timers) this._timers = []; this._timers[this._numberTimers] = new TimerType(); this._timers[this._numberTimers].TimerName = this.GetSimpleParameter(this._lines[this._defineBlocks[i].StartLine]); this._timers[this._numberTimers].TimerActive = false; for (var j = this._defineBlocks[i].StartLine + 1; j <= this._defineBlocks[i].EndLine - 1; j++) { if (this.BeginsWith(this._lines[j], "interval ")) { this._timers[this._numberTimers].TimerInterval = parseInt(this.GetSimpleParameter(this._lines[j])); } else if (this.BeginsWith(this._lines[j], "action ")) { this._timers[this._numberTimers].TimerAction = this.GetEverythingAfter(this._lines[j], "action "); } else if (Trim(LCase(this._lines[j])) == "enabled") { this._timers[this._numberTimers].TimerActive = true; } else if (Trim(LCase(this._lines[j])) == "disabled") { this._timers[this._numberTimers].TimerActive = false; } } } } } SetUpTurnScript(): void { var block = this.GetDefineBlock("game"); this._beforeTurnScript = ""; this._afterTurnScript = ""; for (var i = block.StartLine + 1; i <= block.EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], "beforeturn ")) { this._beforeTurnScript = this._beforeTurnScript + this.GetEverythingAfter(Trim(this._lines[i]), "beforeturn ") + "\n"; } else if (this.BeginsWith(this._lines[i], "afterturn ")) { this._afterTurnScript = this._afterTurnScript + this.GetEverythingAfter(Trim(this._lines[i]), "afterturn ") + "\n"; } } } SetUpUserDefinedPlayerErrors(): void { // goes through "define game" block and sets stored error // messages accordingly var block = this.GetDefineBlock("game"); var examineIsCustomised = false; for (var i = block.StartLine + 1; i <= block.EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], "error ")) { var errorInfo = this.GetSimpleParameter(this._lines[i]); var scp = InStr(errorInfo, ";"); var errorName = Left(errorInfo, scp - 1); var errorMsg = Trim(Mid(errorInfo, scp + 1)); var currentError = 0; switch (errorName) { case "badcommand": currentError = PlayerError.BadCommand; break; case "badgo": currentError = PlayerError.BadGo; break; case "badgive": currentError = PlayerError.BadGive; break; case "badcharacter": currentError = PlayerError.BadCharacter; break; case "noitem": currentError = PlayerError.NoItem; break; case "itemunwanted": currentError = PlayerError.ItemUnwanted; break; case "badlook": currentError = PlayerError.BadLook; break; case "badthing": currentError = PlayerError.BadThing; break; case "defaultlook": currentError = PlayerError.DefaultLook; break; case "defaultspeak": currentError = PlayerError.DefaultSpeak; break; case "baditem": currentError = PlayerError.BadItem; break; case "baddrop": currentError = PlayerError.BadDrop; break; case "defaultake": if (this._gameAslVersion <= 280) { currentError = PlayerError.BadTake; } else { currentError = PlayerError.DefaultTake; } break; case "baduse": currentError = PlayerError.BadUse; break; case "defaultuse": currentError = PlayerError.DefaultUse; break; case "defaultout": currentError = PlayerError.DefaultOut; break; case "badplace": currentError = PlayerError.BadPlace; break; case "badexamine": if (this._gameAslVersion >= 310) { currentError = PlayerError.BadExamine; } break; case "defaultexamine": currentError = PlayerError.DefaultExamine; examineIsCustomised = true; break; case "badtake": currentError = PlayerError.BadTake; break; case "cantdrop": currentError = PlayerError.CantDrop; break; case "defaultdrop": currentError = PlayerError.DefaultDrop; break; case "badpronoun": currentError = PlayerError.BadPronoun; break; case "alreadyopen": currentError = PlayerError.AlreadyOpen; break; case "alreadyclosed": currentError = PlayerError.AlreadyClosed; break; case "cantopen": currentError = PlayerError.CantOpen; break; case "cantclose": currentError = PlayerError.CantClose; break; case "defaultopen": currentError = PlayerError.DefaultOpen; break; case "defaultclose": currentError = PlayerError.DefaultClose; break; case "badput": currentError = PlayerError.BadPut; break; case "cantput": currentError = PlayerError.CantPut; break; case "defaultput": currentError = PlayerError.DefaultPut; break; case "cantremove": currentError = PlayerError.CantRemove; break; case "alreadyput": currentError = PlayerError.AlreadyPut; break; case "defaultremove": currentError = PlayerError.DefaultRemove; break; case "locked": currentError = PlayerError.Locked; break; case "defaultwait": currentError = PlayerError.DefaultWait; break; case "alreadytaken": currentError = PlayerError.AlreadyTaken; break; } this._playerErrorMessageString[currentError] = errorMsg; if (currentError == PlayerError.DefaultLook && !examineIsCustomised) { // If we're setting the default look message, and we've not already customised the // default examine message, then set the default examine message to the same thing. this._playerErrorMessageString[PlayerError.DefaultExamine] = errorMsg; } } } } SetVisibility(thing: string, type: Thing, visible: boolean, ctx: Context): void { // Sets visibilty of objects and characters if (this._gameAslVersion >= 280) { var found = false; for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ObjectName) == LCase(thing)) { this._objs[i].Visible = visible; if (visible) { this.AddToObjectProperties("not invisible", i, ctx); } else { this.AddToObjectProperties("invisible", i, ctx); } found = true; break; } } if (!found) { this.LogASLError("Not found object '" + thing + "'", LogType.WarningError); } } else { // split ThingString into character name and room // (thingstring of form name@room) var atPos = InStr(thing, "@"); var room: string; var name: string; // If no room specified, current room presumed if (atPos == 0) { room = this._currentRoom; name = thing; } else { name = Trim(Left(thing, atPos - 1)); room = Trim(Right(thing, Len(thing) - atPos)); } if (type == Thing.Character) { for (var i = 1; i <= this._numberChars; i++) { if (LCase(this._chars[i].ContainerRoom) == LCase(room) && LCase(this._chars[i].ObjectName) == LCase(name)) { this._chars[i].Visible = visible; break; } } } else if (type == Thing.Object) { for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ContainerRoom) == LCase(room) && LCase(this._objs[i].ObjectName) == LCase(name)) { this._objs[i].Visible = visible; break; } } } } this.UpdateObjectList(ctx); } ShowPictureInText(filename: string): void { if (!this._useStaticFrameForPictures) { this._player.ShowPicture(filename); } else { // Workaround for a particular game which expects pictures to be in a popup window - // use the static picture frame feature so that image is not cleared this._player.SetPanelContents("<img src=\"" + this._player.GetURL(filename) + "\" onload=\"setPanelHeight()\"/>"); } } async ShowRoomInfoV2(room: string): Promise<void> { // ShowRoomInfo for Quest 2.x games var roomDisplayText: string = ""; var descTagExist: boolean = false; var gameBlock: DefineBlock; var charsViewable: string; var charsFound: number = 0; var prefixAliasNoFormat: string; var prefix: string; var prefixAlias: string; var inDesc: string; var aliasName: string = ""; var charList: string; var foundLastComma: number = 0; var cp: number = 0; var ncp: number = 0; var noFormatObjsViewable: string; var objsViewable: string = ""; var objsFound: number = 0; var objListString: string; var noFormatObjListString: string; var possDir: string; var nsew: string; var doorways: string; var places: string; var place: string; var aliasOut: string = ""; var placeNoFormat: string; var descLine: string = ""; var lastComma: number = 0; var oldLastComma: number = 0; var defineBlock: number = 0; var lookString: string = ""; gameBlock = this.GetDefineBlock("game"); this._currentRoom = room; //find the room var roomBlock: DefineBlock; roomBlock = this.DefineBlockParam("room", room); var finishedFindingCommas: boolean = false; charsViewable = ""; charsFound = 0; //see if room has an alias for (var i = roomBlock.StartLine + 1; i <= roomBlock.EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], "alias")) { aliasName = await this.GetParameter(this._lines[i], this._nullContext); i = roomBlock.EndLine; } } if (aliasName == "") { aliasName = room; } //see if room has a prefix prefix = this.FindStatement(roomBlock, "prefix"); if (prefix == "") { prefixAlias = "|cr" + aliasName + "|cb"; prefixAliasNoFormat = aliasName; // No formatting version, for label } else { prefixAlias = prefix + " |cr" + aliasName + "|cb"; prefixAliasNoFormat = prefix + " " + aliasName; } //print player's location //find indescription line: inDesc = "unfound"; for (var i = roomBlock.StartLine + 1; i <= roomBlock.EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], "indescription")) { inDesc = Trim(await this.GetParameter(this._lines[i], this._nullContext)); i = roomBlock.EndLine; } } if (inDesc != "unfound") { // Print player's location according to indescription: if (Right(inDesc, 1) == ":") { // if line ends with a colon, add place name: roomDisplayText = roomDisplayText + Left(inDesc, Len(inDesc) - 1) + " " + prefixAlias + ".\n"; } else { // otherwise, just print the indescription line: roomDisplayText = roomDisplayText + inDesc + "\n"; } } else { // if no indescription line, print the default. roomDisplayText = roomDisplayText + "You are in " + prefixAlias + ".\n"; } this._player.LocationUpdated(prefixAliasNoFormat); await this.SetStringContents("quest.formatroom", prefixAliasNoFormat, this._nullContext); //FIND CHARACTERS === for (var i = 1; i <= this._numberChars; i++) { if (this._chars[i].ContainerRoom == room && this._chars[i].Exists && this._chars[i].Visible) { charsViewable = charsViewable + this._chars[i].Prefix + "|b" + this._chars[i].ObjectName + "|xb" + this._chars[i].Suffix + ", "; charsFound = charsFound + 1; } } if (charsFound == 0) { charsViewable = "There is nobody here."; await this.SetStringContents("quest.characters", "", this._nullContext); } else { //chop off final comma and add full stop (.) charList = Left(charsViewable, Len(charsViewable) - 2); await this.SetStringContents("quest.characters", charList, this._nullContext); //if more than one character, add "and" before //last one: cp = InStr(charList, ","); if (cp != 0) { foundLastComma = 0; do { ncp = InStrFrom(cp + 1, charList, ","); if (ncp == 0) { foundLastComma = 1; } else { cp = ncp; } } while (!(foundLastComma == 1)); charList = Trim(Left(charList, cp - 1)) + " and " + Trim(Mid(charList, cp + 1)); } charsViewable = "You can see " + charList + " here."; } roomDisplayText = roomDisplayText + charsViewable + "\n"; //FIND OBJECTS noFormatObjsViewable = ""; for (var i = 1; i <= this._numberObjs; i++) { if (this._objs[i].ContainerRoom == room && this._objs[i].Exists && this._objs[i].Visible) { objsViewable = objsViewable + this._objs[i].Prefix + "|b" + this._objs[i].ObjectName + "|xb" + this._objs[i].Suffix + ", "; noFormatObjsViewable = noFormatObjsViewable + this._objs[i].Prefix + this._objs[i].ObjectName + ", "; objsFound = objsFound + 1; } } var finishedLoop: boolean = false; if (objsFound != 0) { objListString = Left(objsViewable, Len(objsViewable) - 2); noFormatObjListString = Left(noFormatObjsViewable, Len(noFormatObjsViewable) - 2); cp = InStr(objListString, ","); if (cp != 0) { do { ncp = InStrFrom(cp + 1, objListString, ","); if (ncp == 0) { finishedLoop = true; } else { cp = ncp; } } while (!(finishedLoop)); objListString = Trim(Left(objListString, cp - 1) + " and " + Trim(Mid(objListString, cp + 1))); } objsViewable = "There is " + objListString + " here."; await this.SetStringContents("quest.objects", Left(noFormatObjsViewable, Len(noFormatObjsViewable) - 2), this._nullContext); await this.SetStringContents("quest.formatobjects", objListString, this._nullContext); roomDisplayText = roomDisplayText + objsViewable + "\n"; } else { await this.SetStringContents("quest.objects", "", this._nullContext); await this.SetStringContents("quest.formatobjects", "", this._nullContext); } //FIND DOORWAYS doorways = ""; nsew = ""; places = ""; possDir = ""; for (var i = roomBlock.StartLine + 1; i <= roomBlock.EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], "out")) { doorways = await this.GetParameter(this._lines[i], this._nullContext); } if (this.BeginsWith(this._lines[i], "north ")) { nsew = nsew + "|bnorth|xb, "; possDir = possDir + "n"; } else if (this.BeginsWith(this._lines[i], "south ")) { nsew = nsew + "|bsouth|xb, "; possDir = possDir + "s"; } else if (this.BeginsWith(this._lines[i], "east ")) { nsew = nsew + "|beast|xb, "; possDir = possDir + "e"; } else if (this.BeginsWith(this._lines[i], "west ")) { nsew = nsew + "|bwest|xb, "; possDir = possDir + "w"; } else if (this.BeginsWith(this._lines[i], "northeast ")) { nsew = nsew + "|bnortheast|xb, "; possDir = possDir + "a"; } else if (this.BeginsWith(this._lines[i], "northwest ")) { nsew = nsew + "|bnorthwest|xb, "; possDir = possDir + "b"; } else if (this.BeginsWith(this._lines[i], "southeast ")) { nsew = nsew + "|bsoutheast|xb, "; possDir = possDir + "c"; } else if (this.BeginsWith(this._lines[i], "southwest ")) { nsew = nsew + "|bsouthwest|xb, "; possDir = possDir + "d"; } if (this.BeginsWith(this._lines[i], "place")) { //remove any prefix semicolon from printed text place = await this.GetParameter(this._lines[i], this._nullContext); placeNoFormat = place; //Used in object list - no formatting or prefix if (InStr(place, ";") > 0) { placeNoFormat = Right(place, Len(place) - (InStr(place, ";") + 1)); place = Trim(Left(place, InStr(place, ";") - 1)) + " |b" + Right(place, Len(place) - (InStr(place, ";") + 1)) + "|xb"; } else { place = "|b" + place + "|xb"; } places = places + place + ", "; } } var outside: DefineBlock; if (doorways != "") { //see if outside has an alias outside = this.DefineBlockParam("room", doorways); for (var i = outside.StartLine + 1; i <= outside.EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], "alias")) { aliasOut = await this.GetParameter(this._lines[i], this._nullContext); i = outside.EndLine; } } if (aliasOut == "") { aliasOut = doorways; } roomDisplayText = roomDisplayText + "You can go out to " + aliasOut + ".\n"; possDir = possDir + "o"; await this.SetStringContents("quest.doorways.out", aliasOut, this._nullContext); } else { await this.SetStringContents("quest.doorways.out", "", this._nullContext); } var finished: boolean = false; if (nsew != "") { //strip final comma nsew = Left(nsew, Len(nsew) - 2); cp = InStr(nsew, ","); if (cp != 0) { finished = false; do { ncp = InStrFrom(cp + 1, nsew, ","); if (ncp == 0) { finished = true; } else { cp = ncp; } } while (!(finished)); nsew = Trim(Left(nsew, cp - 1)) + " or " + Trim(Mid(nsew, cp + 1)); } roomDisplayText = roomDisplayText + "You can go " + nsew + ".\n"; await this.SetStringContents("quest.doorways.dirs", nsew, this._nullContext); } else { await this.SetStringContents("quest.doorways.dirs", "", this._nullContext); } this.UpdateDirButtons(possDir, this._nullContext); if (places != "") { //strip final comma places = Left(places, Len(places) - 2); //if there is still a comma here, there is more than //one place, so add the word "or" before the last one. if (InStr(places, ",") > 0) { lastComma = 0; finishedFindingCommas = false; do { oldLastComma = lastComma; lastComma = InStrFrom(lastComma + 1, places, ","); if (lastComma == 0) { finishedFindingCommas = true; lastComma = oldLastComma; } } while (!(finishedFindingCommas)); places = Left(places, lastComma) + " or" + Right(places, Len(places) - lastComma); } roomDisplayText = roomDisplayText + "You can go to " + places + ".\n"; await this.SetStringContents("quest.doorways.places", places, this._nullContext); } else { await this.SetStringContents("quest.doorways.places", "", this._nullContext); } //Print RoomDisplayText if there is no "description" tag, //otherwise execute the description tag information: // First, look in the "define room" block: descTagExist = false; for (var i = roomBlock.StartLine + 1; i <= roomBlock.EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], "description ")) { descLine = this._lines[i]; descTagExist = true; break; } } if (!descTagExist) { //Look in the "define game" block: for (var i = gameBlock.StartLine + 1; i <= gameBlock.EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], "description ")) { descLine = this._lines[i]; descTagExist = true; break; } } } if (!descTagExist) { //Remove final newline: roomDisplayText = Left(roomDisplayText, Len(roomDisplayText) - 2); await this.Print(roomDisplayText, this._nullContext); } else { //execute description tag: //If no script, just print the tag's parameter. //Otherwise, execute it as ASL script: descLine = this.GetEverythingAfter(Trim(descLine), "description "); if (Left(descLine, 1) == "<") { await this.Print(await this.GetParameter(descLine, this._nullContext), this._nullContext); } else { await this.ExecuteScript(descLine, this._nullContext); } } this.UpdateObjectList(this._nullContext); defineBlock = 0; for (var i = roomBlock.StartLine + 1; i <= roomBlock.EndLine - 1; i++) { // don't get the 'look' statements in nested define blocks if (this.BeginsWith(this._lines[i], "define")) { defineBlock = defineBlock + 1; } if (this.BeginsWith(this._lines[i], "end define")) { defineBlock = defineBlock - 1; } if (this.BeginsWith(this._lines[i], "look") && defineBlock == 0) { lookString = await this.GetParameter(this._lines[i], this._nullContext); i = roomBlock.EndLine; } } if (lookString != "") { await this.Print(lookString, this._nullContext); } } AddToObjectList(objList: ListData[], exitList: ListData[], name: string, type: Thing): void { name = this.CapFirst(name); if (type == Thing.Room) { objList.push(new ListData(name, this._listVerbs[ListType.ExitsList])); exitList.push(new ListData(name, this._listVerbs[ListType.ExitsList])); } else { objList.push(new ListData(name, this._listVerbs[ListType.ObjectsList])); } } async ExecExec(scriptLine: string, ctx: Context): Promise<void> { if (ctx.CancelExec) { return; } var execLine = await this.GetParameter(scriptLine, ctx); var newCtx: Context = this.CopyContext(ctx); newCtx.StackCounter = newCtx.StackCounter + 1; if (newCtx.StackCounter > 500) { this.LogASLError("Out of stack space running '" + scriptLine + "' - infinite loop?", LogType.WarningError); ctx.CancelExec = true; return; } if (this._gameAslVersion >= 310) { newCtx.AllowRealNamesInCommand = true; } if (InStr(execLine, ";") == 0) { try { await this.ExecCommand(execLine, newCtx, false); } catch (e) { this.LogASLError("Internal error running '" + scriptLine + "'", LogType.WarningError); ctx.CancelExec = true; } } else { var scp = InStr(execLine, ";"); var ex = Trim(Left(execLine, scp - 1)); var r = Trim(Mid(execLine, scp + 1)); if (r == "normal") { await this.ExecCommand(ex, newCtx, false, false); } else { this.LogASLError("Unrecognised post-command parameter in " + Trim(scriptLine), LogType.WarningError); } } } async ExecSetString(info: string, ctx: Context): Promise<void> { // Sets string contents from a script parameter. // Eg <string1;contents> sets string variable string1 // to "contents" var scp = InStr(info, ";"); var name = Trim(Left(info, scp - 1)); var value = Mid(info, scp + 1); if (IsNumeric(name)) { this.LogASLError("Invalid string name '" + name + "' - string names cannot be numeric", LogType.WarningError); return; } if (this._gameAslVersion >= 281) { value = Trim(value); if (Left(value, 1) == "[" && Right(value, 1) == "]") { value = Mid(value, 2, Len(value) - 2); } } var idx = this.GetArrayIndex(name, ctx); await this.SetStringContents(idx.Name, value, ctx, idx.Index); } async ExecUserCommand(cmd: string, ctx: Context, libCommands: boolean = false): Promise<boolean> { //Executes a user-defined command. If unavailable, returns //false. var curCmd: string; var commandList: string; var script: string = ""; var commandTag: string; var commandLine: string = ""; var foundCommand = false; //First, check for a command in the current room block var roomId = this.GetRoomId(this._currentRoom, ctx); // RoomID is 0 if we have no rooms in the game. Unlikely, but we get an RTE otherwise. if (roomId != 0) { var r = this._rooms[roomId]; for (var i = 1; i <= r.NumberCommands; i++) { commandList = r.Commands[i].CommandText; var ep: number = 0; do { ep = InStr(commandList, ";"); if (ep == 0) { curCmd = commandList; } else { curCmd = Trim(Left(commandList, ep - 1)); commandList = Trim(Mid(commandList, ep + 1)); } if (this.IsCompatible(LCase(cmd), LCase(curCmd))) { commandLine = curCmd; script = r.Commands[i].CommandScript; foundCommand = true; ep = 0; break; } } while (!(ep == 0)); } } if (!libCommands) { commandTag = "command"; } else { commandTag = "lib command"; } if (!foundCommand) { // Check "define game" block var block = this.GetDefineBlock("game"); for (var i = block.StartLine + 1; i <= block.EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], commandTag)) { commandList = await this.GetParameter(this._lines[i], ctx, false); var ep: number = 0; do { ep = InStr(commandList, ";"); if (ep == 0) { curCmd = commandList; } else { curCmd = Trim(Left(commandList, ep - 1)); commandList = Trim(Mid(commandList, ep + 1)); } if (this.IsCompatible(LCase(cmd), LCase(curCmd))) { commandLine = curCmd; var ScriptPos = InStr(this._lines[i], ">") + 1; script = Trim(Mid(this._lines[i], ScriptPos)); foundCommand = true; ep = 0; break; } } while (!(ep == 0)); } } } if (foundCommand) { if (await this.GetCommandParameters(cmd, commandLine, ctx)) { await this.ExecuteScript(script, ctx); } } return foundCommand; } async ExecuteChoose(section: string, ctx: Context): Promise<void> { await this.ExecuteScript(await this.SetUpChoiceForm(section, ctx), ctx); } async GetCommandParameters(test: string, required: string, ctx: Context): Promise<boolean> { //Gets parameters from line. For example, if 'required' //is "read #1#" and 'test' is "read sign", #1# returns //"sign". // Returns FALSE if #@object# form used and object doesn't // exist. var chunksBegin: number[]; var chunksEnd: number[]; var varName: string[]; var var2Pos: number = 0; // Add dots before and after both strings. This fudge // stops problems caused when variables are right at the // beginning or end of a line. // PostScript: well, it used to, I'm not sure if it's really // required now though.... // As of Quest 4.0 we use the � character rather than a dot. test = "�" + Trim(test) + "�"; required = "�" + required + "�"; //Go through RequiredLine in chunks going up to variables. var currentReqLinePos = 1; var currentTestLinePos = 1; var finished = false; var numberChunks = 0; do { var nextVarPos = InStrFrom(currentReqLinePos, required, "#"); var currentVariable = ""; if (nextVarPos == 0) { finished = true; nextVarPos = Len(required) + 1; } else { var2Pos = InStrFrom(nextVarPos + 1, required, "#"); currentVariable = Mid(required, nextVarPos + 1, (var2Pos - 1) - nextVarPos); } var checkChunk = Mid(required, currentReqLinePos, (nextVarPos - 1) - (currentReqLinePos - 1)); var chunkBegin = InStrFrom(currentTestLinePos, LCase(test), LCase(checkChunk)); var chunkEnd = chunkBegin + Len(checkChunk); numberChunks = numberChunks + 1; if (!chunksBegin) chunksBegin = []; if (!chunksEnd) chunksEnd = []; if (!varName) varName = []; chunksBegin[numberChunks] = chunkBegin; chunksEnd[numberChunks] = chunkEnd; varName[numberChunks] = currentVariable; //Get to end of variable name currentReqLinePos = var2Pos + 1; currentTestLinePos = chunkEnd; } while (!(finished)); var success = true; //Return values to string variable for (var i = 1; i <= numberChunks - 1; i++) { var arrayIndex: number = 0; // If VarName contains array name, change to index number if (InStr(varName[i], "[") > 0) { var indexResult = this.GetArrayIndex(varName[i], ctx); varName[i] = indexResult.Name; arrayIndex = indexResult.Index; } else { arrayIndex = 0; } var curChunk = Mid(test, chunksEnd[i], chunksBegin[i + 1] - chunksEnd[i]); if (this.BeginsWith(varName[i], "@")) { varName[i] = this.GetEverythingAfter(varName[i], "@"); var id = await this.Disambiguate(curChunk, this._currentRoom + ";" + "inventory", ctx); if (id == -1) { if (this._gameAslVersion >= 391) { await this.PlayerErrorMessage(PlayerError.BadThing, ctx); } else { await this.PlayerErrorMessage(PlayerError.BadItem, ctx); } // The Mid$(...,2) and Left$(...,2) removes the initial/final "." this._badCmdBefore = Mid(Trim(Left(test, chunksEnd[i] - 1)), 2); this._badCmdAfter = Trim(Mid(test, chunksBegin[i + 1])); this._badCmdAfter = Left(this._badCmdAfter, Len(this._badCmdAfter) - 1); success = false; } else if (id == -2) { this._badCmdBefore = Trim(Left(test, chunksEnd[i] - 1)); this._badCmdAfter = Trim(Mid(test, chunksBegin[i + 1])); success = false; } else { await this.SetStringContents(varName[i], this._objs[id].ObjectName, ctx, arrayIndex); } } else { await this.SetStringContents(varName[i], curChunk, ctx, arrayIndex); } } return success; } async GetGender(character: string, capitalise: boolean, ctx: Context): Promise<string> { var result: string; if (this._gameAslVersion >= 281) { result = this._objs[this.GetObjectIdNoAlias(character)].Gender; } else { var resultLine = this.RetrLine("character", character, "gender", ctx); if (resultLine == "<unfound>") { result = "it "; } else { result = await this.GetParameter(resultLine, ctx) + " "; } } if (capitalise) { result = UCase(Left(result, 1)) + Right(result, Len(result) - 1); } return result; } GetStringContents(name: string, ctx: Context): string { var returnAlias = false; var arrayIndex = 0; // Check for property shortcut var cp = InStr(name, ":"); if (cp != 0) { var objName = Trim(Left(name, cp - 1)); var propName = Trim(Mid(name, cp + 1)); var obp = InStr(objName, "("); if (obp != 0) { var cbp = InStrFrom(obp, objName, ")"); if (cbp != 0) { objName = this.GetStringContents(Mid(objName, obp + 1, (cbp - obp) - 1), ctx); } } return this.GetObjectProperty(propName, this.GetObjectIdNoAlias(objName)); } if (Left(name, 1) == "@") { returnAlias = true; name = Mid(name, 2); } if (InStr(name, "[") != 0 && InStr(name, "]") != 0) { var bp = InStr(name, "["); var ep = InStr(name, "]"); var arrayIndexData = Mid(name, bp + 1, (ep - bp) - 1); if (IsNumeric(arrayIndexData)) { arrayIndex = parseInt(arrayIndexData); } else { arrayIndex = this.GetNumericContents(arrayIndexData, ctx); if (arrayIndex == -32767) { this.LogASLError("Array index in '" + name + "' is not valid. An array index must be either a number or a numeric variable (without surrounding '%' characters)", LogType.WarningError); return ""; } } name = Left(name, bp - 1); } // First, see if the string already exists. If it does, // get its contents. If not, generate an error. var exists = false; var id: number = 0; if (this._numberStringVariables > 0) { for (var i = 1; i <= this._numberStringVariables; i++) { if (LCase(this._stringVariable[i].VariableName) == LCase(name)) { id = i; exists = true; break; } } } if (!exists) { this.LogASLError("No string variable '" + name + "' defined.", LogType.WarningError); return ""; } if (arrayIndex > this._stringVariable[id].VariableUBound) { this.LogASLError("Array index of '" + name + "[" + Trim(Str(arrayIndex)) + "]' too big.", LogType.WarningError); return ""; } // Now, set the contents if (!returnAlias) { return this._stringVariable[id].VariableContents[arrayIndex]; } else { return this._objs[this.GetObjectIdNoAlias(this._stringVariable[id].VariableContents[arrayIndex])].ObjectAlias; } } IsAvailable(thingName: string, type: Thing, ctx: Context): boolean { // Returns availability of object/character // split ThingString into character name and room // (thingstring of form name@room) var room: string; var name: string; var atPos = InStr(thingName, "@"); // If no room specified, current room presumed if (atPos == 0) { room = this._currentRoom; name = thingName; } else { name = Trim(Left(thingName, atPos - 1)); room = Trim(Right(thingName, Len(thingName) - atPos)); } if (type == Thing.Character) { for (var i = 1; i <= this._numberChars; i++) { if (LCase(this._chars[i].ContainerRoom) == LCase(room) && LCase(this._chars[i].ObjectName) == LCase(name)) { return this._chars[i].Exists; } } } else if (type == Thing.Object) { for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ContainerRoom) == LCase(room) && LCase(this._objs[i].ObjectName) == LCase(name)) { return this._objs[i].Exists; } } } } IsCompatible(test: string, required: string): boolean { //Tests to see if 'test' "works" with 'required'. //For example, if 'required' = "read #text#", then the //tests of "read book" and "read sign" are compatible. var var2Pos: number = 0; // This avoids "xxx123" being compatible with "xxx". test = "^" + Trim(test) + "^"; required = "^" + required + "^"; //Go through RequiredLine in chunks going up to variables. var currentReqLinePos = 1; var currentTestLinePos = 1; var finished = false; do { var nextVarPos = InStrFrom(currentReqLinePos, required, "#"); if (nextVarPos == 0) { nextVarPos = Len(required) + 1; finished = true; } else { var2Pos = InStrFrom(nextVarPos + 1, required, "#"); } var checkChunk = Mid(required, currentReqLinePos, (nextVarPos - 1) - (currentReqLinePos - 1)); if (InStrFrom(currentTestLinePos, test, checkChunk) != 0) { currentTestLinePos = InStrFrom(currentTestLinePos, test, checkChunk) + Len(checkChunk); } else { return false; } //Skip to end of variable currentReqLinePos = var2Pos + 1; } while (!(finished)); return true; } async OpenGame(filename: string, onSuccess: Callback, onFailure: Callback): Promise<void> { var cdatb: boolean = false; var result: boolean = false; var visible: boolean = false; var room: string; var fileData: string = ""; var savedQsgVersion: string; var data: string = ""; var name: string; var scp: number = 0; var cdat: number = 0; var scp2: number = 0; var scp3: number = 0; var lines: string[] = null; this._gameLoadMethod = "loaded"; var prevQsgVersion = false; var fileData = this._data; // Check version savedQsgVersion = Left(fileData, 10); if (this.BeginsWith(savedQsgVersion, "QUEST200.1")) { prevQsgVersion = true; } else if (!this.BeginsWith(savedQsgVersion, "QUEST300")) { onFailure(); return; } if (prevQsgVersion) { lines = fileData.split("\n"); this._gameFileName = lines[1]; } else { this.InitFileData(fileData); this.GetNextChunk(); // TODO: For desktop version, game file to load is stored in next chunk this.GetNextChunk(); //this._gameFileName = this.GetNextChunk(); this._gameFileName = filename; } // TODO //if (this._data == null && !System.IO.File.Exists(this._gameFileName)) { // this._gameFileName = this._player.GetNewGameFile(this._gameFileName, "*.asl;*.cas;*.zip"); // if (this._gameFileName == "") { // return false; // } //} var self = this; await this.InitialiseGame(this._gameFileName, true, async function () : Promise<void> { if (!prevQsgVersion) { // Open Quest 3.0 saved game file self._gameLoading = true; await self.RestoreGameData(fileData); self._gameLoading = false; } else { // Open Quest 2.x saved game file self._currentRoom = lines[3]; // Start at line 5 as line 4 is always "!c" var lineNumber: number = 5; do { data = lines[lineNumber]; lineNumber += 1; if (data != "!i") { scp = InStr(data, ";"); name = Trim(Left(data, scp - 1)); cdat = parseInt(Right(data, Len(data) - scp)); for (var i = 1; i <= self._numCollectables; i++) { if (self._collectables[i].Name == name) { self._collectables[i].Value = cdat; i = self._numCollectables; } } } } while (!(data == "!i")); do { data = lines[lineNumber]; lineNumber += 1; if (data != "!o") { scp = InStr(data, ";"); name = Trim(Left(data, scp - 1)); cdatb = self.IsYes(Right(data, Len(data) - scp)); for (var i = 1; i <= self._numberItems; i++) { if (self._items[i].Name == name) { self._items[i].Got = cdatb; i = self._numberItems; } } } } while (!(data == "!o")); do { data = lines[lineNumber]; lineNumber += 1; if (data != "!p") { scp = InStr(data, ";"); scp2 = InStrFrom(scp + 1, data, ";"); scp3 = InStrFrom(scp2 + 1, data, ";"); name = Trim(Left(data, scp - 1)); cdatb = self.IsYes(Mid(data, scp + 1, (scp2 - scp) - 1)); visible = self.IsYes(Mid(data, scp2 + 1, (scp3 - scp2) - 1)); room = Trim(Mid(data, scp3 + 1)); for (var i = 1; i <= self._numberObjs; i++) { if (self._objs[i].ObjectName == name && !self._objs[i].Loaded) { self._objs[i].Exists = cdatb; self._objs[i].Visible = visible; self._objs[i].ContainerRoom = room; self._objs[i].Loaded = true; i = self._numberObjs; } } } } while (!(data == "!p")); do { data = lines[lineNumber]; lineNumber += 1; if (data != "!s") { scp = InStr(data, ";"); scp2 = InStrFrom(scp + 1, data, ";"); scp3 = InStrFrom(scp2 + 1, data, ";"); name = Trim(Left(data, scp - 1)); cdatb = self.IsYes(Mid(data, scp + 1, (scp2 - scp) - 1)); visible = self.IsYes(Mid(data, scp2 + 1, (scp3 - scp2) - 1)); room = Trim(Mid(data, scp3 + 1)); for (var i = 1; i <= self._numberChars; i++) { if (self._chars[i].ObjectName == name) { self._chars[i].Exists = cdatb; self._chars[i].Visible = visible; self._chars[i].ContainerRoom = room; i = self._numberChars; } } } } while (!(data == "!s")); do { data = lines[lineNumber]; lineNumber += 1; if (data != "!n") { scp = InStr(data, ";"); name = Trim(Left(data, scp - 1)); data = Right(data, Len(data) - scp); await self.SetStringContents(name, data, self._nullContext); } } while (!(data == "!n")); do { data = lines[lineNumber]; lineNumber += 1; if (data != "!e") { scp = InStr(data, ";"); name = Trim(Left(data, scp - 1)); data = Right(data, Len(data) - scp); await self.SetNumericVariableContents(name, Val(data), self._nullContext); } } while (!(data == "!e")); } onSuccess(); }, onFailure); } async SaveGame(html: string, callback: StringCallback): Promise<void> { // html parameter is ignored for ASL4 var saveData: string; if (this._gameAslVersion >= 391) { var ctx: Context = new Context(); await this.ExecuteScript(this._beforeSaveScript, ctx); } if (this._gameAslVersion >= 280) { saveData = this.MakeRestoreData(); } else { saveData = this.MakeRestoreDataV2(); } callback(saveData); } MakeRestoreDataV2(): string { var lines: string[] = []; var i: number = 0; lines.push("QUEST200.1"); lines.push(this.GetOriginalFilenameForQSG()); lines.push(this._gameName); lines.push(this._currentRoom); lines.push("!c"); for (var i = 1; i <= this._numCollectables; i++) { lines.push(this._collectables[i].Name + ";" + Str(this._collectables[i].Value)); } lines.push("!i"); for (var i = 1; i <= this._numberItems; i++) { lines.push(this._items[i].Name + ";" + this.YesNo(this._items[i].Got)); } lines.push("!o"); for (var i = 1; i <= this._numberObjs; i++) { lines.push(this._objs[i].ObjectName + ";" + this.YesNo(this._objs[i].Exists) + ";" + this.YesNo(this._objs[i].Visible) + ";" + this._objs[i].ContainerRoom); } lines.push("!p"); for (var i = 1; i <= this._numberChars; i++) { lines.push(this._chars[i].ObjectName + ";" + this.YesNo(this._chars[i].Exists) + ";" + this.YesNo(this._chars[i].Visible) + ";" + this._chars[i].ContainerRoom); } lines.push("!s"); for (var i = 1; i <= this._numberStringVariables; i++) { lines.push(this._stringVariable[i].VariableName + ";" + this._stringVariable[i].VariableContents[0]); } lines.push("!n"); for (var i = 1; i <= this._numberNumericVariables; i++) { lines.push(this._numericVariable[i].VariableName + ";" + Str(parseFloat(this._numericVariable[i].VariableContents[0]))); } lines.push("!e"); return lines.join("\n"); } SetAvailability(thingString: string, exists: boolean, ctx: Context, type: Thing = Thing.Object): void { // Sets availability of objects (and characters in ASL<281) if (this._gameAslVersion >= 281) { var found = false; for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ObjectName) == LCase(thingString)) { this._objs[i].Exists = exists; if (exists) { this.AddToObjectProperties("not hidden", i, ctx); } else { this.AddToObjectProperties("hidden", i, ctx); } found = true; break; } } if (!found) { this.LogASLError("Not found object '" + thingString + "'", LogType.WarningError); } } else { // split ThingString into character name and room // (thingstring of form name@room) var room: string; var name: string; var atPos = InStr(thingString, "@"); // If no room specified, currentroom presumed if (atPos == 0) { room = this._currentRoom; name = thingString; } else { name = Trim(Left(thingString, atPos - 1)); room = Trim(Right(thingString, Len(thingString) - atPos)); } if (type == Thing.Character) { for (var i = 1; i <= this._numberChars; i++) { if (LCase(this._chars[i].ContainerRoom) == LCase(room) && LCase(this._chars[i].ObjectName) == LCase(name)) { this._chars[i].Exists = exists; break; } } } else if (type == Thing.Object) { for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ContainerRoom) == LCase(room) && LCase(this._objs[i].ObjectName) == LCase(name)) { this._objs[i].Exists = exists; break; } } } } this.UpdateInventory(ctx); this.UpdateObjectList(ctx); } SetStringContentsSimple(name: string, value: string, ctx: Context, arrayIndex: number = 0): number { var id: number = 0; var exists = false; if (name == "") { this.LogASLError("Internal error - tried to set empty string name to '" + value + "'", LogType.WarningError); return -1; } if (this._gameAslVersion >= 281) { var bp = InStr(name, "["); if (bp != 0) { arrayIndex = this.GetArrayIndex(name, ctx).Index; name = Left(name, bp - 1); } } if (arrayIndex < 0) { this.LogASLError("'" + name + "[" + Trim(Str(arrayIndex)) + "]' is invalid - did not assign to array", LogType.WarningError); return -1; } // First, see if the string already exists. If it does, // modify it. If not, create it. if (this._numberStringVariables > 0) { for (var i = 1; i <= this._numberStringVariables; i++) { if (LCase(this._stringVariable[i].VariableName) == LCase(name)) { id = i; exists = true; break; } } } if (!exists) { this._numberStringVariables = this._numberStringVariables + 1; id = this._numberStringVariables; if (!this._stringVariable) this._stringVariable = []; this._stringVariable[id] = new VariableType(); this._stringVariable[id].VariableUBound = arrayIndex; } if (arrayIndex > this._stringVariable[id].VariableUBound) { if (!this._stringVariable[id].VariableContents) this._stringVariable[id].VariableContents = []; this._stringVariable[id].VariableUBound = arrayIndex; } // Now, set the contents this._stringVariable[id].VariableName = name; if (!this._stringVariable[id].VariableContents) this._stringVariable[id].VariableContents = []; this._stringVariable[id].VariableContents[arrayIndex] = value; return id; } async SetStringContents(name: string, value: string, ctx: Context, arrayIndex: number = 0): Promise<void> { var id = this.SetStringContentsSimple(name, value, ctx, arrayIndex); if (id == -1) return; if (this._stringVariable[id].OnChangeScript != "") { var script = this._stringVariable[id].OnChangeScript; await this.ExecuteScript(script, ctx); } if (this._stringVariable[id].DisplayString != "") { await this.UpdateStatusVars(ctx); } } SetUpCharObjectInfo(): void { var defaultProperties: PropertiesActions = new PropertiesActions(); this._numberChars = 0; // see if define type <default> exists: var defaultExists = false; for (var i = 1; i <= this._numberSections; i++) { if (Trim(this._lines[this._defineBlocks[i].StartLine]) == "define type <default>") { defaultExists = true; defaultProperties = this.GetPropertiesInType("default"); break; } } for (var i = 1; i <= this._numberSections; i++) { var block = this._defineBlocks[i]; if (!(this.BeginsWith(this._lines[block.StartLine], "define room") || this.BeginsWith(this._lines[block.StartLine], "define game") || this.BeginsWith(this._lines[block.StartLine], "define object "))) { continue; } var restOfLine: string; var origContainerRoomName: string; var containerRoomName: string; if (this.BeginsWith(this._lines[block.StartLine], "define room")) { origContainerRoomName = this.GetSimpleParameter(this._lines[block.StartLine]); } else { origContainerRoomName = ""; } var startLine: number = block.StartLine; var endLine: number = block.EndLine; if (this.BeginsWith(this._lines[block.StartLine], "define object ")) { startLine = startLine - 1; endLine = endLine + 1; } for (var j = startLine + 1; j <= endLine - 1; j++) { if (this.BeginsWith(this._lines[j], "define object")) { containerRoomName = origContainerRoomName; this._numberObjs = this._numberObjs + 1; if (!this._objs) this._objs = []; this._objs[this._numberObjs] = new ObjectType(); var o = this._objs[this._numberObjs]; o.ObjectName = this.GetSimpleParameter(this._lines[j]); o.ObjectAlias = o.ObjectName; o.DefinitionSectionStart = j; o.ContainerRoom = containerRoomName; o.Visible = true; o.Gender = "it"; o.Article = "it"; o.Take.Type = TextActionType.Nothing; if (defaultExists) { this.AddToObjectProperties(defaultProperties.Properties, this._numberObjs, this._nullContext); for (var k = 1; k <= defaultProperties.NumberActions; k++) { this.AddObjectAction(this._numberObjs, defaultProperties.Actions[k].ActionName, defaultProperties.Actions[k].Script); } } if (this._gameAslVersion >= 391) { this.AddToObjectProperties("list", this._numberObjs, this._nullContext); } var hidden = false; do { j = j + 1; if (Trim(this._lines[j]) == "hidden") { o.Exists = false; hidden = true; if (this._gameAslVersion >= 311) { this.AddToObjectProperties("hidden", this._numberObjs, this._nullContext); } } else if (this.BeginsWith(this._lines[j], "startin ") && containerRoomName == "__UNKNOWN") { containerRoomName = this.GetSimpleParameter(this._lines[j]); } else if (this.BeginsWith(this._lines[j], "prefix ")) { o.Prefix = this.GetSimpleParameter(this._lines[j]) + " "; if (this._gameAslVersion >= 311) { this.AddToObjectProperties("prefix=" + o.Prefix, this._numberObjs, this._nullContext); } } else if (this.BeginsWith(this._lines[j], "suffix ")) { o.Suffix = this.GetSimpleParameter(this._lines[j]); if (this._gameAslVersion >= 311) { this.AddToObjectProperties("suffix=" + o.Suffix, this._numberObjs, this._nullContext); } } else if (Trim(this._lines[j]) == "invisible") { o.Visible = false; if (this._gameAslVersion >= 311) { this.AddToObjectProperties("invisible", this._numberObjs, this._nullContext); } } else if (this.BeginsWith(this._lines[j], "alias ")) { o.ObjectAlias = this.GetSimpleParameter(this._lines[j]); if (this._gameAslVersion >= 311) { this.AddToObjectProperties("alias=" + o.ObjectAlias, this._numberObjs, this._nullContext); } } else if (this.BeginsWith(this._lines[j], "alt ")) { this.AddToObjectAltNames(this.GetSimpleParameter(this._lines[j]), this._numberObjs); } else if (this.BeginsWith(this._lines[j], "detail ")) { o.Detail = this.GetSimpleParameter(this._lines[j]); if (this._gameAslVersion >= 311) { this.AddToObjectProperties("detail=" + o.Detail, this._numberObjs, this._nullContext); } } else if (this.BeginsWith(this._lines[j], "gender ")) { o.Gender = this.GetSimpleParameter(this._lines[j]); if (this._gameAslVersion >= 311) { this.AddToObjectProperties("gender=" + o.Gender, this._numberObjs, this._nullContext); } } else if (this.BeginsWith(this._lines[j], "article ")) { o.Article = this.GetSimpleParameter(this._lines[j]); if (this._gameAslVersion >= 311) { this.AddToObjectProperties("article=" + o.Article, this._numberObjs, this._nullContext); } } else if (this.BeginsWith(this._lines[j], "gain ")) { o.GainScript = this.GetEverythingAfter(this._lines[j], "gain "); this.AddObjectAction(this._numberObjs, "gain", o.GainScript); } else if (this.BeginsWith(this._lines[j], "lose ")) { o.LoseScript = this.GetEverythingAfter(this._lines[j], "lose "); this.AddObjectAction(this._numberObjs, "lose", o.LoseScript); } else if (this.BeginsWith(this._lines[j], "displaytype ")) { o.DisplayType = this.GetSimpleParameter(this._lines[j]); if (this._gameAslVersion >= 311) { this.AddToObjectProperties("displaytype=" + o.DisplayType, this._numberObjs, this._nullContext); } } else if (this.BeginsWith(this._lines[j], "look ")) { if (this._gameAslVersion >= 311) { restOfLine = this.GetEverythingAfter(this._lines[j], "look "); if (Left(restOfLine, 1) == "<") { this.AddToObjectProperties("look=" + this.GetSimpleParameter(this._lines[j]), this._numberObjs, this._nullContext); } else { this.AddObjectAction(this._numberObjs, "look", restOfLine); } } } else if (this.BeginsWith(this._lines[j], "examine ")) { if (this._gameAslVersion >= 311) { restOfLine = this.GetEverythingAfter(this._lines[j], "examine "); if (Left(restOfLine, 1) == "<") { this.AddToObjectProperties("examine=" + this.GetSimpleParameter(this._lines[j]), this._numberObjs, this._nullContext); } else { this.AddObjectAction(this._numberObjs, "examine", restOfLine); } } } else if (this._gameAslVersion >= 311 && this.BeginsWith(this._lines[j], "speak ")) { restOfLine = this.GetEverythingAfter(this._lines[j], "speak "); if (Left(restOfLine, 1) == "<") { this.AddToObjectProperties("speak=" + this.GetSimpleParameter(this._lines[j]), this._numberObjs, this._nullContext); } else { this.AddObjectAction(this._numberObjs, "speak", restOfLine); } } else if (this.BeginsWith(this._lines[j], "properties ")) { this.AddToObjectProperties(this.GetSimpleParameter(this._lines[j]), this._numberObjs, this._nullContext); } else if (this.BeginsWith(this._lines[j], "type ")) { o.NumberTypesIncluded = o.NumberTypesIncluded + 1; if (!o.TypesIncluded) o.TypesIncluded = []; o.TypesIncluded[o.NumberTypesIncluded] = this.GetSimpleParameter(this._lines[j]); var PropertyData = this.GetPropertiesInType(this.GetSimpleParameter(this._lines[j])); this.AddToObjectProperties(PropertyData.Properties, this._numberObjs, this._nullContext); for (var k = 1; k <= PropertyData.NumberActions; k++) { this.AddObjectAction(this._numberObjs, PropertyData.Actions[k].ActionName, PropertyData.Actions[k].Script); } if (!o.TypesIncluded) o.TypesIncluded = []; for (var k = 1; k <= PropertyData.NumberTypesIncluded; k++) { o.TypesIncluded[k + o.NumberTypesIncluded] = PropertyData.TypesIncluded[k]; } o.NumberTypesIncluded = o.NumberTypesIncluded + PropertyData.NumberTypesIncluded; } else if (this.BeginsWith(this._lines[j], "action ")) { this.AddToObjectActions(this.GetEverythingAfter(this._lines[j], "action "), this._numberObjs); } else if (this.BeginsWith(this._lines[j], "use ")) { this.AddToUseInfo(this._numberObjs, this.GetEverythingAfter(this._lines[j], "use ")); } else if (this.BeginsWith(this._lines[j], "give ")) { this.AddToGiveInfo(this._numberObjs, this.GetEverythingAfter(this._lines[j], "give ")); } else if (Trim(this._lines[j]) == "take") { o.Take.Type = TextActionType.Default; this.AddToObjectProperties("take", this._numberObjs, this._nullContext); } else if (this.BeginsWith(this._lines[j], "take ")) { if (Left(this.GetEverythingAfter(this._lines[j], "take "), 1) == "<") { o.Take.Type = TextActionType.Text; o.Take.Data = this.GetSimpleParameter(this._lines[j]); this.AddToObjectProperties("take=" + this.GetSimpleParameter(this._lines[j]), this._numberObjs, this._nullContext); } else { o.Take.Type = TextActionType.Script; restOfLine = this.GetEverythingAfter(this._lines[j], "take "); o.Take.Data = restOfLine; this.AddObjectAction(this._numberObjs, "take", restOfLine); } } else if (Trim(this._lines[j]) == "container") { if (this._gameAslVersion >= 391) { this.AddToObjectProperties("container", this._numberObjs, this._nullContext); } } else if (Trim(this._lines[j]) == "surface") { if (this._gameAslVersion >= 391) { this.AddToObjectProperties("container", this._numberObjs, this._nullContext); this.AddToObjectProperties("surface", this._numberObjs, this._nullContext); } } else if (Trim(this._lines[j]) == "opened") { if (this._gameAslVersion >= 391) { this.AddToObjectProperties("opened", this._numberObjs, this._nullContext); } } else if (Trim(this._lines[j]) == "transparent") { if (this._gameAslVersion >= 391) { this.AddToObjectProperties("transparent", this._numberObjs, this._nullContext); } } else if (Trim(this._lines[j]) == "open") { this.AddToObjectProperties("open", this._numberObjs, this._nullContext); } else if (this.BeginsWith(this._lines[j], "open ")) { if (Left(this.GetEverythingAfter(this._lines[j], "open "), 1) == "<") { this.AddToObjectProperties("open=" + this.GetSimpleParameter(this._lines[j]), this._numberObjs, this._nullContext); } else { restOfLine = this.GetEverythingAfter(this._lines[j], "open "); this.AddObjectAction(this._numberObjs, "open", restOfLine); } } else if (Trim(this._lines[j]) == "close") { this.AddToObjectProperties("close", this._numberObjs, this._nullContext); } else if (this.BeginsWith(this._lines[j], "close ")) { if (Left(this.GetEverythingAfter(this._lines[j], "close "), 1) == "<") { this.AddToObjectProperties("close=" + this.GetSimpleParameter(this._lines[j]), this._numberObjs, this._nullContext); } else { restOfLine = this.GetEverythingAfter(this._lines[j], "close "); this.AddObjectAction(this._numberObjs, "close", restOfLine); } } else if (Trim(this._lines[j]) == "add") { this.AddToObjectProperties("add", this._numberObjs, this._nullContext); } else if (this.BeginsWith(this._lines[j], "add ")) { if (Left(this.GetEverythingAfter(this._lines[j], "add "), 1) == "<") { this.AddToObjectProperties("add=" + this.GetSimpleParameter(this._lines[j]), this._numberObjs, this._nullContext); } else { restOfLine = this.GetEverythingAfter(this._lines[j], "add "); this.AddObjectAction(this._numberObjs, "add", restOfLine); } } else if (Trim(this._lines[j]) == "remove") { this.AddToObjectProperties("remove", this._numberObjs, this._nullContext); } else if (this.BeginsWith(this._lines[j], "remove ")) { if (Left(this.GetEverythingAfter(this._lines[j], "remove "), 1) == "<") { this.AddToObjectProperties("remove=" + this.GetSimpleParameter(this._lines[j]), this._numberObjs, this._nullContext); } else { restOfLine = this.GetEverythingAfter(this._lines[j], "remove "); this.AddObjectAction(this._numberObjs, "remove", restOfLine); } } else if (this.BeginsWith(this._lines[j], "parent ")) { this.AddToObjectProperties("parent=" + this.GetSimpleParameter(this._lines[j]), this._numberObjs, this._nullContext); } else if (this.BeginsWith(this._lines[j], "list")) { this.ProcessListInfo(this._lines[j], this._numberObjs); } } while (!(Trim(this._lines[j]) == "end define")); o.DefinitionSectionEnd = j; if (!hidden) { o.Exists = true; } } else if (this._gameAslVersion <= 280 && this.BeginsWith(this._lines[j], "define character")) { containerRoomName = origContainerRoomName; this._numberChars = this._numberChars + 1; if (!this._chars) this._chars = []; this._chars[this._numberChars] = new ObjectType(); this._chars[this._numberChars].ObjectName = this.GetSimpleParameter(this._lines[j]); this._chars[this._numberChars].DefinitionSectionStart = j; this._chars[this._numberChars].ContainerRoom = ""; this._chars[this._numberChars].Visible = true; var hidden = false; do { j = j + 1; if (Trim(this._lines[j]) == "hidden") { this._chars[this._numberChars].Exists = false; hidden = true; } else if (this.BeginsWith(this._lines[j], "startin ") && containerRoomName == "__UNKNOWN") { containerRoomName = this.GetSimpleParameter(this._lines[j]); } else if (this.BeginsWith(this._lines[j], "prefix ")) { this._chars[this._numberChars].Prefix = this.GetSimpleParameter(this._lines[j]) + " "; } else if (this.BeginsWith(this._lines[j], "suffix ")) { this._chars[this._numberChars].Suffix = " " + this.GetSimpleParameter(this._lines[j]); } else if (Trim(this._lines[j]) == "invisible") { this._chars[this._numberChars].Visible = false; } else if (this.BeginsWith(this._lines[j], "alias ")) { this._chars[this._numberChars].ObjectAlias = this.GetSimpleParameter(this._lines[j]); } else if (this.BeginsWith(this._lines[j], "detail ")) { this._chars[this._numberChars].Detail = this.GetSimpleParameter(this._lines[j]); } this._chars[this._numberChars].ContainerRoom = containerRoomName; } while (!(Trim(this._lines[j]) == "end define")); this._chars[this._numberChars].DefinitionSectionEnd = j; if (!hidden) { this._chars[this._numberChars].Exists = true; } } } } this.UpdateVisibilityInContainers(this._nullContext); } async ShowGameAbout(ctx: Context): Promise<void> { var version = this.FindStatement(this.GetDefineBlock("game"), "game version"); var author = this.FindStatement(this.GetDefineBlock("game"), "game author"); var copyright = this.FindStatement(this.GetDefineBlock("game"), "game copyright"); var info = this.FindStatement(this.GetDefineBlock("game"), "game info"); await this.Print("|bGame name:|cl " + this._gameName + "|cb|xb", ctx); if (version != "") { await this.Print("|bVersion:|xb " + version, ctx); } if (author != "") { await this.Print("|bAuthor:|xb " + author, ctx); } if (copyright != "") { await this.Print("|bCopyright:|xb " + copyright, ctx); } if (info != "") { await this.Print("", ctx); await this.Print(info, ctx); } } async ShowPicture(filename: string): Promise<void> { // In Quest 4.x this function would be used for showing a picture in a popup window, but // this is no longer supported - ALL images are displayed in-line with the game text. Any // image caption is displayed as text, and any image size specified is ignored. var caption: string = ""; if (InStr(filename, ";") != 0) { caption = Trim(Mid(filename, InStr(filename, ";") + 1)); filename = Trim(Left(filename, InStr(filename, ";") - 1)); } if (InStr(filename, "@") != 0) { // size is ignored filename = Trim(Left(filename, InStr(filename, "@") - 1)); } if (caption.length > 0) { await this.Print(caption, this._nullContext); } this.ShowPictureInText(filename); } async ShowRoomInfo(room: string, ctx: Context, noPrint: boolean = false): Promise<void> { if (this._gameAslVersion < 280) { await this.ShowRoomInfoV2(room); return; } var roomDisplayText: string = ""; var descTagExist: boolean = false; var doorwayString: string; var roomAlias: string; var finishedFindingCommas: boolean = false; var prefix: string; var roomDisplayName: string; var roomDisplayNameNoFormat: string; var inDescription: string; var visibleObjects: string = ""; var visibleObjectsNoFormat: string; var placeList: string; var lastComma: number = 0; var oldLastComma: number = 0; var descType: number = 0; var descLine: string = ""; var showLookText: boolean = false; var lookDesc: string = ""; var objLook: string; var objSuffix: string; var gameBlock = this.GetDefineBlock("game"); this._currentRoom = room; var id = this.GetRoomId(this._currentRoom, ctx); if (id == 0) { return; } // FIRST LINE - YOU ARE IN... *********************************************** roomAlias = this._rooms[id].RoomAlias; if (roomAlias == "") { roomAlias = this._rooms[id].RoomName; } prefix = this._rooms[id].Prefix; if (prefix == "") { roomDisplayName = "|cr" + roomAlias + "|cb"; roomDisplayNameNoFormat = roomAlias; // No formatting version, for label } else { roomDisplayName = prefix + " |cr" + roomAlias + "|cb"; roomDisplayNameNoFormat = prefix + " " + roomAlias; } inDescription = this._rooms[id].InDescription; if (inDescription != "") { // Print player's location according to indescription: if (Right(inDescription, 1) == ":") { // if line ends with a colon, add place name: roomDisplayText = roomDisplayText + Left(inDescription, Len(inDescription) - 1) + " " + roomDisplayName + ".\n"; } else { // otherwise, just print the indescription line: roomDisplayText = roomDisplayText + inDescription + "\n"; } } else { // if no indescription line, print the default. roomDisplayText = roomDisplayText + "You are in " + roomDisplayName + ".\n"; } this._player.LocationUpdated(UCase(Left(roomAlias, 1)) + Mid(roomAlias, 2)); await this.SetStringContents("quest.formatroom", roomDisplayNameNoFormat, ctx); // SHOW OBJECTS ************************************************************* visibleObjectsNoFormat = ""; var visibleObjectsList: number[] = []; // of object IDs var count: number = 0; for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ContainerRoom) == LCase(room) && this._objs[i].Exists && this._objs[i].Visible && !this._objs[i].IsExit) { visibleObjectsList.push(i); } } visibleObjectsList.forEach(function (objId) { objSuffix = this._objs[objId].Suffix; if (objSuffix != "") { objSuffix = " " + objSuffix; } if (this._objs[objId].ObjectAlias == "") { visibleObjects = visibleObjects + this._objs[objId].Prefix + "|b" + this._objs[objId].ObjectName + "|xb" + objSuffix; visibleObjectsNoFormat = visibleObjectsNoFormat + this._objs[objId].Prefix + this._objs[objId].ObjectName; } else { visibleObjects = visibleObjects + this._objs[objId].Prefix + "|b" + this._objs[objId].ObjectAlias + "|xb" + objSuffix; visibleObjectsNoFormat = visibleObjectsNoFormat + this._objs[objId].Prefix + this._objs[objId].ObjectAlias; } count = count + 1; if (count < visibleObjectsList.length - 1) { visibleObjects = visibleObjects + ", "; visibleObjectsNoFormat = visibleObjectsNoFormat + ", "; } else if (count == visibleObjectsList.length - 1) { visibleObjects = visibleObjects + " and "; visibleObjectsNoFormat = visibleObjectsNoFormat + ", "; } }, this); if (visibleObjectsList.length > 0) { await this.SetStringContents("quest.formatobjects", visibleObjects, ctx); visibleObjects = "There is " + visibleObjects + " here."; await this.SetStringContents("quest.objects", visibleObjectsNoFormat, ctx); roomDisplayText = roomDisplayText + visibleObjects + "\n"; } else { await this.SetStringContents("quest.objects", "", ctx); await this.SetStringContents("quest.formatobjects", "", ctx); } // SHOW EXITS *************************************************************** doorwayString = await this.UpdateDoorways(id, ctx); if (this._gameAslVersion < 410) { placeList = this.GetGoToExits(id, ctx); if (placeList != "") { //strip final comma placeList = Left(placeList, Len(placeList) - 2); //if there is still a comma here, there is more than //one place, so add the word "or" before the last one. if (InStr(placeList, ",") > 0) { lastComma = 0; finishedFindingCommas = false; do { oldLastComma = lastComma; lastComma = InStrFrom(lastComma + 1, placeList, ","); if (lastComma == 0) { finishedFindingCommas = true; lastComma = oldLastComma; } } while (!(finishedFindingCommas)); placeList = Left(placeList, lastComma - 1) + " or" + Right(placeList, Len(placeList) - lastComma); } roomDisplayText = roomDisplayText + "You can go to " + placeList + ".\n"; await this.SetStringContents("quest.doorways.places", placeList, ctx); } else { await this.SetStringContents("quest.doorways.places", "", ctx); } } // GET "LOOK" DESCRIPTION (but don't print it yet) ************************** objLook = this.GetObjectProperty("look", this._rooms[id].ObjId, null, false); if (objLook == "") { if (this._rooms[id].Look != "") { lookDesc = this._rooms[id].Look; } } else { lookDesc = objLook; } await this.SetStringContents("quest.lookdesc", lookDesc, ctx); // FIND DESCRIPTION TAG, OR ACTION ****************************************** // In Quest versions prior to 3.1, with any custom description, the "look" // text was always displayed after the "description" tag was printed/executed. // In Quest 3.1 and later, it isn't - descriptions should print the look // tag themselves when and where necessary. showLookText = true; if (this._rooms[id].Description.Data != "") { descLine = this._rooms[id].Description.Data; descType = this._rooms[id].Description.Type; descTagExist = true; } else { descTagExist = false; } if (!descTagExist) { //Look in the "define game" block: for (var i = gameBlock.StartLine + 1; i <= gameBlock.EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], "description ")) { descLine = this.GetEverythingAfter(this._lines[i], "description "); descTagExist = true; if (Left(descLine, 1) == "<") { descLine = await this.GetParameter(descLine, ctx); descType = TextActionType.Text; } else { descType = TextActionType.Script; } i = gameBlock.EndLine; } } } if (descTagExist && this._gameAslVersion >= 310) { showLookText = false; } if (!noPrint) { if (!descTagExist) { //Remove final \n roomDisplayText = Left(roomDisplayText, Len(roomDisplayText) - 1); await this.Print(roomDisplayText, ctx); if (doorwayString != "") { await this.Print(doorwayString, ctx); } } else { //execute description tag: //If no script, just print the tag's parameter. //Otherwise, execute it as ASL script: if (descType == TextActionType.Text) { await this.Print(descLine, ctx); } else { await this.ExecuteScript(descLine, ctx); } } this.UpdateObjectList(ctx); // SHOW "LOOK" DESCRIPTION ************************************************** if (showLookText) { if (lookDesc != "") { await this.Print(lookDesc, ctx); } } } } CheckCollectable(id: number): void { // Checks to see whether a collectable item has exceeded // its range - if so, it resets the number to the nearest // valid number. It's a handy quick way of making sure that // a player's health doesn't reach 101%, for example. var max: number = 0; var value: number = 0; var min: number = 0; var m: number = 0; var type = this._collectables[id].Type; value = this._collectables[id].Value; if (type == "%" && value > 100) { value = 100; } if ((type == "%" || type == "p") && value < 0) { value = 0; } if (InStr(type, "r") > 0) { if (InStr(type, "r") == 1) { max = Val(Mid(type, Len(type) - 1)); m = 1; } else if (InStr(type, "r") == Len(type)) { min = Val(Left(type, Len(type) - 1)); m = 2; } else { min = Val(Left(type, InStr(type, "r") - 1)); max = Val(Mid(type, InStr(type, "r") + 1)); m = 3; } if ((m == 1 || m == 3) && value > max) { value = max; } if ((m == 2 || m == 3) && value < min) { value = min; } } this._collectables[id].Value = value; } DisplayCollectableInfo(id: number): string { var display: string; if (this._collectables[id].Display == "<def>") { display = "You have " + Trim(Str(this._collectables[id].Value)) + " " + this._collectables[id].Name; } else if (this._collectables[id].Display == "") { display = "<null>"; } else { var ep = InStr(this._collectables[id].Display, "!"); if (ep == 0) { display = this._collectables[id].Display; } else { var firstBit = Left(this._collectables[id].Display, ep - 1); var nextBit = Right(this._collectables[id].Display, Len(this._collectables[id].Display) - ep); display = firstBit + Trim(Str(this._collectables[id].Value)) + nextBit; } if (InStr(display, "*") > 0) { var firstStarPos = InStr(display, "*"); var secondStarPos = InStrFrom(firstStarPos + 1, display, "*"); var beforeStar = Left(display, firstStarPos - 1); var afterStar = Mid(display, secondStarPos + 1); var betweenStar = Mid(display, firstStarPos + 1, (secondStarPos - firstStarPos) - 1); if (this._collectables[id].Value != 1) { display = beforeStar + betweenStar + afterStar; } else { display = beforeStar + afterStar; } } } if (this._collectables[id].Value == 0 && !this._collectables[id].DisplayWhenZero) { display = "<null>"; } return display; } async DisplayTextSection(section: string, ctx: Context): Promise<void> { var block: DefineBlock; block = this.DefineBlockParam("text", section); if (block.StartLine == 0) { return; } for (var i = block.StartLine + 1; i <= block.EndLine - 1; i++) { if (this._gameAslVersion >= 392) { // Convert string variables etc. await this.Print(await this.GetParameter("<" + this._lines[i] + ">", ctx), ctx); } else { await this.Print(this._lines[i], ctx); } } await this.Print("", ctx); } // Returns true if the system is ready to process a new command after completion - so it will be // in most cases, except when ExecCommand just caused an "enter" script command to complete async ExecCommand(input: string, ctx: Context, echo: boolean = true, runUserCommand: boolean = true, dontSetIt: boolean = false): Promise<boolean> { var parameter: string; var skipAfterTurn = false; input = this.RemoveFormatting(input); var oldBadCmdBefore = this._badCmdBefore; var roomID = this.GetRoomId(this._currentRoom, ctx); var enteredHelpCommand = false; if (input == "") { return true; } var cmd = LCase(input); if (this._commandOverrideModeOn) { this._commandOverrideModeOn = false; // Commands have been overridden for this command, // so put input into previously specified variable // and exit: await this.SetStringContents(this._commandOverrideVariable, input, ctx); this._commandOverrideResolve(); return false; } var userCommandReturn: boolean = false; if (echo) { await this.Print("> " + input, ctx); } input = LCase(input); await this.SetStringContents("quest.originalcommand", input, ctx); var newCommand = " " + input + " "; // Convert synonyms: for (var i = 1; i <= this._numberSynonyms; i++) { var cp = 1; var n: number = 0; do { n = InStrFrom(cp, newCommand, " " + this._synonyms[i].OriginalWord + " "); if (n != 0) { newCommand = Left(newCommand, n - 1) + " " + this._synonyms[i].ConvertTo + " " + Mid(newCommand, n + Len(this._synonyms[i].OriginalWord) + 2); cp = n + 1; } } while (!(n == 0)); } //strip starting and ending spaces input = Mid(newCommand, 2, Len(newCommand) - 2); await this.SetStringContents("quest.command", input, ctx); // Execute any "beforeturn" script: var newCtx: Context = this.CopyContext(ctx); var globalOverride = false; // RoomID is 0 if there are no rooms in the game. Unlikely, but we get an RTE otherwise. if (roomID != 0) { if (this._rooms[roomID].BeforeTurnScript != "") { if (this.BeginsWith(this._rooms[roomID].BeforeTurnScript, "override")) { await this.ExecuteScript(this.GetEverythingAfter(this._rooms[roomID].BeforeTurnScript, "override"), newCtx); globalOverride = true; } else { await this.ExecuteScript(this._rooms[roomID].BeforeTurnScript, newCtx); } } } if (this._beforeTurnScript != "" && !globalOverride) { await this.ExecuteScript(this._beforeTurnScript, newCtx); } // In executing BeforeTurn script, "dontprocess" sets ctx.DontProcessCommand, // in which case we don't process the command. if (!newCtx.DontProcessCommand) { //Try to execute user defined command, if allowed: userCommandReturn = false; if (runUserCommand) { userCommandReturn = await this.ExecUserCommand(input, ctx); if (!userCommandReturn) { userCommandReturn = await this.ExecVerb(input, ctx); } if (!userCommandReturn) { // Try command defined by a library userCommandReturn = await this.ExecUserCommand(input, ctx, true); } if (!userCommandReturn) { // Try verb defined by a library userCommandReturn = await this.ExecVerb(input, ctx, true); } } input = LCase(input); } else { // Set the UserCommand flag to fudge not processing any more commands userCommandReturn = true; } var invList = ""; if (!userCommandReturn) { if (this.CmdStartsWith(input, "speak to ")) { parameter = this.GetEverythingAfter(input, "speak to "); await this.ExecSpeak(parameter, ctx); } else if (this.CmdStartsWith(input, "talk to ")) { parameter = this.GetEverythingAfter(input, "talk to "); await this.ExecSpeak(parameter, ctx); } else if (cmd == "exit" || cmd == "out" || cmd == "leave") { await this.GoDirection("out", ctx); this._lastIt = 0; } else if (cmd == "north" || cmd == "south" || cmd == "east" || cmd == "west") { await this.GoDirection(input, ctx); this._lastIt = 0; } else if (cmd == "n" || cmd == "s" || cmd == "w" || cmd == "e") { switch (InStr("nswe", cmd)) { case 1: await this.GoDirection("north", ctx); break; case 2: await this.GoDirection("south", ctx); break; case 3: await this.GoDirection("west", ctx); break; case 4: await this.GoDirection("east", ctx); break; } this._lastIt = 0; } else if (cmd == "ne" || cmd == "northeast" || cmd == "north-east" || cmd == "north east" || cmd == "go ne" || cmd == "go northeast" || cmd == "go north-east" || cmd == "go north east") { await this.GoDirection("northeast", ctx); this._lastIt = 0; } else if (cmd == "nw" || cmd == "northwest" || cmd == "north-west" || cmd == "north west" || cmd == "go nw" || cmd == "go northwest" || cmd == "go north-west" || cmd == "go north west") { await this.GoDirection("northwest", ctx); this._lastIt = 0; } else if (cmd == "se" || cmd == "southeast" || cmd == "south-east" || cmd == "south east" || cmd == "go se" || cmd == "go southeast" || cmd == "go south-east" || cmd == "go south east") { await this.GoDirection("southeast", ctx); this._lastIt = 0; } else if (cmd == "sw" || cmd == "southwest" || cmd == "south-west" || cmd == "south west" || cmd == "go sw" || cmd == "go southwest" || cmd == "go south-west" || cmd == "go south west") { await this.GoDirection("southwest", ctx); this._lastIt = 0; } else if (cmd == "up" || cmd == "u") { await this.GoDirection("up", ctx); this._lastIt = 0; } else if (cmd == "down" || cmd == "d") { await this.GoDirection("down", ctx); this._lastIt = 0; } else if (this.CmdStartsWith(input, "go ")) { if (this._gameAslVersion >= 410) { await this._rooms[this.GetRoomId(this._currentRoom, ctx)].Exits.ExecuteGo(input, ctx); } else { parameter = this.GetEverythingAfter(input, "go "); if (parameter == "out") { await this.GoDirection("out", ctx); } else if (parameter == "north" || parameter == "south" || parameter == "east" || parameter == "west" || parameter == "up" || parameter == "down") { await this.GoDirection(parameter, ctx); } else if (this.BeginsWith(parameter, "to ")) { parameter = this.GetEverythingAfter(parameter, "to "); await this.GoToPlace(parameter, ctx); } else { await this.PlayerErrorMessage(PlayerError.BadGo, ctx); } } this._lastIt = 0; } else if (this.CmdStartsWith(input, "give ")) { parameter = this.GetEverythingAfter(input, "give "); await this.ExecGive(parameter, ctx); } else if (this.CmdStartsWith(input, "take ")) { parameter = this.GetEverythingAfter(input, "take "); await this.ExecTake(parameter, ctx); } else if (this.CmdStartsWith(input, "drop ") && this._gameAslVersion >= 280) { parameter = this.GetEverythingAfter(input, "drop "); await this.ExecDrop(parameter, ctx); } else if (this.CmdStartsWith(input, "get ")) { parameter = this.GetEverythingAfter(input, "get "); await this.ExecTake(parameter, ctx); } else if (this.CmdStartsWith(input, "pick up ")) { parameter = this.GetEverythingAfter(input, "pick up "); await this.ExecTake(parameter, ctx); } else if (cmd == "pick it up" || cmd == "pick them up" || cmd == "pick this up" || cmd == "pick that up" || cmd == "pick these up" || cmd == "pick those up" || cmd == "pick him up" || cmd == "pick her up") { await this.ExecTake(Mid(cmd, 6, InStrFrom(7, cmd, " ") - 6), ctx); } else if (this.CmdStartsWith(input, "look ")) { await this.ExecLook(input, ctx); } else if (this.CmdStartsWith(input, "l ")) { await this.ExecLook("look " + this.GetEverythingAfter(input, "l "), ctx); } else if (this.CmdStartsWith(input, "examine ") && this._gameAslVersion >= 280) { await this.ExecExamine(input, ctx); } else if (this.CmdStartsWith(input, "x ") && this._gameAslVersion >= 280) { await this.ExecExamine("examine " + this.GetEverythingAfter(input, "x "), ctx); } else if (cmd == "l" || cmd == "look") { await this.ExecLook("look", ctx); } else if (cmd == "x" || cmd == "examine") { await this.ExecExamine("examine", ctx); } else if (this.CmdStartsWith(input, "use ")) { await this.ExecUse(input, ctx); } else if (this.CmdStartsWith(input, "open ") && this._gameAslVersion >= 391) { await this.ExecOpenClose(input, ctx); } else if (this.CmdStartsWith(input, "close ") && this._gameAslVersion >= 391) { await this.ExecOpenClose(input, ctx); } else if (this.CmdStartsWith(input, "put ") && this._gameAslVersion >= 391) { await this.ExecAddRemove(input, ctx); } else if (this.CmdStartsWith(input, "add ") && this._gameAslVersion >= 391) { await this.ExecAddRemove(input, ctx); } else if (this.CmdStartsWith(input, "remove ") && this._gameAslVersion >= 391) { await this.ExecAddRemove(input, ctx); } else if (cmd == "save") { this._player.RequestSave(null); } else if (cmd == "quit") { this.GameFinished(); } else if (this.BeginsWith(cmd, "help")) { await this.ShowHelp(ctx); enteredHelpCommand = true; } else if (cmd == "about") { await this.ShowGameAbout(ctx); } else if (cmd == "clear") { this.DoClear(); } else if (cmd == "inventory" || cmd == "inv" || cmd == "i") { if (this._gameAslVersion >= 280) { for (var i = 1; i <= this._numberObjs; i++) { if (this._objs[i].ContainerRoom == "inventory" && this._objs[i].Exists && this._objs[i].Visible) { invList = invList + this._objs[i].Prefix; if (this._objs[i].ObjectAlias == "") { invList = invList + "|b" + this._objs[i].ObjectName + "|xb"; } else { invList = invList + "|b" + this._objs[i].ObjectAlias + "|xb"; } if (this._objs[i].Suffix != "") { invList = invList + " " + this._objs[i].Suffix; } invList = invList + ", "; } } } else { for (var j = 1; j <= this._numberItems; j++) { if (this._items[j].Got) { invList = invList + this._items[j].Name + ", "; } } } if (invList != "") { invList = Left(invList, Len(invList) - 2); invList = UCase(Left(invList, 1)) + Mid(invList, 2); var pos = 1; var lastComma: number = 0; var thisComma: number = 0; do { thisComma = InStrFrom(pos, invList, ","); if (thisComma != 0) { lastComma = thisComma; pos = thisComma + 1; } } while (!(thisComma == 0)); if (lastComma != 0) { invList = Left(invList, lastComma - 1) + " and" + Mid(invList, lastComma + 1); } await this.Print("You are carrying:|n" + invList + ".", ctx); } else { await this.Print("You are not carrying anything.", ctx); } } else if (this.CmdStartsWith(input, "oops ")) { await this.ExecOops(this.GetEverythingAfter(input, "oops "), ctx); } else if (this.CmdStartsWith(input, "the ")) { await this.ExecOops(this.GetEverythingAfter(input, "the "), ctx); } else { await this.PlayerErrorMessage(PlayerError.BadCommand, ctx); } } if (!skipAfterTurn) { // Execute any "afterturn" script: globalOverride = false; if (roomID != 0) { if (this._rooms[roomID].AfterTurnScript != "") { if (this.BeginsWith(this._rooms[roomID].AfterTurnScript, "override")) { await this.ExecuteScript(this.GetEverythingAfter(this._rooms[roomID].AfterTurnScript, "override"), ctx); globalOverride = true; } else { await this.ExecuteScript(this._rooms[roomID].AfterTurnScript, ctx); } } } if (this._afterTurnScript != "" && !globalOverride) { await this.ExecuteScript(this._afterTurnScript, ctx); } } await this.Print("", ctx); if (!dontSetIt) { // Use "DontSetIt" when we don't want "it" etc. to refer to the object used in this turn. // This is used for e.g. auto-remove object from container when taking. this._lastIt = this._thisTurnIt; this._lastItMode = this._thisTurnItMode; } if (this._badCmdBefore == oldBadCmdBefore) { this._badCmdBefore = ""; } return true; } CmdStartsWith(cmd: string, startsWith: string): boolean { // When we are checking user input in ExecCommand, we check things like whether // the player entered something beginning with "put ". We need to trim what the player entered // though, otherwise they might just type "put " and then we would try disambiguating an object // called "". return this.BeginsWith(Trim(cmd), startsWith); } async ExecGive(giveString: string, ctx: Context): Promise<void> { var article: string; var item: string; var character: string; var type: Thing; var id: number = 0; var script: string = ""; var toPos = InStr(giveString, " to "); if (toPos == 0) { toPos = InStr(giveString, " the "); if (toPos == 0) { await this.PlayerErrorMessage(PlayerError.BadGive, ctx); return; } else { item = Trim(Mid(giveString, toPos + 4, Len(giveString) - (toPos + 2))); character = Trim(Mid(giveString, 1, toPos)); } } else { item = Trim(Mid(giveString, 1, toPos)); character = Trim(Mid(giveString, toPos + 3, Len(giveString) - (toPos + 2))); } if (this._gameAslVersion >= 281) { type = Thing.Object; } else { type = Thing.Character; } // First see if player has "ItemToGive": if (this._gameAslVersion >= 280) { id = await this.Disambiguate(item, "inventory", ctx); if (id == -1) { await this.PlayerErrorMessage(PlayerError.NoItem, ctx); this._badCmdBefore = "give"; this._badCmdAfter = "to " + character; return; } else if (id == -2) { return; } else { article = this._objs[id].Article; } } else { // ASL2: var notGot = true; for (var i = 1; i <= this._numberItems; i++) { if (LCase(this._items[i].Name) == LCase(item)) { if (!this._items[i].Got) { notGot = true; break; } else { notGot = false; } } } if (notGot) { await this.PlayerErrorMessage(PlayerError.NoItem, ctx); return; } else { article = this._objs[id].Article; } } if (this._gameAslVersion >= 281) { var foundScript = false; var foundObject = false; var giveToId = await this.Disambiguate(character, this._currentRoom, ctx); if (giveToId > 0) { foundObject = true; } if (!foundObject) { if (giveToId != -2) { await this.PlayerErrorMessage(PlayerError.BadCharacter, ctx); } this._badCmdBefore = "give " + item + " to"; return; } //Find appropriate give script **** //now, for "give a to b", we have //ItemID=a and GiveToObjectID=b var o = this._objs[giveToId]; for (var i = 1; i <= o.NumberGiveData; i++) { if (o.GiveData[i].GiveType == GiveType.GiveSomethingTo && LCase(o.GiveData[i].GiveObject) == LCase(this._objs[id].ObjectName)) { foundScript = true; script = o.GiveData[i].GiveScript; break; } } if (!foundScript) { //check a for give to <b>: var g = this._objs[id]; for (var i = 1; i <= g.NumberGiveData; i++) { if (g.GiveData[i].GiveType == GiveType.GiveToSomething && LCase(g.GiveData[i].GiveObject) == LCase(this._objs[giveToId].ObjectName)) { foundScript = true; script = g.GiveData[i].GiveScript; break; } } } if (!foundScript) { //check b for give anything: script = this._objs[giveToId].GiveAnything; if (script != "") { foundScript = true; await this.SetStringContents("quest.give.object.name", this._objs[id].ObjectName, ctx); } } if (!foundScript) { //check a for give to anything: script = this._objs[id].GiveToAnything; if (script != "") { foundScript = true; await this.SetStringContents("quest.give.object.name", this._objs[giveToId].ObjectName, ctx); } } if (foundScript) { await this.ExecuteScript(script, ctx, id); } else { await this.SetStringContents("quest.error.charactername", this._objs[giveToId].ObjectName, ctx); var gender = Trim(this._objs[giveToId].Gender); gender = UCase(Left(gender, 1)) + Mid(gender, 2); await this.SetStringContents("quest.error.gender", gender, ctx); await this.SetStringContents("quest.error.article", article, ctx); await this.PlayerErrorMessage(PlayerError.ItemUnwanted, ctx); } } else { // ASL2: var block = this.GetThingBlock(character, this._currentRoom, type); if ((block.StartLine == 0 && block.EndLine == 0) || !this.IsAvailable(character + "@" + this._currentRoom, type, ctx)) { await this.PlayerErrorMessage(PlayerError.BadCharacter, ctx); return; } var realName = this._chars[this.GetThingNumber(character, this._currentRoom, type)].ObjectName; // now, see if there's a give statement for this item in // this characters definition: var giveLine = 0; for (var i = block.StartLine + 1; i <= block.EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], "give")) { var ItemCheck = await this.GetParameter(this._lines[i], ctx); if (LCase(ItemCheck) == LCase(item)) { giveLine = i; } } } if (giveLine == 0) { if (article == "") { article = "it"; } await this.SetStringContents("quest.error.charactername", realName, ctx); await this.SetStringContents("quest.error.gender", Trim(await this.GetGender(character, true, ctx)), ctx); await this.SetStringContents("quest.error.article", article, ctx); await this.PlayerErrorMessage(PlayerError.ItemUnwanted, ctx); return; } // now, execute the statement on GiveLine await this.ExecuteScript(this.GetSecondChunk(this._lines[giveLine]), ctx); } } async ExecLook(lookLine: string, ctx: Context): Promise<void> { var item: string; if (Trim(lookLine) == "look") { await this.ShowRoomInfo((this._currentRoom), ctx); } else { if (this._gameAslVersion < 391) { var atPos = InStr(lookLine, " at "); if (atPos == 0) { item = this.GetEverythingAfter(lookLine, "look "); } else { item = Trim(Mid(lookLine, atPos + 4)); } } else { if (this.BeginsWith(lookLine, "look at ")) { item = this.GetEverythingAfter(lookLine, "look at "); } else if (this.BeginsWith(lookLine, "look in ")) { item = this.GetEverythingAfter(lookLine, "look in "); } else if (this.BeginsWith(lookLine, "look on ")) { item = this.GetEverythingAfter(lookLine, "look on "); } else if (this.BeginsWith(lookLine, "look inside ")) { item = this.GetEverythingAfter(lookLine, "look inside "); } else { item = this.GetEverythingAfter(lookLine, "look "); } } if (this._gameAslVersion >= 280) { var id = await this.Disambiguate(item, "inventory;" + this._currentRoom, ctx); if (id <= 0) { if (id != -2) { await this.PlayerErrorMessage(PlayerError.BadThing, ctx); } this._badCmdBefore = "look at"; return; } await this.DoLook(id, ctx); } else { if (this.BeginsWith(item, "the ")) { item = this.GetEverythingAfter(item, "the "); } lookLine = this.RetrLine("object", item, "look", ctx); if (lookLine != "<unfound>") { //Check for availability if (!this.IsAvailable(item, Thing.Object, ctx)) { lookLine = "<unfound>"; } } if (lookLine == "<unfound>") { lookLine = this.RetrLine("character", item, "look", ctx); if (lookLine != "<unfound>") { if (!this.IsAvailable(item, Thing.Character, ctx)) { lookLine = "<unfound>"; } } if (lookLine == "<unfound>") { await this.PlayerErrorMessage(PlayerError.BadThing, ctx); return; } else if (lookLine == "<undefined>") { await this.PlayerErrorMessage(PlayerError.DefaultLook, ctx); return; } } else if (lookLine == "<undefined>") { await this.PlayerErrorMessage(PlayerError.DefaultLook, ctx); return; } var lookData = Trim(this.GetEverythingAfter(Trim(lookLine), "look ")); if (Left(lookData, 1) == "<") { var lookText = await this.GetParameter(lookLine, ctx); await this.Print(lookText, ctx); } else { await this.ExecuteScript(lookData, ctx); } } } } async ExecSpeak(cmd: string, ctx: Context): Promise<void> { if (this.BeginsWith(cmd, "the ")) { cmd = this.GetEverythingAfter(cmd, "the "); } var name = cmd; // if the "speak" parameter of the character c$'s definition // is just a parameter, say it - otherwise execute it as // a script. if (this._gameAslVersion >= 281) { var speakLine: string = ""; var ObjID = await this.Disambiguate(name, "inventory;" + this._currentRoom, ctx); if (ObjID <= 0) { if (ObjID != -2) { await this.PlayerErrorMessage(PlayerError.BadThing, ctx); } this._badCmdBefore = "speak to"; return; } var foundSpeak = false; // First look for action, then look // for property, then check define // section: var o = this._objs[ObjID]; for (var i = 1; i <= o.NumberActions; i++) { if (o.Actions[i].ActionName == "speak") { speakLine = "speak " + o.Actions[i].Script; foundSpeak = true; break; } } if (!foundSpeak) { for (var i = 1; i <= o.NumberProperties; i++) { if (o.Properties[i].PropertyName == "speak") { speakLine = "speak <" + o.Properties[i].PropertyValue + ">"; foundSpeak = true; break; } } } // For some reason ASL3 < 311 looks for a "look" tag rather than // having had this set up at initialisation. if (this._gameAslVersion < 311 && !foundSpeak) { for (var i = o.DefinitionSectionStart; i <= o.DefinitionSectionEnd; i++) { if (this.BeginsWith(this._lines[i], "speak ")) { speakLine = this._lines[i]; foundSpeak = true; } } } if (!foundSpeak) { await this.SetStringContents("quest.error.gender", UCase(Left(this._objs[ObjID].Gender, 1)) + Mid(this._objs[ObjID].Gender, 2), ctx); await this.PlayerErrorMessage(PlayerError.DefaultSpeak, ctx); return; } speakLine = this.GetEverythingAfter(speakLine, "speak "); if (this.BeginsWith(speakLine, "<")) { var text = await this.GetParameter(speakLine, ctx); if (this._gameAslVersion >= 350) { await this.Print(text, ctx); } else { await this.Print(Chr(34) + text + Chr(34), ctx); } } else { await this.ExecuteScript(speakLine, ctx, ObjID); } } else { var line = this.RetrLine("character", cmd, "speak", ctx); var type = Thing.Character; var data = Trim(this.GetEverythingAfter(Trim(line), "speak ")); if (line != "<unfound>" && line != "<undefined>") { // Character exists; but is it available?? if (!this.IsAvailable(cmd + "@" + this._currentRoom, type, ctx)) { line = "<undefined>"; } } if (line == "<undefined>") { await this.PlayerErrorMessage(PlayerError.BadCharacter, ctx); } else if (line == "<unfound>") { await this.SetStringContents("quest.error.gender", Trim(await this.GetGender(cmd, true, ctx)), ctx); await this.SetStringContents("quest.error.charactername", cmd, ctx); await this.PlayerErrorMessage(PlayerError.DefaultSpeak, ctx); } else if (this.BeginsWith(data, "<")) { data = await this.GetParameter(line, ctx); await this.Print(Chr(34) + data + Chr(34), ctx); } else { await this.ExecuteScript(data, ctx); } } } async ExecTake(item: string, ctx: Context): Promise<void> { var parentID: number = 0; var parentDisplayName: string; var foundItem = true; var foundTake = false; var id = await this.Disambiguate(item, this._currentRoom, ctx); if (id < 0) { foundItem = false; } else { foundItem = true; } if (!foundItem) { if (id != -2) { if (this._gameAslVersion >= 410) { id = await this.Disambiguate(item, "inventory", ctx); if (id >= 0) { // Player already has this item await this.PlayerErrorMessage(PlayerError.AlreadyTaken, ctx); } else { await this.PlayerErrorMessage(PlayerError.BadThing, ctx); } } else if (this._gameAslVersion >= 391) { await this.PlayerErrorMessage(PlayerError.BadThing, ctx); } else { await this.PlayerErrorMessage(PlayerError.BadItem, ctx); } } this._badCmdBefore = "take"; return; } else { await this.SetStringContents("quest.error.article", this._objs[id].Article, ctx); } var isInContainer = false; if (this._gameAslVersion >= 391) { var canAccessObject = this.PlayerCanAccessObject(id); if (!canAccessObject.CanAccessObject) { await this.PlayerErrorMessage_ExtendInfo(PlayerError.BadTake, ctx, canAccessObject.ErrorMsg); return; } var parent = this.GetObjectProperty("parent", id, false, false); parentID = this.GetObjectIdNoAlias(parent); } if (this._gameAslVersion >= 280) { var t = this._objs[id].Take; if (isInContainer && (t.Type == TextActionType.Default || t.Type == TextActionType.Text)) { // So, we want to take an object that's in a container or surface. So first // we have to remove the object from that container. if (this._objs[parentID].ObjectAlias != "") { parentDisplayName = this._objs[parentID].ObjectAlias; } else { parentDisplayName = this._objs[parentID].ObjectName; } await this.Print("(first removing " + this._objs[id].Article + " from " + parentDisplayName + ")", ctx); // Try to remove the object ctx.AllowRealNamesInCommand = true; await this.ExecCommand("remove " + this._objs[id].ObjectName, ctx, false, null, true); if (this.GetObjectProperty("parent", id, false, false) != "") { // removing the object failed return; } } if (t.Type == TextActionType.Default) { await this.PlayerErrorMessage(PlayerError.DefaultTake, ctx); await this.PlayerItem(item, true, ctx, id); } else if (t.Type == TextActionType.Text) { await this.Print(t.Data, ctx); await this.PlayerItem(item, true, ctx, id); } else if (t.Type == TextActionType.Script) { await this.ExecuteScript(t.Data, ctx, id); } else { await this.PlayerErrorMessage(PlayerError.BadTake, ctx); } } else { // find 'take' line for (var i = this._objs[id].DefinitionSectionStart + 1; i <= this._objs[id].DefinitionSectionEnd - 1; i++) { if (this.BeginsWith(this._lines[i], "take")) { var script = Trim(this.GetEverythingAfter(Trim(this._lines[i]), "take")); await this.ExecuteScript(script, ctx, id); foundTake = true; i = this._objs[id].DefinitionSectionEnd; } } if (!foundTake) { await this.PlayerErrorMessage(PlayerError.BadTake, ctx); } } } async ExecUse(useLine: string, ctx: Context): Promise<void> { var endOnWith: number = 0; var useDeclareLine = ""; var useOn: string; var useItem: string; useLine = Trim(this.GetEverythingAfter(useLine, "use ")); var roomId: number = 0; roomId = this.GetRoomId(this._currentRoom, ctx); var onWithPos = InStr(useLine, " on "); if (onWithPos == 0) { onWithPos = InStr(useLine, " with "); endOnWith = onWithPos + 4; } else { endOnWith = onWithPos + 2; } if (onWithPos != 0) { useOn = Trim(Right(useLine, Len(useLine) - endOnWith)); useItem = Trim(Left(useLine, onWithPos - 1)); } else { useOn = ""; useItem = useLine; } // see if player has this item: var id: number = 0; var notGotItem: boolean = false; if (this._gameAslVersion >= 280) { var foundItem = false; id = await this.Disambiguate(useItem, "inventory", ctx); if (id > 0) { foundItem = true; } if (!foundItem) { if (id != -2) { await this.PlayerErrorMessage(PlayerError.NoItem, ctx); } if (useOn == "") { this._badCmdBefore = "use"; } else { this._badCmdBefore = "use"; this._badCmdAfter = "on " + useOn; } return; } } else { notGotItem = true; for (var i = 1; i <= this._numberItems; i++) { if (LCase(this._items[i].Name) == LCase(useItem)) { if (!this._items[i].Got) { notGotItem = true; i = this._numberItems; } else { notGotItem = false; } } } if (notGotItem) { await this.PlayerErrorMessage(PlayerError.NoItem, ctx); return; } } var useScript: string = ""; var foundUseScript: boolean = false; var foundUseOnObject: boolean = false; var useOnObjectId: number = 0; var found: boolean = false; if (this._gameAslVersion >= 280) { foundUseScript = false; if (useOn == "") { if (this._gameAslVersion < 410) { var r = this._rooms[roomId]; for (var i = 1; i <= r.NumberUse; i++) { if (LCase(this._objs[id].ObjectName) == LCase(r.Use[i].Text)) { foundUseScript = true; useScript = r.Use[i].Script; break; } } } if (!foundUseScript) { useScript = this._objs[id].Use; if (useScript != "") { foundUseScript = true; } } } else { foundUseOnObject = false; useOnObjectId = await this.Disambiguate(useOn, this._currentRoom, ctx); if (useOnObjectId > 0) { foundUseOnObject = true; } else { useOnObjectId = await this.Disambiguate(useOn, "inventory", ctx); if (useOnObjectId > 0) { foundUseOnObject = true; } } if (!foundUseOnObject) { if (useOnObjectId != -2) { await this.PlayerErrorMessage(PlayerError.BadThing, ctx); } this._badCmdBefore = "use " + useItem + " on"; return; } //now, for "use a on b", we have //ItemID=a and UseOnObjectID=b //first check b for use <a>: var o = this._objs[useOnObjectId]; for (var i = 1; i <= o.NumberUseData; i++) { if (o.UseData[i].UseType == UseType.UseSomethingOn && LCase(o.UseData[i].UseObject) == LCase(this._objs[id].ObjectName)) { foundUseScript = true; useScript = o.UseData[i].UseScript; break; } } if (!foundUseScript) { //check a for use on <b>: var u = this._objs[id]; for (var i = 1; i <= u.NumberUseData; i++) { if (u.UseData[i].UseType == UseType.UseOnSomething && LCase(u.UseData[i].UseObject) == LCase(this._objs[useOnObjectId].ObjectName)) { foundUseScript = true; useScript = u.UseData[i].UseScript; break; } } } if (!foundUseScript) { //check b for use anything: useScript = this._objs[useOnObjectId].UseAnything; if (useScript != "") { foundUseScript = true; await this.SetStringContents("quest.use.object.name", this._objs[id].ObjectName, ctx); } } if (!foundUseScript) { //check a for use on anything: useScript = this._objs[id].UseOnAnything; if (useScript != "") { foundUseScript = true; await this.SetStringContents("quest.use.object.name", this._objs[useOnObjectId].ObjectName, ctx); } } } if (foundUseScript) { await this.ExecuteScript(useScript, ctx, id); } else { await this.PlayerErrorMessage(PlayerError.DefaultUse, ctx); } } else { if (useOn != "") { useDeclareLine = await this.RetrLineParam("object", useOn, "use", useItem, ctx); } else { found = false; for (var i = 1; i <= this._rooms[roomId].NumberUse; i++) { if (LCase(this._rooms[roomId].Use[i].Text) == LCase(useItem)) { useDeclareLine = "use <> " + this._rooms[roomId].Use[i].Script; found = true; break; } } if (!found) { useDeclareLine = this.FindLine(this.GetDefineBlock("game"), "use", useItem); } if (!found && useDeclareLine == "") { await this.PlayerErrorMessage(PlayerError.DefaultUse, ctx); return; } } if (useDeclareLine != "<unfound>" && useDeclareLine != "<undefined>" && useOn != "") { //Check for object availablity if (!this.IsAvailable(useOn, Thing.Object, ctx)) { useDeclareLine = "<undefined>"; } } if (useDeclareLine == "<undefined>") { useDeclareLine = await this.RetrLineParam("character", useOn, "use", useItem, ctx); if (useDeclareLine != "<undefined>") { //Check for character availability if (!this.IsAvailable(useOn, Thing.Character, ctx)) { useDeclareLine = "<undefined>"; } } if (useDeclareLine == "<undefined>") { await this.PlayerErrorMessage(PlayerError.BadThing, ctx); return; } else if (useDeclareLine == "<unfound>") { await this.PlayerErrorMessage(PlayerError.DefaultUse, ctx); return; } } else if (useDeclareLine == "<unfound>") { await this.PlayerErrorMessage(PlayerError.DefaultUse, ctx); return; } var script = Right(useDeclareLine, Len(useDeclareLine) - InStr(useDeclareLine, ">")); await this.ExecuteScript(script, ctx); } } ObjectActionUpdate(id: number, name: string, script: string, noUpdate: boolean = false): void { var objectName: string; var sp: number = 0; var ep: number = 0; name = LCase(name); if (!noUpdate) { if (name == "take") { this._objs[id].Take.Data = script; this._objs[id].Take.Type = TextActionType.Script; } else if (name == "use") { this.AddToUseInfo(id, script); } else if (name == "gain") { this._objs[id].GainScript = script; } else if (name == "lose") { this._objs[id].LoseScript = script; } else if (this.BeginsWith(name, "use ")) { name = this.GetEverythingAfter(name, "use "); if (InStr(name, "'") > 0) { sp = InStr(name, "'"); ep = InStrFrom(sp + 1, name, "'"); if (ep == 0) { this.LogASLError("Missing ' in 'action <use " + name + "> " + this.ReportErrorLine(script)); return; } objectName = Mid(name, sp + 1, ep - sp - 1); this.AddToUseInfo(id, Trim(Left(name, sp - 1)) + " <" + objectName + "> " + script); } else { this.AddToUseInfo(id, name + " " + script); } } else if (this.BeginsWith(name, "give ")) { name = this.GetEverythingAfter(name, "give "); if (InStr(name, "'") > 0) { sp = InStr(name, "'"); ep = InStrFrom(sp + 1, name, "'"); if (ep == 0) { this.LogASLError("Missing ' in 'action <give " + name + "> " + this.ReportErrorLine(script)); return; } objectName = Mid(name, sp + 1, ep - sp - 1); this.AddToGiveInfo(id, Trim(Left(name, sp - 1)) + " <" + objectName + "> " + script); } else { this.AddToGiveInfo(id, name + " " + script); } } } if (this._gameFullyLoaded) { this.AddToObjectChangeLog(AppliesTo.Object, this._objs[id].ObjectName, name, "action <" + name + "> " + script); } } async ExecuteIf(scriptLine: string, ctx: Context): Promise<void> { var ifLine = Trim(this.GetEverythingAfter(Trim(scriptLine), "if ")); var obscuredLine = this.ObliterateParameters(ifLine); var thenPos = InStr(obscuredLine, "then"); if (thenPos == 0) { var errMsg = "Expected 'then' missing from script statement '" + this.ReportErrorLine(scriptLine) + "' - statement bypassed."; this.LogASLError(errMsg, LogType.WarningError); return; } var conditions = Trim(Left(ifLine, thenPos - 1)); thenPos = thenPos + 4; var elsePos = InStr(obscuredLine, "else"); var thenEndPos: number = 0; if (elsePos == 0) { thenEndPos = Len(obscuredLine) + 1; } else { thenEndPos = elsePos - 1; } var thenScript = Trim(Mid(ifLine, thenPos, thenEndPos - thenPos)); var elseScript = ""; if (elsePos != 0) { elseScript = Trim(Right(ifLine, Len(ifLine) - (thenEndPos + 4))); } // Remove braces from around "then" and "else" script // commands, if present if (Left(thenScript, 1) == "{" && Right(thenScript, 1) == "}") { thenScript = Mid(thenScript, 2, Len(thenScript) - 2); } if (Left(elseScript, 1) == "{" && Right(elseScript, 1) == "}") { elseScript = Mid(elseScript, 2, Len(elseScript) - 2); } if (await this.ExecuteConditions(conditions, ctx)) { await this.ExecuteScript((thenScript), ctx); } else { if (elsePos != 0) { await this.ExecuteScript((elseScript), ctx); } } } async ExecuteScript(scriptLine: string, ctx: Context, newCallingObjectId: number = 0): Promise<void> { try { if (Trim(scriptLine) == "") { return; } if (this._gameFinished) { return; } if (InStr(scriptLine, "\n") > 0) { var curPos = 1; var finished = false; do { var crLfPos = InStrFrom(curPos, scriptLine, "\n"); if (crLfPos == 0) { finished = true; crLfPos = Len(scriptLine) + 1; } var curScriptLine = Trim(Mid(scriptLine, curPos, crLfPos - curPos)); if (curScriptLine != "\n") { await this.ExecuteScript(curScriptLine, ctx); } curPos = crLfPos + 1; } while (!(finished)); return; } if (newCallingObjectId != 0) { ctx.CallingObjectId = newCallingObjectId; } if (this.BeginsWith(scriptLine, "if ")) { await this.ExecuteIf(scriptLine, ctx); } else if (this.BeginsWith(scriptLine, "select case ")) { await this.ExecuteSelectCase(scriptLine, ctx); } else if (this.BeginsWith(scriptLine, "choose ")) { await this.ExecuteChoose(await this.GetParameter(scriptLine, ctx), ctx); } else if (this.BeginsWith(scriptLine, "set ")) { await this.ExecuteSet(this.GetEverythingAfter(scriptLine, "set "), ctx); } else if (this.BeginsWith(scriptLine, "inc ") || this.BeginsWith(scriptLine, "dec ")) { await this.ExecuteIncDec(scriptLine, ctx); } else if (this.BeginsWith(scriptLine, "say ")) { await this.Print(Chr(34) + await this.GetParameter(scriptLine, ctx) + Chr(34), ctx); } else if (this.BeginsWith(scriptLine, "do ")) { await this.ExecuteDo(await this.GetParameter(scriptLine, ctx), ctx); } else if (this.BeginsWith(scriptLine, "doaction ")) { await this.ExecuteDoAction(await this.GetParameter(scriptLine, ctx), ctx); } else if (this.BeginsWith(scriptLine, "give ")) { await this.PlayerItem(await this.GetParameter(scriptLine, ctx), true, ctx); } else if (this.BeginsWith(scriptLine, "lose ") || this.BeginsWith(scriptLine, "drop ")) { await this.PlayerItem(await this.GetParameter(scriptLine, ctx), false, ctx); } else if (this.BeginsWith(scriptLine, "msg ")) { await this.Print(await this.GetParameter(scriptLine, ctx), ctx); } else if (this.BeginsWith(scriptLine, "speak ")) { this.LogASLError("'speak' is not supported in this version of Quest", LogType.WarningError); } else if (this.BeginsWith(scriptLine, "helpmsg ")) { await this.Print(await this.GetParameter(scriptLine, ctx), ctx); } else if (Trim(LCase(scriptLine)) == "helpclose") { // This command does nothing in the Quest 5 player, as there is no separate help window } else if (this.BeginsWith(scriptLine, "goto ")) { await this.PlayGame(await this.GetParameter(scriptLine, ctx), ctx); } else if (this.BeginsWith(scriptLine, "playerwin")) { await this.FinishGame(StopType.Win, ctx); } else if (this.BeginsWith(scriptLine, "playerlose")) { await this.FinishGame(StopType.Lose, ctx); } else if (Trim(LCase(scriptLine)) == "stop") { await this.FinishGame(StopType.Null, ctx); } else if (this.BeginsWith(scriptLine, "playwav ")) { this.PlayWav(await this.GetParameter(scriptLine, ctx)); } else if (this.BeginsWith(scriptLine, "playmidi ")) { this.PlayMedia(await this.GetParameter(scriptLine, ctx)); } else if (this.BeginsWith(scriptLine, "playmp3 ")) { this.PlayMedia(await this.GetParameter(scriptLine, ctx)); } else if (Trim(LCase(scriptLine)) == "picture close") { } else if ((this._gameAslVersion >= 390 && this.BeginsWith(scriptLine, "picture popup ")) || (this._gameAslVersion >= 282 && this._gameAslVersion < 390 && this.BeginsWith(scriptLine, "picture ")) || (this._gameAslVersion < 282 && this.BeginsWith(scriptLine, "show "))) { // This command does nothing in the Quest 5 player, as there is no separate picture window await this.ShowPicture(await this.GetParameter(scriptLine, ctx)); } else if ((this._gameAslVersion >= 390 && this.BeginsWith(scriptLine, "picture "))) { this.ShowPictureInText(await this.GetParameter(scriptLine, ctx)); } else if (this.BeginsWith(scriptLine, "animate persist ")) { await this.ShowPicture(await this.GetParameter(scriptLine, ctx)); } else if (this.BeginsWith(scriptLine, "animate ")) { await this.ShowPicture(await this.GetParameter(scriptLine, ctx)); } else if (this.BeginsWith(scriptLine, "extract ")) { this.ExtractFile(await this.GetParameter(scriptLine, ctx)); } else if (this._gameAslVersion < 281 && this.BeginsWith(scriptLine, "hideobject ")) { this.SetAvailability(await this.GetParameter(scriptLine, ctx), false, ctx); } else if (this._gameAslVersion < 281 && this.BeginsWith(scriptLine, "showobject ")) { this.SetAvailability(await this.GetParameter(scriptLine, ctx), true, ctx); } else if (this._gameAslVersion < 281 && this.BeginsWith(scriptLine, "moveobject ")) { this.ExecMoveThing(await this.GetParameter(scriptLine, ctx), Thing.Object, ctx); } else if (this._gameAslVersion < 281 && this.BeginsWith(scriptLine, "hidechar ")) { this.SetAvailability(await this.GetParameter(scriptLine, ctx), false, ctx, Thing.Character); } else if (this._gameAslVersion < 281 && this.BeginsWith(scriptLine, "showchar ")) { this.SetAvailability(await this.GetParameter(scriptLine, ctx), true, ctx, Thing.Character); } else if (this._gameAslVersion < 281 && this.BeginsWith(scriptLine, "movechar ")) { this.ExecMoveThing(await this.GetParameter(scriptLine, ctx), Thing.Character, ctx); } else if (this._gameAslVersion < 281 && this.BeginsWith(scriptLine, "revealobject ")) { this.SetVisibility(await this.GetParameter(scriptLine, ctx), Thing.Object, true, ctx); } else if (this._gameAslVersion < 281 && this.BeginsWith(scriptLine, "concealobject ")) { this.SetVisibility(await this.GetParameter(scriptLine, ctx), Thing.Object, false, ctx); } else if (this._gameAslVersion < 281 && this.BeginsWith(scriptLine, "revealchar ")) { this.SetVisibility(await this.GetParameter(scriptLine, ctx), Thing.Character, true, ctx); } else if (this._gameAslVersion < 281 && this.BeginsWith(scriptLine, "concealchar ")) { this.SetVisibility(await this.GetParameter(scriptLine, ctx), Thing.Character, false, ctx); } else if (this._gameAslVersion >= 281 && this.BeginsWith(scriptLine, "hide ")) { this.SetAvailability(await this.GetParameter(scriptLine, ctx), false, ctx); } else if (this._gameAslVersion >= 281 && this.BeginsWith(scriptLine, "show ")) { this.SetAvailability(await this.GetParameter(scriptLine, ctx), true, ctx); } else if (this._gameAslVersion >= 281 && this.BeginsWith(scriptLine, "move ")) { this.ExecMoveThing(await this.GetParameter(scriptLine, ctx), Thing.Object, ctx); } else if (this._gameAslVersion >= 281 && this.BeginsWith(scriptLine, "reveal ")) { this.SetVisibility(await this.GetParameter(scriptLine, ctx), Thing.Object, true, ctx); } else if (this._gameAslVersion >= 281 && this.BeginsWith(scriptLine, "conceal ")) { this.SetVisibility(await this.GetParameter(scriptLine, ctx), Thing.Object, false, ctx); } else if (this._gameAslVersion >= 391 && this.BeginsWith(scriptLine, "open ")) { await this.SetOpenClose(await this.GetParameter(scriptLine, ctx), true, ctx); } else if (this._gameAslVersion >= 391 && this.BeginsWith(scriptLine, "close ")) { await this.SetOpenClose(await this.GetParameter(scriptLine, ctx), false, ctx); } else if (this._gameAslVersion >= 391 && this.BeginsWith(scriptLine, "add ")) { this.ExecAddRemoveScript(await this.GetParameter(scriptLine, ctx), true, ctx); } else if (this._gameAslVersion >= 391 && this.BeginsWith(scriptLine, "remove ")) { this.ExecAddRemoveScript(await this.GetParameter(scriptLine, ctx), false, ctx); } else if (this.BeginsWith(scriptLine, "clone ")) { this.ExecClone(await this.GetParameter(scriptLine, ctx), ctx); } else if (this.BeginsWith(scriptLine, "exec ")) { await this.ExecExec(scriptLine, ctx); } else if (this.BeginsWith(scriptLine, "setstring ")) { await this.ExecSetString(await this.GetParameter(scriptLine, ctx), ctx); } else if (this.BeginsWith(scriptLine, "setvar ")) { await this.ExecSetVar(await this.GetParameter(scriptLine, ctx), ctx); } else if (this.BeginsWith(scriptLine, "for ")) { await this.ExecFor(this.GetEverythingAfter(scriptLine, "for "), ctx); } else if (this.BeginsWith(scriptLine, "property ")) { this.ExecProperty(await this.GetParameter(scriptLine, ctx), ctx); } else if (this.BeginsWith(scriptLine, "type ")) { this.ExecType(await this.GetParameter(scriptLine, ctx), ctx); } else if (this.BeginsWith(scriptLine, "action ")) { await this.ExecuteAction(this.GetEverythingAfter(scriptLine, "action "), ctx); } else if (this.BeginsWith(scriptLine, "flag ")) { await this.ExecuteFlag(this.GetEverythingAfter(scriptLine, "flag "), ctx); } else if (this.BeginsWith(scriptLine, "create ")) { await this.ExecuteCreate(this.GetEverythingAfter(scriptLine, "create "), ctx); } else if (this.BeginsWith(scriptLine, "destroy exit ")) { await this.DestroyExit(await this.GetParameter(scriptLine, ctx), ctx); } else if (this.BeginsWith(scriptLine, "repeat ")) { await this.ExecuteRepeat(this.GetEverythingAfter(scriptLine, "repeat "), ctx); } else if (this.BeginsWith(scriptLine, "enter ")) { await this.ExecuteEnter(scriptLine, ctx); } else if (this.BeginsWith(scriptLine, "displaytext ")) { await this.DisplayTextSection(await this.GetParameter(scriptLine, ctx), ctx); } else if (this.BeginsWith(scriptLine, "helpdisplaytext ")) { await this.DisplayTextSection(await this.GetParameter(scriptLine, ctx), ctx); } else if (this.BeginsWith(scriptLine, "font ")) { this.SetFont(await this.GetParameter(scriptLine, ctx)); } else if (this.BeginsWith(scriptLine, "pause ")) { await this.Pause(parseInt(await this.GetParameter(scriptLine, ctx))); } else if (Trim(LCase(scriptLine)) == "clear") { this.DoClear(); } else if (Trim(LCase(scriptLine)) == "helpclear") { // This command does nothing in the Quest 5 player, as there is no separate help window } else if (this.BeginsWith(scriptLine, "background ")) { this.SetBackground(await this.GetParameter(scriptLine, ctx)); } else if (this.BeginsWith(scriptLine, "foreground ")) { this.SetForeground(await this.GetParameter(scriptLine, ctx)); } else if (Trim(LCase(scriptLine)) == "nointro") { this._autoIntro = false; } else if (this.BeginsWith(scriptLine, "debug ")) { this.LogASLError(await this.GetParameter(scriptLine, ctx), LogType.Misc); } else if (this.BeginsWith(scriptLine, "mailto ")) { // TODO: Just write HTML directly var emailAddress: string = await this.GetParameter(scriptLine, ctx); } else if (this.BeginsWith(scriptLine, "shell ") && this._gameAslVersion < 410) { this.LogASLError("'shell' is not supported in this version of Quest", LogType.WarningError); } else if (this.BeginsWith(scriptLine, "shellexe ") && this._gameAslVersion < 410) { this.LogASLError("'shellexe' is not supported in this version of Quest", LogType.WarningError); } else if (this.BeginsWith(scriptLine, "wait")) { await this.ExecuteWait(Trim(this.GetEverythingAfter(Trim(scriptLine), "wait")), ctx); } else if (this.BeginsWith(scriptLine, "timeron ")) { this.SetTimerState(await this.GetParameter(scriptLine, ctx), true); } else if (this.BeginsWith(scriptLine, "timeroff ")) { this.SetTimerState(await this.GetParameter(scriptLine, ctx), false); } else if (Trim(LCase(scriptLine)) == "outputon") { this._outPutOn = true; this.UpdateObjectList(ctx); await this.UpdateItems(ctx); } else if (Trim(LCase(scriptLine)) == "outputoff") { this._outPutOn = false; } else if (Trim(LCase(scriptLine)) == "panes off") { this._player.SetPanesVisible("off"); } else if (Trim(LCase(scriptLine)) == "panes on") { this._player.SetPanesVisible("on"); } else if (this.BeginsWith(scriptLine, "lock ")) { this.ExecuteLock(await this.GetParameter(scriptLine, ctx), true); } else if (this.BeginsWith(scriptLine, "unlock ")) { this.ExecuteLock(await this.GetParameter(scriptLine, ctx), false); } else if (this.BeginsWith(scriptLine, "playmod ") && this._gameAslVersion < 410) { this.LogASLError("'playmod' is not supported in this version of Quest", LogType.WarningError); } else if (this.BeginsWith(scriptLine, "modvolume") && this._gameAslVersion < 410) { this.LogASLError("'modvolume' is not supported in this version of Quest", LogType.WarningError); } else if (Trim(LCase(scriptLine)) == "dontprocess") { ctx.DontProcessCommand = true; } else if (this.BeginsWith(scriptLine, "return ")) { ctx.FunctionReturnValue = await this.GetParameter(scriptLine, ctx); } else { if (!this.BeginsWith(scriptLine, "'")) { this.LogASLError("Unrecognized keyword. Line reads: '" + Trim(this.ReportErrorLine(scriptLine)) + "'", LogType.WarningError); } } } catch (e) { await this.Print("[An internal error occurred]", ctx); this.LogASLError("Error - '" + e + "' occurred processing script line '" + scriptLine + "'", LogType.InternalError); } } async ExecuteEnter(scriptLine: string, ctx: Context): Promise<void> { this._commandOverrideModeOn = true; this._commandOverrideVariable = await this.GetParameter(scriptLine, ctx); // Now, wait for CommandOverrideModeOn to be set // to False by ExecCommand. Execution can then resume. var self = this; return new Promise<void>((resolve) => self._commandOverrideResolve = resolve); } async ExecuteSet(setInstruction: string, ctx: Context): Promise<void> { if (this._gameAslVersion >= 280) { if (this.BeginsWith(setInstruction, "interval ")) { var interval = await this.GetParameter(setInstruction, ctx); var scp = InStr(interval, ";"); if (scp == 0) { this.LogASLError("Too few parameters in 'set " + setInstruction + "'", LogType.WarningError); return; } var name = Trim(Left(interval, scp - 1)); interval = (Val(Trim(Mid(interval, scp + 1)))).toString(); var found = false; for (var i = 1; i <= this._numberTimers; i++) { if (LCase(name) == LCase(this._timers[i].TimerName)) { found = true; this._timers[i].TimerInterval = parseInt(interval); i = this._numberTimers; } } if (!found) { this.LogASLError("No such timer '" + name + "'", LogType.WarningError); return; } } else if (this.BeginsWith(setInstruction, "string ")) { await this.ExecSetString(await this.GetParameter(setInstruction, ctx), ctx); } else if (this.BeginsWith(setInstruction, "numeric ")) { await this.ExecSetVar(await this.GetParameter(setInstruction, ctx), ctx); } else if (this.BeginsWith(setInstruction, "collectable ")) { this.ExecuteSetCollectable(await this.GetParameter(setInstruction, ctx), ctx); } else { var result = await this.SetUnknownVariableType(await this.GetParameter(setInstruction, ctx), ctx); if (result == SetResult.Error) { this.LogASLError("Error on setting 'set " + setInstruction + "'", LogType.WarningError); } else if (result == SetResult.Unfound) { this.LogASLError("Variable type not specified in 'set " + setInstruction + "'", LogType.WarningError); } } } else { this.ExecuteSetCollectable(await this.GetParameter(setInstruction, ctx), ctx); } } FindStatement(block: DefineBlock, statement: string): string { // Finds a statement within a given block of lines for (var i = block.StartLine + 1; i <= block.EndLine - 1; i++) { // Ignore sub-define blocks if (this.BeginsWith(this._lines[i], "define ")) { do { i = i + 1; } while (!(Trim(this._lines[i]) == "end define")); } // Check to see if the line matches the statement // that is begin searched for if (this.BeginsWith(this._lines[i], statement)) { // Return the parameters between < and > : return this.GetSimpleParameter(this._lines[i]); } } return ""; } FindLine(block: DefineBlock, statement: string, statementParam: string): string { // Finds a statement within a given block of lines for (var i = block.StartLine + 1; i <= block.EndLine - 1; i++) { // Ignore sub-define blocks if (this.BeginsWith(this._lines[i], "define ")) { do { i = i + 1; } while (!(Trim(this._lines[i]) == "end define")); } // Check to see if the line matches the statement // that is begin searched for if (this.BeginsWith(this._lines[i], statement)) { if (UCase(Trim(this.GetSimpleParameter(this._lines[i]))) == UCase(Trim(statementParam))) { return Trim(this._lines[i]); } } } return ""; } GetCollectableAmount(name: string): number { for (var i = 1; i <= this._numCollectables; i++) { if (this._collectables[i].Name == name) { return this._collectables[i].Value; } } return 0; } GetSecondChunk(line: string): string { var endOfFirstBit = InStr(line, ">") + 1; var lengthOfKeyword = (Len(line) - endOfFirstBit) + 1; return Trim(Mid(line, endOfFirstBit, lengthOfKeyword)); } async GoDirection(direction: string, ctx: Context): Promise<void> { // leaves the current room in direction specified by // 'direction' var dirData: TextAction = new TextAction(); var id = this.GetRoomId(this._currentRoom, ctx); if (id == 0) { return; } if (this._gameAslVersion >= 410) { await this._rooms[id].Exits.ExecuteGo(direction, ctx); return; } var r = this._rooms[id]; if (direction == "north") { dirData = r.North; } else if (direction == "south") { dirData = r.South; } else if (direction == "west") { dirData = r.West; } else if (direction == "east") { dirData = r.East; } else if (direction == "northeast") { dirData = r.NorthEast; } else if (direction == "northwest") { dirData = r.NorthWest; } else if (direction == "southeast") { dirData = r.SouthEast; } else if (direction == "southwest") { dirData = r.SouthWest; } else if (direction == "up") { dirData = r.Up; } else if (direction == "down") { dirData = r.Down; } else if (direction == "out") { if (r.Out.Script == "") { dirData.Data = r.Out.Text; dirData.Type = TextActionType.Text; } else { dirData.Data = r.Out.Script; dirData.Type = TextActionType.Script; } } if (dirData.Type == TextActionType.Script && dirData.Data != "") { await this.ExecuteScript(dirData.Data, ctx); } else if (dirData.Data != "") { var newRoom = dirData.Data; var scp = InStr(newRoom, ";"); if (scp != 0) { newRoom = Trim(Mid(newRoom, scp + 1)); } await this.PlayGame(newRoom, ctx); } else { if (direction == "out") { await this.PlayerErrorMessage(PlayerError.DefaultOut, ctx); } else { await this.PlayerErrorMessage(PlayerError.BadPlace, ctx); } } } async GoToPlace(place: string, ctx: Context): Promise<void> { // leaves the current room in direction specified by // 'direction' var destination = ""; var placeData: string; var disallowed = false; placeData = this.PlaceExist(place, ctx); if (placeData != "") { destination = placeData; } else if (this.BeginsWith(place, "the ")) { var np = this.GetEverythingAfter(place, "the "); placeData = this.PlaceExist(np, ctx); if (placeData != "") { destination = placeData; } else { disallowed = true; } } else { disallowed = true; } if (destination != "") { if (InStr(destination, ";") > 0) { var s = Trim(Right(destination, Len(destination) - InStr(destination, ";"))); await this.ExecuteScript(s, ctx); } else { await this.PlayGame(destination, ctx); } } if (disallowed) { await this.PlayerErrorMessage(PlayerError.BadPlace, ctx); } } async InitialiseGame(filename: string, fromQsg: boolean, onSuccess: Callback, onFailure: Callback): Promise<void> { this._loadedFromQsg = fromQsg; this._changeLogRooms = new ChangeLog(); this._changeLogObjects = new ChangeLog(); this._changeLogRooms.AppliesToType = AppliesTo.Room; this._changeLogObjects.AppliesToType = AppliesTo.Object; this._outPutOn = true; this._useAbbreviations = true; var self = this; var doInitialise = function () { // Check version var gameBlock: DefineBlock; gameBlock = self.GetDefineBlock("game"); var aslVersion = "//"; for (var i = gameBlock.StartLine + 1; i <= gameBlock.EndLine - 1; i++) { if (self.BeginsWith(self._lines[i], "asl-version ")) { aslVersion = self.GetSimpleParameter(self._lines[i]); } } if (aslVersion == "//") { self.LogASLError("File contains no version header.", LogType.WarningError); } else { self._gameAslVersion = parseInt(aslVersion); var recognisedVersions = "/100/200/210/217/280/281/282/283/284/285/300/310/311/320/350/390/391/392/400/410/"; if (InStr(recognisedVersions, "/" + aslVersion + "/") == 0) { self.LogASLError("Unrecognised ASL version number.", LogType.WarningError); } } self._listVerbs[ListType.ExitsList] = ["Go to"]; if (self._gameAslVersion >= 280 && self._gameAslVersion < 390) { self._listVerbs[ListType.ObjectsList] = ["Look at", "Examine", "Take", "Speak to"]; self._listVerbs[ListType.InventoryList] = ["Look at", "Examine", "Use", "Drop"]; } else { self._listVerbs[ListType.ObjectsList] = ["Look at", "Take", "Speak to"]; self._listVerbs[ListType.InventoryList] = ["Look at", "Use", "Drop"]; } // Get the name of the game: self._gameName = self.GetSimpleParameter(self._lines[self.GetDefineBlock("game").StartLine]); self._player.UpdateGameName(self._gameName); self._player.Show("Panes"); self._player.Show("Location"); self._player.Show("Command"); self.SetUpGameObject(); self.SetUpOptions(); for (var i = self.GetDefineBlock("game").StartLine + 1; i <= self.GetDefineBlock("game").EndLine - 1; i++) { if (self.BeginsWith(self._lines[i], "beforesave ")) { self._beforeSaveScript = self.GetEverythingAfter(self._lines[i], "beforesave "); } else if (self.BeginsWith(self._lines[i], "onload ")) { self._onLoadScript = self.GetEverythingAfter(self._lines[i], "onload "); } } self.SetDefaultPlayerErrorMessages(); self.SetUpSynonyms(); self.SetUpRoomData(); if (self._gameAslVersion >= 410) { self.SetUpExits(); } if (self._gameAslVersion < 280) { // Set up an array containing the names of all the items // used in the game, based on the possitems statement // of the 'define game' block. self.SetUpItemArrays(); } if (self._gameAslVersion < 280) { // Now, go through the 'startitems' statement and set up // the items array so we start with those items mentioned. self.SetUpStartItems(); } // Set up collectables. self.SetUpCollectables(); self.SetUpDisplayVariables(); // Set up characters and objects. self.SetUpCharObjectInfo(); self.SetUpUserDefinedPlayerErrors(); self.SetUpDefaultFonts(); self.SetUpTurnScript(); self.SetUpTimers(); self._gameFileName = filename; self.LogASLError("Finished loading file.", LogType.Init); self._defaultRoomProperties = self.GetPropertiesInType("defaultroom", false); self._defaultProperties = self.GetPropertiesInType("default", false); onSuccess(); }; var onParseFailure = function () { self.LogASLError("Unable to open file", LogType.Init); var err = "Unable to open " + filename; if (self._openErrorReport) { // Strip last \n self._openErrorReport = Left(self._openErrorReport, Len(self._openErrorReport) - 1); err = err + ":\n\n" + self._openErrorReport; } self.DoPrint("Error: " + err); onFailure(); }; this.LogASLError("Opening file " + filename, LogType.Init); await this.ParseFile(filename, doInitialise, onParseFailure); await this.UpdateItems(this._nullContext); } PlaceExist(placeName: string, ctx: Context): string { // Returns actual name of an available "place" exit, and if // script is executed on going in that direction, that script // is returned after a ";" var roomId = this.GetRoomId(this._currentRoom, ctx); var foundPlace = false; var scriptPresent = false; // check if place is available var r = this._rooms[roomId]; for (var i = 1; i <= r.NumberPlaces; i++) { var checkPlace = r.Places[i].PlaceName; //remove any prefix and semicolon if (InStr(checkPlace, ";") > 0) { checkPlace = Trim(Right(checkPlace, Len(checkPlace) - (InStr(checkPlace, ";") + 1))); } var checkPlaceName = checkPlace; if (this._gameAslVersion >= 311 && r.Places[i].Script == "") { var destRoomId = this.GetRoomId(checkPlace, ctx); if (destRoomId != 0) { if (this._rooms[destRoomId].RoomAlias != "") { checkPlaceName = this._rooms[destRoomId].RoomAlias; } } } if (LCase(checkPlaceName) == LCase(placeName)) { foundPlace = true; if (r.Places[i].Script != "") { return checkPlace + ";" + r.Places[i].Script; } else { return checkPlace; } } } return ""; } async PlayerItem(item: string, got: boolean, ctx: Context, objId: number = 0): Promise<void> { // Gives the player an item (if got=True) or takes an // item away from the player (if got=False). // If ASL>280, setting got=TRUE moves specified // *object* to room "inventory"; setting got=FALSE // drops object into current room. var foundObjectName = false; if (this._gameAslVersion >= 280) { if (objId == 0) { for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ObjectName) == LCase(item)) { objId = i; break; } } } if (objId != 0) { if (got) { if (this._gameAslVersion >= 391) { // Unset parent information, if any this.AddToObjectProperties("not parent", objId, ctx); } this.MoveThing(this._objs[objId].ObjectName, "inventory", Thing.Object, ctx); if (this._objs[objId].GainScript != "") { await this.ExecuteScript(this._objs[objId].GainScript, ctx); } } else { this.MoveThing(this._objs[objId].ObjectName, this._currentRoom, Thing.Object, ctx); if (this._objs[objId].LoseScript != "") { await this.ExecuteScript(this._objs[objId].LoseScript, ctx); } } foundObjectName = true; } if (!foundObjectName) { this.LogASLError("No such object '" + item + "'", LogType.WarningError); } else { await this.UpdateItems(ctx); this.UpdateObjectList(ctx); } } else { for (var i = 1; i <= this._numberItems; i++) { if (this._items[i].Name == item) { this._items[i].Got = got; i = this._numberItems; } } await this.UpdateItems(ctx); } } async PlayGame(room: string, ctx: Context): Promise<void> { //plays the specified room var id = this.GetRoomId(room, ctx); if (id == 0) { this.LogASLError("No such room '" + room + "'", LogType.WarningError); return; } this._currentRoom = room; await this.SetStringContents("quest.currentroom", room, ctx); if (this._gameAslVersion >= 391 && this._gameAslVersion < 410) { this.AddToObjectProperties("visited", this._rooms[id].ObjId, ctx); } await this.ShowRoomInfo(room, ctx); await this.UpdateItems(ctx); // Find script lines and execute them. if (this._rooms[id].Script != "") { var script = this._rooms[id].Script; await this.ExecuteScript(script, ctx); } if (this._gameAslVersion >= 410) { this.AddToObjectProperties("visited", this._rooms[id].ObjId, ctx); } } async Print(txt: string, ctx: Context): Promise<void> { var printString = ""; if (txt == "") { this.DoPrint(printString); } else { for (var i = 1; i <= Len(txt); i++) { var printThis = true; if (Mid(txt, i, 2) == "|w") { this.DoPrint(printString); printString = ""; printThis = false; i = i + 1; await this.ExecuteScript("wait <>", ctx); } else if (Mid(txt, i, 2) == "|c") { switch (Mid(txt, i, 3)) { case "|cb": case "|cr": case "|cl": case "|cy": case "|cg": // Do nothing - we don't want to remove the colour formatting codes. break; default: this.DoPrint(printString); printString = ""; printThis = false; i = i + 1; await this.ExecuteScript("clear", ctx); break; } } if (printThis) { printString = printString + Mid(txt, i, 1); } } if (printString != "") { this.DoPrint(printString); } } } RetrLine(blockType: string, param: string, line: string, ctx: Context): string { var searchblock: DefineBlock; if (blockType == "object") { searchblock = this.GetThingBlock(param, this._currentRoom, Thing.Object); } else { searchblock = this.GetThingBlock(param, this._currentRoom, Thing.Character); } if (searchblock.StartLine == 0 && searchblock.EndLine == 0) { return "<undefined>"; } for (var i = searchblock.StartLine + 1; i <= searchblock.EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], line)) { return Trim(this._lines[i]); } } return "<unfound>"; } async RetrLineParam(blockType: string, param: string, line: string, lineParam: string, ctx: Context): Promise<string> { var searchblock: DefineBlock; if (blockType == "object") { searchblock = this.GetThingBlock(param, this._currentRoom, Thing.Object); } else { searchblock = this.GetThingBlock(param, this._currentRoom, Thing.Character); } if (searchblock.StartLine == 0 && searchblock.EndLine == 0) { return "<undefined>"; } for (var i = searchblock.StartLine + 1; i <= searchblock.EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], line) && LCase(await this.GetParameter(this._lines[i], ctx)) == LCase(lineParam)) { return Trim(this._lines[i]); } } return "<unfound>"; } SetUpCollectables(): void { var lastItem = false; this._numCollectables = 0; // Initialise collectables: // First, find the collectables section within the define // game block, and get its parameters: for (var a = this.GetDefineBlock("game").StartLine + 1; a <= this.GetDefineBlock("game").EndLine - 1; a++) { if (this.BeginsWith(this._lines[a], "collectables ")) { var collectables = Trim(this.GetSimpleParameter(this._lines[a])); // if collectables is a null string, there are no // collectables. Otherwise, there is one more object than // the number of commas. So, first check to see if we have // no objects: if (collectables != "") { this._numCollectables = 1; var pos = 1; do { if (!this._collectables) this._collectables = []; this._collectables[this._numCollectables] = new Collectable(); var nextComma = InStrFrom(pos + 1, collectables, ","); if (nextComma == 0) { nextComma = InStrFrom(pos + 1, collectables, ";"); } //If there are no more commas, we want everything //up to the end of the string, and then to exit //the loop: if (nextComma == 0) { nextComma = Len(collectables) + 1; lastItem = true; } //Get item info var info = Trim(Mid(collectables, pos, nextComma - pos)); this._collectables[this._numCollectables].Name = Trim(Left(info, InStr(info, " "))); var ep = InStr(info, "="); var sp1 = InStr(info, " "); var sp2 = InStrFrom(ep, info, " "); if (sp2 == 0) { sp2 = Len(info) + 1; } var t = Trim(Mid(info, sp1 + 1, ep - sp1 - 1)); var i = Trim(Mid(info, ep + 1, sp2 - ep - 1)); if (Left(t, 1) == "d") { t = Mid(t, 2); this._collectables[this._numCollectables].DisplayWhenZero = false; } else { this._collectables[this._numCollectables].DisplayWhenZero = true; } this._collectables[this._numCollectables].Type = t; this._collectables[this._numCollectables].Value = Val(i); // Get display string between square brackets var obp = InStr(info, "["); var cbp = InStr(info, "]"); if (obp == 0) { this._collectables[this._numCollectables].Display = "<def>"; } else { var b = Mid(info, obp + 1, (cbp - 1) - obp); this._collectables[this._numCollectables].Display = Trim(b); } pos = nextComma + 1; this._numCollectables = this._numCollectables + 1; //lastitem set when nextcomma=0, above. } while (!lastItem); this._numCollectables = this._numCollectables - 1; } } } } SetUpItemArrays(): void { var lastItem = false; this._numberItems = 0; // Initialise items: // First, find the possitems section within the define game // block, and get its parameters: for (var a = this.GetDefineBlock("game").StartLine + 1; a <= this.GetDefineBlock("game").EndLine - 1; a++) { if (this.BeginsWith(this._lines[a], "possitems ") || this.BeginsWith(this._lines[a], "items ")) { var possItems = this.GetSimpleParameter(this._lines[a]); if (possItems != "") { this._numberItems = this._numberItems + 1; var pos = 1; do { if (!this._items) this._items = []; this._items[this._numberItems] = new ItemType(); var nextComma = InStrFrom(pos + 1, possItems, ","); if (nextComma == 0) { nextComma = InStrFrom(pos + 1, possItems, ";"); } //If there are no more commas, we want everything //up to the end of the string, and then to exit //the loop: if (nextComma == 0) { nextComma = Len(possItems) + 1; lastItem = true; } //Get item name this._items[this._numberItems].Name = Trim(Mid(possItems, pos, nextComma - pos)); this._items[this._numberItems].Got = false; pos = nextComma + 1; this._numberItems = this._numberItems + 1; //lastitem set when nextcomma=0, above. } while (!lastItem); this._numberItems = this._numberItems - 1; } } } } SetUpStartItems(): void { var lastItem = false; for (var a = this.GetDefineBlock("game").StartLine + 1; a <= this.GetDefineBlock("game").EndLine - 1; a++) { if (this.BeginsWith(this._lines[a], "startitems ")) { var startItems = this.GetSimpleParameter(this._lines[a]); if (startItems != "") { var pos = 1; do { var nextComma = InStrFrom(pos + 1, startItems, ","); if (nextComma == 0) { nextComma = InStrFrom(pos + 1, startItems, ";"); } //If there are no more commas, we want everything //up to the end of the string, and then to exit //the loop: if (nextComma == 0) { nextComma = Len(startItems) + 1; lastItem = true; } //Get item name var name = Trim(Mid(startItems, pos, nextComma - pos)); //Find which item this is, and set it for (var i = 1; i <= this._numberItems; i++) { if (this._items[i].Name == name) { this._items[i].Got = true; break; } } pos = nextComma + 1; //lastitem set when nextcomma=0, above. } while (!lastItem); } } } } async ShowHelp(ctx: Context): Promise<void> { await this.Print("|b|cl|s14Quest Quick Help|xb|cb|s00", ctx); await this.Print("", ctx); await this.Print("|cl|bMoving|xb|cb Press the direction buttons in the 'Compass' pane, or type |bGO NORTH|xb, |bSOUTH|xb, |bE|xb, etc. |xn", ctx); await this.Print("To go into a place, type |bGO TO ...|xb . To leave a place, type |bOUT, EXIT|xb or |bLEAVE|xb, or press the '|crOUT|cb' button.|n", ctx); await this.Print("|cl|bObjects and Characters|xb|cb Use |bTAKE ...|xb, |bGIVE ... TO ...|xb, |bTALK|xb/|bSPEAK TO ...|xb, |bUSE ... ON|xb/|bWITH ...|xb, |bLOOK AT ...|xb, etc.|n", ctx); await this.Print("|cl|bMisc|xb|cb Type |bABOUT|xb to get information on the current game. The next turn after referring to an object or character, you can use |bIT|xb, |bHIM|xb etc. as appropriate to refer to it/him/etc. again. If you make a mistake when typing an object's name, type |bOOPS|xb followed by your correction.|n", ctx); await this.Print("|cl|bKeyboard shortcuts|xb|cb Press the |crup arrow|cb and |crdown arrow|cb to scroll through commands you have already typed in. Press |crEsc|cb to clear the command box.", ctx); } ReadCatalog(data: Uint8Array): void { var nullPos = data.indexOf(0); this._numResources = parseInt(this.DecryptString(data.slice(0, nullPos))); if (!this._resources) this._resources = []; data = data.slice(nullPos + 1); var resourceStart = 0; for (var i = 1; i <= this._numResources; i++) { this._resources[i] = new ResourceType(); var r = this._resources[i]; var nullPos = data.indexOf(0); r.ResourceName = this.DecryptString(data.slice(0, nullPos)); data = data.slice(nullPos + 1); nullPos = data.indexOf(0); r.ResourceLength = parseInt(this.DecryptString(data.slice(0, nullPos))); data = data.slice(nullPos + 1); r.ResourceStart = resourceStart; resourceStart = resourceStart + r.ResourceLength; r.Extracted = false; } } UpdateDirButtons(dirs: string, ctx: Context): void { var compassExits: ListData[] = []; if (InStr(dirs, "n") > 0) { this.AddCompassExit(compassExits, "north"); } if (InStr(dirs, "s") > 0) { this.AddCompassExit(compassExits, "south"); } if (InStr(dirs, "w") > 0) { this.AddCompassExit(compassExits, "west"); } if (InStr(dirs, "e") > 0) { this.AddCompassExit(compassExits, "east"); } if (InStr(dirs, "o") > 0) { this.AddCompassExit(compassExits, "out"); } if (InStr(dirs, "a") > 0) { this.AddCompassExit(compassExits, "northeast"); } if (InStr(dirs, "b") > 0) { this.AddCompassExit(compassExits, "northwest"); } if (InStr(dirs, "c") > 0) { this.AddCompassExit(compassExits, "southeast"); } if (InStr(dirs, "d") > 0) { this.AddCompassExit(compassExits, "southwest"); } if (InStr(dirs, "u") > 0) { this.AddCompassExit(compassExits, "up"); } if (InStr(dirs, "f") > 0) { this.AddCompassExit(compassExits, "down"); } this._compassExits = compassExits; this.UpdateExitsList(); } AddCompassExit(exitList: ListData[], name: string): void { exitList.push(new ListData(name, this._listVerbs[ListType.ExitsList])); } async UpdateDoorways(roomId: number, ctx: Context): Promise<string> { var roomDisplayText: string = ""; var outPlace: string = ""; var directions: string = ""; var nsew: string = ""; var outPlaceName: string = ""; var outPlacePrefix: string = ""; var n = "north"; var s = "south"; var e = "east"; var w = "west"; var ne = "northeast"; var nw = "northwest"; var se = "southeast"; var sw = "southwest"; var u = "up"; var d = "down"; var o = "out"; if (this._gameAslVersion >= 410) { var result = await this._rooms[roomId].Exits.GetAvailableDirectionsDescription(); roomDisplayText = result.Description; directions = result.List; } else { if (this._rooms[roomId].Out.Text != "") { outPlace = this._rooms[roomId].Out.Text; //remove any prefix semicolon from printed text var scp = InStr(outPlace, ";"); if (scp == 0) { outPlaceName = outPlace; } else { outPlaceName = Trim(Mid(outPlace, scp + 1)); outPlacePrefix = Trim(Left(outPlace, scp - 1)); outPlace = outPlacePrefix + " " + outPlaceName; } } if (this._rooms[roomId].North.Data != "") { nsew = nsew + "|b" + n + "|xb, "; directions = directions + "n"; } if (this._rooms[roomId].South.Data != "") { nsew = nsew + "|b" + s + "|xb, "; directions = directions + "s"; } if (this._rooms[roomId].East.Data != "") { nsew = nsew + "|b" + e + "|xb, "; directions = directions + "e"; } if (this._rooms[roomId].West.Data != "") { nsew = nsew + "|b" + w + "|xb, "; directions = directions + "w"; } if (this._rooms[roomId].NorthEast.Data != "") { nsew = nsew + "|b" + ne + "|xb, "; directions = directions + "a"; } if (this._rooms[roomId].NorthWest.Data != "") { nsew = nsew + "|b" + nw + "|xb, "; directions = directions + "b"; } if (this._rooms[roomId].SouthEast.Data != "") { nsew = nsew + "|b" + se + "|xb, "; directions = directions + "c"; } if (this._rooms[roomId].SouthWest.Data != "") { nsew = nsew + "|b" + sw + "|xb, "; directions = directions + "d"; } if (this._rooms[roomId].Up.Data != "") { nsew = nsew + "|b" + u + "|xb, "; directions = directions + "u"; } if (this._rooms[roomId].Down.Data != "") { nsew = nsew + "|b" + d + "|xb, "; directions = directions + "f"; } if (outPlace != "") { //see if outside has an alias var outPlaceAlias = this._rooms[this.GetRoomId(outPlaceName, ctx)].RoomAlias; if (outPlaceAlias == "") { outPlaceAlias = outPlace; } else { if (this._gameAslVersion >= 360) { if (outPlacePrefix != "") { outPlaceAlias = outPlacePrefix + " " + outPlaceAlias; } } } roomDisplayText = roomDisplayText + "You can go |bout|xb to " + outPlaceAlias + "."; if (nsew != "") { roomDisplayText = roomDisplayText + " "; } directions = directions + "o"; if (this._gameAslVersion >= 280) { await this.SetStringContents("quest.doorways.out", outPlaceName, ctx); } else { await this.SetStringContents("quest.doorways.out", outPlaceAlias, ctx); } await this.SetStringContents("quest.doorways.out.display", outPlaceAlias, ctx); } else { await this.SetStringContents("quest.doorways.out", "", ctx); await this.SetStringContents("quest.doorways.out.display", "", ctx); } if (nsew != "") { //strip final comma nsew = Left(nsew, Len(nsew) - 2); var cp = InStr(nsew, ","); if (cp != 0) { var finished = false; do { var ncp = InStrFrom(cp + 1, nsew, ","); if (ncp == 0) { finished = true; } else { cp = ncp; } } while (!(finished)); nsew = Trim(Left(nsew, cp - 1)) + " or " + Trim(Mid(nsew, cp + 1)); } roomDisplayText = roomDisplayText + "You can go " + nsew + "."; await this.SetStringContents("quest.doorways.dirs", nsew, ctx); } else { await this.SetStringContents("quest.doorways.dirs", "", ctx); } } this.UpdateDirButtons(directions, ctx); return roomDisplayText; } UpdateInventory(ctx: Context) { var invList: ListData[] = []; if (!this._outPutOn) { return; } var name: string; if (this._gameAslVersion >= 280) { for (var i = 1; i <= this._numberObjs; i++) { if (this._objs[i].ContainerRoom == "inventory" && this._objs[i].Exists && this._objs[i].Visible) { if (this._objs[i].ObjectAlias == "") { name = this._objs[i].ObjectName; } else { name = this._objs[i].ObjectAlias; } invList.push(new ListData(this.CapFirst(name), this._listVerbs[ListType.InventoryList])); } } } else { for (var j = 1; j <= this._numberItems; j++) { if (this._items[j].Got) { invList.push(new ListData(this.CapFirst(this._items[j].Name), this._listVerbs[ListType.InventoryList])); } } } this._player.UpdateInventoryList(invList); } UpdateCollectables(): void { if (this._numCollectables > 0) { var status: string = ""; for (var j = 1; j <= this._numCollectables; j++) { var k = this.DisplayCollectableInfo(j); if (k != "<null>") { if (status.length > 0) { status += "\n"; } status += k; } } this._player.SetStatusText(status); } } async UpdateItems(ctx: Context): Promise<void> { // displays the items a player has this.UpdateInventory(ctx); if (this._gameAslVersion >= 284) { await this.UpdateStatusVars(ctx); } else { this.UpdateCollectables(); } } async FinishGame(stopType: StopType, ctx: Context): Promise<void> { if (stopType == StopType.Win) { await this.DisplayTextSection("win", ctx); } else if (stopType == StopType.Lose) { await this.DisplayTextSection("lose", ctx); } this.GameFinished(); } UpdateObjectList(ctx: Context) { // Updates object list var shownPlaceName: string; var objSuffix: string; var charsViewable: string = ""; var charsFound: number = 0; var noFormatObjsViewable: string; var charList: string; var objsViewable: string = ""; var objsFound: number = 0; var objListString: string; var noFormatObjListString: string; if (!this._outPutOn) { return; } var objList: ListData[] = []; var exitList: ListData[] = []; //find the room var roomBlock: DefineBlock; roomBlock = this.DefineBlockParam("room", this._currentRoom); //FIND CHARACTERS === if (this._gameAslVersion < 281) { // go through Chars() array for (var i = 1; i <= this._numberChars; i++) { if (this._chars[i].ContainerRoom == this._currentRoom && this._chars[i].Exists && this._chars[i].Visible) { this.AddToObjectList(objList, exitList, this._chars[i].ObjectName, Thing.Character); charsViewable = charsViewable + this._chars[i].Prefix + "|b" + this._chars[i].ObjectName + "|xb" + this._chars[i].Suffix + ", "; charsFound = charsFound + 1; } } if (charsFound == 0) { this.SetStringContentsSimple("quest.characters", "", ctx); } else { //chop off final comma and add full stop (.) charList = Left(charsViewable, Len(charsViewable) - 2); this.SetStringContentsSimple("quest.characters", charList, ctx); } } //FIND OBJECTS noFormatObjsViewable = ""; for (var i = 1; i <= this._numberObjs; i++) { if (LCase(this._objs[i].ContainerRoom) == LCase(this._currentRoom) && this._objs[i].Exists && this._objs[i].Visible && !this._objs[i].IsExit) { objSuffix = this._objs[i].Suffix; if (objSuffix != "") { objSuffix = " " + objSuffix; } if (this._objs[i].ObjectAlias == "") { this.AddToObjectList(objList, exitList, this._objs[i].ObjectName, Thing.Object); objsViewable = objsViewable + this._objs[i].Prefix + "|b" + this._objs[i].ObjectName + "|xb" + objSuffix + ", "; noFormatObjsViewable = noFormatObjsViewable + this._objs[i].Prefix + this._objs[i].ObjectName + ", "; } else { this.AddToObjectList(objList, exitList, this._objs[i].ObjectAlias, Thing.Object); objsViewable = objsViewable + this._objs[i].Prefix + "|b" + this._objs[i].ObjectAlias + "|xb" + objSuffix + ", "; noFormatObjsViewable = noFormatObjsViewable + this._objs[i].Prefix + this._objs[i].ObjectAlias + ", "; } objsFound = objsFound + 1; } } if (objsFound != 0) { objListString = Left(objsViewable, Len(objsViewable) - 2); noFormatObjListString = Left(noFormatObjsViewable, Len(noFormatObjsViewable) - 2); this.SetStringContentsSimple("quest.objects", Left(noFormatObjsViewable, Len(noFormatObjsViewable) - 2), ctx); this.SetStringContentsSimple("quest.formatobjects", objListString, ctx); } else { this.SetStringContentsSimple("quest.objects", "", ctx); this.SetStringContentsSimple("quest.formatobjects", "", ctx); } //FIND DOORWAYS var roomId: number = 0; roomId = this.GetRoomId(this._currentRoom, ctx); if (roomId > 0) { if (this._gameAslVersion >= 410) { var places = this._rooms[roomId].Exits.GetPlaces(); for (var key in places) { var roomExit = places[key]; this.AddToObjectList(objList, exitList, roomExit.GetDisplayName(), Thing.Room); }; } else { var r = this._rooms[roomId]; for (var i = 1; i <= r.NumberPlaces; i++) { if (this._gameAslVersion >= 311 && this._rooms[roomId].Places[i].Script == "") { var placeId = this.GetRoomId(this._rooms[roomId].Places[i].PlaceName, ctx); if (placeId == 0) { shownPlaceName = this._rooms[roomId].Places[i].PlaceName; } else { if (this._rooms[placeId].RoomAlias != "") { shownPlaceName = this._rooms[placeId].RoomAlias; } else { shownPlaceName = this._rooms[roomId].Places[i].PlaceName; } } } else { shownPlaceName = this._rooms[roomId].Places[i].PlaceName; } this.AddToObjectList(objList, exitList, shownPlaceName, Thing.Room); } } } this._player.UpdateObjectsList(objList); this._gotoExits = exitList; this.UpdateExitsList(); } async UpdateStatusVars(ctx: Context): Promise<void> { var displayData: string; var status: string = ""; if (this._numDisplayStrings > 0) { for (var i = 1; i <= this._numDisplayStrings; i++) { displayData = await this.DisplayStatusVariableInfo(i, VarType.String, ctx); if (displayData != "") { if (status.length > 0) { status += "\n"; } status += displayData; } } } if (this._numDisplayNumerics > 0) { for (var i = 1; i <= this._numDisplayNumerics; i++) { displayData = await this.DisplayStatusVariableInfo(i, VarType.Numeric, ctx); if (displayData != "") { if (status.length > 0) { status += "\n"; } status += displayData; } } } this._player.SetStatusText(status); } UpdateVisibilityInContainers(ctx: Context, onlyParent: string = ""): void { // Use OnlyParent to only update objects that are contained by a specific parent var parentId: number = 0; var parent: string; var parentIsTransparent: boolean = false; var parentIsOpen: boolean = false; var parentIsSeen: boolean = false; var parentIsSurface: boolean = false; if (this._gameAslVersion < 391) { return; } if (onlyParent != "") { onlyParent = LCase(onlyParent); parentId = this.GetObjectIdNoAlias(onlyParent); parentIsOpen = this.IsYes(this.GetObjectProperty("opened", parentId, true, false)); parentIsTransparent = this.IsYes(this.GetObjectProperty("transparent", parentId, true, false)); parentIsSeen = this.IsYes(this.GetObjectProperty("seen", parentId, true, false)); parentIsSurface = this.IsYes(this.GetObjectProperty("surface", parentId, true, false)); } for (var i = 1; i <= this._numberObjs; i++) { // If object has a parent object parent = this.GetObjectProperty("parent", i, false, false); if (parent != "") { // Check if that parent is open, or transparent if (onlyParent == "") { parentId = this.GetObjectIdNoAlias(parent); parentIsOpen = this.IsYes(this.GetObjectProperty("opened", parentId, true, false)); parentIsTransparent = this.IsYes(this.GetObjectProperty("transparent", parentId, true, false)); parentIsSeen = this.IsYes(this.GetObjectProperty("seen", parentId, true, false)); parentIsSurface = this.IsYes(this.GetObjectProperty("surface", parentId, true, false)); } if (onlyParent == "" || (LCase(parent) == onlyParent)) { if (parentIsSurface || ((parentIsOpen || parentIsTransparent) && parentIsSeen)) { // If the parent is a surface, then the contents are always available. // Otherwise, only if the parent has been seen, AND is either open or transparent, // then the contents are available. this.SetAvailability(this._objs[i].ObjectName, true, ctx); } else { this.SetAvailability(this._objs[i].ObjectName, false, ctx); } } } } } PlayerCanAccessObject(id: number, colObjects: number[] = null): PlayerCanAccessObjectResult { // Called to see if a player can interact with an object (take it, open it etc.). // For example, if the object is on a surface which is inside a closed container, // the object cannot be accessed. var parent: string; var parentId: number = 0; var parentDisplayName: string; var result: PlayerCanAccessObjectResult = new PlayerCanAccessObjectResult(); var hierarchy: string = ""; if (this.IsYes(this.GetObjectProperty("parent", id, true, false))) { // Object is in a container... parent = this.GetObjectProperty("parent", id, false, false); parentId = this.GetObjectIdNoAlias(parent); // But if it's a surface then it's OK if (!this.IsYes(this.GetObjectProperty("surface", parentId, true, false)) && !this.IsYes(this.GetObjectProperty("opened", parentId, true, false))) { // Parent has no "opened" property, so it's closed. Hence // object can't be accessed if (this._objs[parentId].ObjectAlias != "") { parentDisplayName = this._objs[parentId].ObjectAlias; } else { parentDisplayName = this._objs[parentId].ObjectName; } result.CanAccessObject = false; result.ErrorMsg = "inside closed " + parentDisplayName; return result; } // Is the parent itself accessible? if (colObjects == null) { colObjects = []; } if (colObjects.indexOf(parentId) != -1) { // We've already encountered this parent while recursively calling // this function - we're in a loop of parents! colObjects.forEach(function (objId) { hierarchy = hierarchy + this._objs[objId].ObjectName + " -> "; }, this); hierarchy = hierarchy + this._objs[parentId].ObjectName; this.LogASLError("Looped object parents detected: " + hierarchy); result.CanAccessObject = false; return result; } colObjects.push(parentId); return this.PlayerCanAccessObject(parentId, colObjects); } result.CanAccessObject = true; return result; } GetGoToExits(roomId: number, ctx: Context): string { var placeList: string = ""; var shownPlaceName: string; for (var i = 1; i <= this._rooms[roomId].NumberPlaces; i++) { if (this._gameAslVersion >= 311 && this._rooms[roomId].Places[i].Script == "") { var placeId = this.GetRoomId(this._rooms[roomId].Places[i].PlaceName, ctx); if (placeId == 0) { this.LogASLError("No such room '" + this._rooms[roomId].Places[i].PlaceName + "'", LogType.WarningError); shownPlaceName = this._rooms[roomId].Places[i].PlaceName; } else { if (this._rooms[placeId].RoomAlias != "") { shownPlaceName = this._rooms[placeId].RoomAlias; } else { shownPlaceName = this._rooms[roomId].Places[i].PlaceName; } } } else { shownPlaceName = this._rooms[roomId].Places[i].PlaceName; } var shownPrefix = this._rooms[roomId].Places[i].Prefix; if (shownPrefix != "") { shownPrefix = shownPrefix + " "; } placeList = placeList + shownPrefix + "|b" + shownPlaceName + "|xb, "; } return placeList; } SetUpExits(): void { // Exits have to be set up after all the rooms have been initialised for (var i = 1; i <= this._numberSections; i++) { if (this.BeginsWith(this._lines[this._defineBlocks[i].StartLine], "define room ")) { var roomName = this.GetSimpleParameter(this._lines[this._defineBlocks[i].StartLine]); var roomId = this.GetRoomId(roomName, this._nullContext); for (var j = this._defineBlocks[i].StartLine + 1; j <= this._defineBlocks[i].EndLine - 1; j++) { if (this.BeginsWith(this._lines[j], "define ")) { //skip nested blocks var nestedBlock = 1; do { j = j + 1; if (this.BeginsWith(this._lines[j], "define ")) { nestedBlock = nestedBlock + 1; } else if (Trim(this._lines[j]) == "end define") { nestedBlock = nestedBlock - 1; } } while (!(nestedBlock == 0)); } this._rooms[roomId].Exits.AddExitFromTag(this._lines[j]); } } } return; } FindExit(tag: string): RoomExit { // e.g. Takes a tag of the form "room; north" and return's the north exit of room. var params = Split(tag, ";"); if (UBound(params) < 1) { this.LogASLError("No exit specified in '" + tag + "'", LogType.WarningError); return new RoomExit(this); } var room = Trim(params[0]); var exitName = Trim(params[1]); var roomId = this.GetRoomId(room, this._nullContext); if (roomId == 0) { this.LogASLError("Can't find room '" + room + "'", LogType.WarningError); return null; } var exits = this._rooms[roomId].Exits; var dir = exits.GetDirectionEnum(exitName); if (dir == Direction.None) { if (exits.GetPlaces()[exitName]) { return exits.GetPlaces()[exitName]; } } else { return exits.GetDirectionExit(dir); } return null; } ExecuteLock(tag: string, lock: boolean): void { var roomExit: RoomExit; roomExit = this.FindExit(tag); if (roomExit == null) { this.LogASLError("Can't find exit '" + tag + "'", LogType.WarningError); return; } roomExit.SetIsLocked(lock); } async DoBegin(): Promise<void> { var gameBlock: DefineBlock = this.GetDefineBlock("game"); var ctx: Context = new Context(); this.SetFont(""); this._player.SetFontSize(this._defaultFontSize); for (var i = this.GetDefineBlock("game").StartLine + 1; i <= this.GetDefineBlock("game").EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], "background ")) { this.SetBackground(await this.GetParameter(this._lines[i], this._nullContext)); } } for (var i = this.GetDefineBlock("game").StartLine + 1; i <= this.GetDefineBlock("game").EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], "foreground ")) { this.SetForeground(await this.GetParameter(this._lines[i], this._nullContext)); } } // Execute any startscript command that appears in the // "define game" block: this._autoIntro = true; // For ASL>=391, we only run startscripts if LoadMethod is normal (i.e. we haven't started // from a saved QSG file) if (this._gameAslVersion < 391 || (this._gameAslVersion >= 391 && this._gameLoadMethod == "normal")) { // for GameASLVersion 311 and later, any library startscript is executed first: if (this._gameAslVersion >= 311) { // We go through the game block executing these in reverse order, as // the statements which are included last should be executed first. for (var i = gameBlock.EndLine - 1; i >= gameBlock.StartLine + 1; i--) { if (this.BeginsWith(this._lines[i], "lib startscript ")) { ctx = this._nullContext; await this.ExecuteScript(Trim(this.GetEverythingAfter(Trim(this._lines[i]), "lib startscript ")), ctx); } } } for (var i = gameBlock.StartLine + 1; i <= gameBlock.EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], "startscript ")) { ctx = this._nullContext; await this.ExecuteScript(Trim(this.GetEverythingAfter(Trim(this._lines[i]), "startscript")), ctx); } else if (this.BeginsWith(this._lines[i], "lib startscript ") && this._gameAslVersion < 311) { ctx = this._nullContext; await this.ExecuteScript(Trim(this.GetEverythingAfter(Trim(this._lines[i]), "lib startscript ")), ctx); } } } this._gameFullyLoaded = true; // Display intro text if (this._autoIntro && this._gameLoadMethod == "normal") { await this.DisplayTextSection("intro", this._nullContext); } // Start game from room specified by "start" statement var startRoom: string = ""; for (var i = gameBlock.StartLine + 1; i <= gameBlock.EndLine - 1; i++) { if (this.BeginsWith(this._lines[i], "start ")) { startRoom = await this.GetParameter(this._lines[i], this._nullContext); } } if (!this._loadedFromQsg) { ctx = this._nullContext; await this.PlayGame(startRoom, ctx); await this.Print("", this._nullContext); } else { await this.UpdateItems(this._nullContext); await this.Print("Restored saved game", this._nullContext); await this.Print("", this._nullContext); await this.PlayGame(this._currentRoom, this._nullContext); await this.Print("", this._nullContext); if (this._gameAslVersion >= 391) { // For ASL>=391, OnLoad is now run for all games. ctx = this._nullContext; await this.ExecuteScript(this._onLoadScript, ctx); } } this.RaiseNextTimerTickRequest(); } Finish(): void { this.GameFinished(); } async SendCommand(command: string, elapsedTime?: number): Promise<void> { await this.ExecCommand(command, new Context()); if (elapsedTime > 0) { await this.Tick(elapsedTime); } else { this.RaiseNextTimerTickRequest(); } } async Initialise(onSuccess: Callback, onFailure: Callback): Promise<void> { if (LCase(Right(this._filename, 4)) == ".qsg" || this._data != null) { await this.OpenGame(this._filename, onSuccess, onFailure); } else { await this.InitialiseGame(this._filename, false, onSuccess, onFailure); } } GameFinished(): void { this._gameFinished = true; } GetResourcePath(filename: string): string { if (!this._resourceFile == null && this._resourceFile.length > 0) { var extractResult: string = this.ExtractFile(filename); return extractResult; } // TODO //return System.IO.Path.Combine(this._gamePath, filename); return null; } GetLibraryLines(libName: string): string[] { var lib = libraries[libName.toLowerCase()]; if (!lib) return null; return lib.split("\n"); } async Tick(elapsedTime: number): Promise<void> { var i: number = 0; var timerScripts: string[] = []; for (var i = 1; i <= this._numberTimers; i++) { if (this._timers[i].TimerActive) { if (this._timers[i].BypassThisTurn) { // don't trigger timer during the turn it was first enabled this._timers[i].BypassThisTurn = false; } else { this._timers[i].TimerTicks = this._timers[i].TimerTicks + elapsedTime; if (this._timers[i].TimerTicks >= this._timers[i].TimerInterval) { this._timers[i].TimerTicks = 0; timerScripts.push(this._timers[i].TimerAction); } } } } if (timerScripts.length > 0) { await this.RunTimer(timerScripts); } this.RaiseNextTimerTickRequest(); } async RunTimer(scripts: string[]): Promise<void> { await scripts.forEach(async function (script) { try { await this.ExecuteScript(script, this._nullContext); } catch (e) { } }, this); } RaiseNextTimerTickRequest(): void { var anyTimerActive: boolean = false; var nextTrigger: number = 60; for (var i = 1; i <= this._numberTimers; i++) { if (this._timers[i].TimerActive) { anyTimerActive = true; var thisNextTrigger: number = this._timers[i].TimerInterval - this._timers[i].TimerTicks; if (thisNextTrigger < nextTrigger) { nextTrigger = thisNextTrigger; } } } if (!anyTimerActive) { nextTrigger = 0; } if (this._gameFinished) { nextTrigger = 0; } this._player.RequestNextTimerTick(nextTrigger); } GetOriginalFilenameForQSG(): string { if (this._originalFilename != null) { return this._originalFilename; } return this._gameFileName; } GetFileData(filename: string, onSuccess: FileFetcherCallback, onFailure: FileFetcherCallback): void { this._fileFetcher(filename, onSuccess, onFailure); } async GetCASFileData(filename: string) : Promise<Uint8Array> { var self = this; return new Promise<Uint8Array>(function (resolve) { var onSuccess = function (data: Uint8Array) { resolve(data); }; var onFailure = function () { resolve(null); }; self._binaryFileFetcher(filename, onSuccess, onFailure); }); } DoPrint(text: string) { var output = this._textFormatter.OutputHTML(text); quest.print(output.text, !output.nobr); } async DoWait(): Promise<void> { this._player.DoWait(); return new Promise<void>(resolve => this._waitResolve = resolve); } EndWait() { this._waitResolve(); } Pause(duration: number): Promise<void> { return new Promise<void>(function (resolve) { setTimeout(function () { resolve(); }, duration); }); } async ExecuteIfAsk(question: string): Promise<boolean> { this._player.ShowQuestion(question); return new Promise<boolean>(resolve => this._askResolve = resolve); } SetQuestionResponse(response: string) { this._askResolve(response == "yes"); } UpdateExitsList() { // The Quest 5.0 Player takes a combined list of compass and "go to" exits, whereas the // ASL4 code produces these separately. So we keep track of them separately and then // merge to send to the Player. var mergedList: ListData[] = this._compassExits.concat(this._gotoExits); this._player.UpdateExitsList(mergedList); } async Begin(): Promise<void> { await this.DoBegin(); } async ShowMenu(menuData: MenuData): Promise<string> { this._player.ShowMenu(menuData); return new Promise<string>(resolve => this._menuResolve = resolve); } SetMenuResponse(response: string) { this._menuResolve(response); } DecryptString(input: Uint8Array): string { var result: string[] = []; for (var i = 0; i < input.length; i++) { result.push(Chr(input[i] ^ 255)); } return result.join(""); } DecryptItem(input: number): string { return Chr(input ^ 255); } } class ChangeLog { // NOTE: We only actually use the Object change log at the moment, as that is the only // one that has properties and actions. AppliesToType: AppliesTo; Changes: StringDictionary = {}; // appliesTo = room or object name // element = the thing that's changed, e.g. an action or property name // changeData = the actual change info AddItem(appliesTo: string, element: string, changeData: string): void { // the first four characters of the changeData will be "prop" or "acti", so we add this to the // key so that actions and properties don't collide. var key = appliesTo + "#" + Left(changeData, 4) + "~" + element; this.Changes[key] = changeData; } } class RoomExit { Id: string; _objId: number = 0; _roomId: number = 0; _direction: Direction; _parent: RoomExits; _objName: string; _displayName: string; // this could be a place exit's alias _game: LegacyGame; constructor(game: LegacyGame) { this._game = game; game._numberObjs = game._numberObjs + 1; if (!game._objs) game._objs = []; game._objs[game._numberObjs] = new ObjectType(); this._objId = game._numberObjs; var o = game._objs[this._objId]; o.IsExit = true; o.Visible = true; o.Exists = true; } SetExitProperty(propertyName: string, value: string): void { this._game.AddToObjectProperties(propertyName + "=" + value, this._objId, this._game._nullContext); } GetExitProperty(propertyName: string): string { return this._game.GetObjectProperty(propertyName, this._objId, false, false); } SetExitPropertyBool(propertyName: string, value: boolean): void { var sPropertyString: string; sPropertyString = propertyName; if (!value) { sPropertyString = "not " + sPropertyString; } this._game.AddToObjectProperties(sPropertyString, this._objId, this._game._nullContext); } GetExitPropertyBool(propertyName: string): boolean { return (this._game.GetObjectProperty(propertyName, this._objId, true, false) == "yes"); } SetAction(actionName: string, value: string): void { this._game.AddToObjectActions("<" + actionName + "> " + value, this._objId); } SetToRoom(value: string): void { this.SetExitProperty("to", value); this.UpdateObjectName(); } GetToRoom(): string { return this.GetExitProperty("to"); } SetPrefix(value: string): void { this.SetExitProperty("prefix", value); } GetPrefix(): string { return this.GetExitProperty("prefix"); } SetScript(value: string): void { if (Len(value) > 0) { this.SetAction("script", value); } } IsScript(): boolean { return this._game.HasAction(this._objId, "script"); } SetDirection(value: Direction): void { this._direction = value; if (value != Direction.None) { this.UpdateObjectName(); } } GetDirection(): Direction { return this._direction; } SetParent(value: RoomExits): void { this._parent = value; } GetParent(): RoomExits { return this._parent; } GetObjId(): number { return this._objId; } GetRoomId(): number { if (this._roomId == 0) { this._roomId = this._game.GetRoomId(this.GetToRoom(), this._game._nullContext); } return this._roomId; } GetDisplayName(): string { return this._displayName; } GetDisplayText(): string { return this._displayName; } SetIsLocked(value: boolean): void { this.SetExitPropertyBool("locked", value); } GetIsLocked(): boolean { return this.GetExitPropertyBool("locked"); } SetLockMessage(value: string): void { this.SetExitProperty("lockmessage", value); } GetLockMessage(): string { return this.GetExitProperty("lockmessage"); } async RunAction(actionName: string, ctx: Context): Promise<void> { await this._game.DoAction(this._objId, actionName, ctx); } async RunScript(ctx: Context): Promise<void> { await this.RunAction("script", ctx); } UpdateObjectName(): void { var objName: string; var lastExitId: number = 0; var parentRoom: string; if (Len(this._objName) > 0) { return; } if (this._parent == null) { return; } parentRoom = this._game._objs[this._parent.GetObjId()].ObjectName; objName = parentRoom; if (this._direction != Direction.None) { objName = objName + "." + this._parent.GetDirectionName(this._direction); this._game._objs[this._objId].ObjectAlias = this._parent.GetDirectionName(this._direction); } else { var lastExitIdString: string = this._game.GetObjectProperty("quest.lastexitid", (this._parent.GetObjId()), null, false); if (lastExitIdString.length == 0) { lastExitId = 0; } lastExitId = lastExitId + 1; this._game.AddToObjectProperties("quest.lastexitid=" + (lastExitId).toString(), (this._parent.GetObjId()), this._game._nullContext); objName = objName + ".exit" + (lastExitId).toString(); if (this.GetRoomId() == 0) { // the room we're pointing at might not exist, especially if this is a script exit this._displayName = this.GetToRoom(); } else { if (Len(this._game._rooms[this.GetRoomId()].RoomAlias) > 0) { this._displayName = this._game._rooms[this.GetRoomId()].RoomAlias; } else { this._displayName = this.GetToRoom(); } } this._game._objs[this._objId].ObjectAlias = this._displayName; this.SetPrefix(this._game._rooms[this.GetRoomId()].Prefix); } this._game._objs[this._objId].ObjectName = objName; this._game._objs[this._objId].ContainerRoom = parentRoom; this._objName = objName; } async Go(ctx: Context): Promise<void> { if (this.GetIsLocked()) { if (this.GetExitPropertyBool("lockmessage")) { await this._game.Print(this.GetExitProperty("lockmessage"), ctx); } else { await this._game.PlayerErrorMessage(PlayerError.Locked, ctx); } } else { if (this.IsScript()) { await this.RunScript(ctx); } else { await this._game.PlayGame(this.GetToRoom(), ctx); } } } } interface NumberRoomExitDictionary { [index: number]: RoomExit; } interface StringRoomExitDictionary { [index: string]: RoomExit; } class RoomExits { _directions: NumberRoomExitDictionary = {}; _places: StringRoomExitDictionary = {}; _objId: number = 0; _allExits: RoomExit[]; _regenerateAllExits: boolean; _game: LegacyGame; constructor(game: LegacyGame) { this._game = game; this._regenerateAllExits = true; } SetDirection(direction: Direction): RoomExit { var roomExit: RoomExit; if (this._directions[direction]) { roomExit = this._directions[direction]; this._game._objs[roomExit.GetObjId()].Exists = true; } else { roomExit = new RoomExit(this._game); this._directions[direction] = roomExit; } this._regenerateAllExits = true; return roomExit; } GetDirectionExit(direction: Direction): RoomExit { if (this._directions[direction]) { return this._directions[direction]; } return null; } AddPlaceExit(roomExit: RoomExit): void { this._places[roomExit.GetToRoom()] = roomExit; this._regenerateAllExits = true; } AddExitFromTag(tag: string): void { var thisDir: Direction; var roomExit: RoomExit = null; var params: string[] = []; var afterParam: string; var param: boolean = false; if (this._game.BeginsWith(tag, "out ")) { tag = this._game.GetEverythingAfter(tag, "out "); thisDir = Direction.Out; } else if (this._game.BeginsWith(tag, "east ")) { tag = this._game.GetEverythingAfter(tag, "east "); thisDir = Direction.East; } else if (this._game.BeginsWith(tag, "west ")) { tag = this._game.GetEverythingAfter(tag, "west "); thisDir = Direction.West; } else if (this._game.BeginsWith(tag, "north ")) { tag = this._game.GetEverythingAfter(tag, "north "); thisDir = Direction.North; } else if (this._game.BeginsWith(tag, "south ")) { tag = this._game.GetEverythingAfter(tag, "south "); thisDir = Direction.South; } else if (this._game.BeginsWith(tag, "northeast ")) { tag = this._game.GetEverythingAfter(tag, "northeast "); thisDir = Direction.NorthEast; } else if (this._game.BeginsWith(tag, "northwest ")) { tag = this._game.GetEverythingAfter(tag, "northwest "); thisDir = Direction.NorthWest; } else if (this._game.BeginsWith(tag, "southeast ")) { tag = this._game.GetEverythingAfter(tag, "southeast "); thisDir = Direction.SouthEast; } else if (this._game.BeginsWith(tag, "southwest ")) { tag = this._game.GetEverythingAfter(tag, "southwest "); thisDir = Direction.SouthWest; } else if (this._game.BeginsWith(tag, "up ")) { tag = this._game.GetEverythingAfter(tag, "up "); thisDir = Direction.Up; } else if (this._game.BeginsWith(tag, "down ")) { tag = this._game.GetEverythingAfter(tag, "down "); thisDir = Direction.Down; } else if (this._game.BeginsWith(tag, "place ")) { tag = this._game.GetEverythingAfter(tag, "place "); thisDir = Direction.None; } else { return; } if (thisDir != Direction.None) { // This will reuse an existing Exit object if we're resetting // the destination of an existing directional exit. roomExit = this.SetDirection(thisDir); } else { roomExit = new RoomExit(this._game); } roomExit.SetParent(this); roomExit.SetDirection(thisDir); if (this._game.BeginsWith(tag, "locked ")) { roomExit.SetIsLocked(true); tag = this._game.GetEverythingAfter(tag, "locked "); } if (Left(Trim(tag), 1) == "<") { params = Split(this._game.GetSimpleParameter(tag), ";"); afterParam = Trim(Mid(tag, InStr(tag, ">") + 1)); param = true; } else { afterParam = tag; } if (Len(afterParam) > 0) { // Script exit roomExit.SetScript(afterParam); if (thisDir == Direction.None) { // A place exit with a script still has a ToRoom roomExit.SetToRoom(params[0]); // and may have a lock message if (UBound(params) > 0) { roomExit.SetLockMessage(params[1]); } } else { // A directional exit with a script may have no parameter. // If it does have a parameter it will be a lock message. if (param) { roomExit.SetLockMessage(params[0]); } } } else { roomExit.SetToRoom(params[0]); if (UBound(params) > 0) { roomExit.SetLockMessage(params[1]); } } if (thisDir == Direction.None) { this.AddPlaceExit(roomExit); } } async AddExitFromCreateScript(script: string, ctx: Context): Promise<void> { // sScript is the "create exit ..." script, but without the "create exit" at the beginning. // So it's very similar to creating an exit from a tag, except we have the source room // name before the semicolon (which we don't even care about as we ARE the source room). var param: string; var params: string[]; var paramStart: number = 0; var paramEnd: number = 0; // Just need to convert e.g. // create exit <src_room; dest_room> { script } // to // place <dest_room> { script } // And // create exit north <src_room> { script } // to // north { script } // And // create exit north <src_room; dest_room> // to // north <dest_room> param = await this._game.GetParameter(script, ctx); params = Split(param, ";"); paramStart = InStr(script, "<"); paramEnd = InStrFrom(paramStart, script, ">"); if (paramStart > 1) { // Directional exit if (UBound(params) == 0) { // Script directional exit this.AddExitFromTag(Trim(Left(script, paramStart - 1)) + " " + Trim(Mid(script, paramEnd + 1))); } else { // "Normal" directional exit this.AddExitFromTag(Trim(Left(script, paramStart - 1)) + " <" + Trim(params[1]) + ">"); } } else { if (UBound(params) < 1) { this._game.LogASLError("No exit destination given in 'create exit " + script + "'", LogType.WarningError); return; } // Place exit so add "place" tag at the beginning this.AddExitFromTag("place <" + Trim(params[1]) + Mid(script, paramEnd)); } } SetObjId(value: number): void { this._objId = value; } GetObjId(): number { return this._objId; } GetPlaces(): StringRoomExitDictionary { return this._places; } async ExecuteGo(cmd: string, ctx: Context): Promise<void> { // This will handle "n", "go east", "go [to] library" etc. var exitId: number = 0; var roomExit: RoomExit; if (this._game.BeginsWith(cmd, "go to ")) { cmd = this._game.GetEverythingAfter(cmd, "go to "); } else if (this._game.BeginsWith(cmd, "go ")) { cmd = this._game.GetEverythingAfter(cmd, "go "); } exitId = await this._game.Disambiguate(cmd, this._game._currentRoom, ctx, true); if (exitId == -1) { await this._game.PlayerErrorMessage(PlayerError.BadPlace, ctx); } else { roomExit = this.GetExitByObjectId(exitId); await roomExit.Go(ctx); } } async GetAvailableDirectionsDescription(): Promise<GetAvailableDirectionsResult> { var roomExit: RoomExit; var count: number = 0; var descPrefix: string; var orString: string; descPrefix = "You can go"; orString = "or"; var list = ""; var description = ""; count = 0; var allExits = this.AllExits(); allExits.forEach(function (roomExit) { count = count + 1; list = list + this.GetDirectionToken(roomExit.GetDirection()); description = description + this.GetDirectionNameDisplay(roomExit); if (count < allExits.length - 1) { description = description + ", "; } else if (count == allExits.length - 1) { description = description + " " + orString + " "; } }, this); await this._game.SetStringContents("quest.doorways", description, this._game._nullContext); if (count > 0) { description = descPrefix + " " + description + "."; } var result = new GetAvailableDirectionsResult(); result.Description = description; result.List = list; return result; } GetDirectionName(dir: Direction): string { switch (dir) { case Direction.Out: return "out"; case Direction.North: return "north"; case Direction.South: return "south"; case Direction.East: return "east"; case Direction.West: return "west"; case Direction.NorthWest: return "northwest"; case Direction.NorthEast: return "northeast"; case Direction.SouthWest: return "southwest"; case Direction.SouthEast: return "southeast"; case Direction.Up: return "up"; case Direction.Down: return "down"; } return null; } GetDirectionEnum(dir: string): Direction { switch (dir) { case "out": return Direction.Out; case "north": return Direction.North; case "south": return Direction.South; case "east": return Direction.East; case "west": return Direction.West; case "northwest": return Direction.NorthWest; case "northeast": return Direction.NorthEast; case "southwest": return Direction.SouthWest; case "southeast": return Direction.SouthEast; case "up": return Direction.Up; case "down": return Direction.Down; } return Direction.None; } GetDirectionToken(dir: Direction): string { switch (dir) { case Direction.Out: return "o"; case Direction.North: return "n"; case Direction.South: return "s"; case Direction.East: return "e"; case Direction.West: return "w"; case Direction.NorthWest: return "b"; case Direction.NorthEast: return "a"; case Direction.SouthWest: return "d"; case Direction.SouthEast: return "c"; case Direction.Up: return "u"; case Direction.Down: return "f"; } return null; } GetDirectionNameDisplay(roomExit: RoomExit): string { if (roomExit.GetDirection() != Direction.None) { var dir = this.GetDirectionName(roomExit.GetDirection()); return "|b" + dir + "|xb"; } var display = "|b" + roomExit.GetDisplayName() + "|xb"; if (Len(roomExit.GetPrefix()) > 0) { display = roomExit.GetPrefix() + " " + display; } return "to " + display; } GetExitByObjectId(id: number): RoomExit { var result: RoomExit; this.AllExits().forEach(function (roomExit) { if (roomExit.GetObjId() == id) { result = roomExit; return; } }, this); return result; } AllExits(): RoomExit[] { if (!this._regenerateAllExits) { return this._allExits; } this._allExits = []; for (var dir in this._directions) { var roomExit = this._directions[dir]; if (this._game._objs[roomExit.GetObjId()].Exists) { this._allExits.push(this._directions[dir]); } }; for (var dir in this._places) { var roomExit = this._places[dir]; if (this._game._objs[roomExit.GetObjId()].Exists) { this._allExits.push(this._places[dir]); } }; return this._allExits; } RemoveExit(roomExit: RoomExit): void { // Don't remove directional exits, as if they're recreated // a new object will be created which will have the same name // as the old one. This is because we can't delete objects yet... if (roomExit.GetDirection() == Direction.None) { if (this._places[roomExit.GetToRoom()]) { delete this._places[roomExit.GetToRoom()]; } } this._game._objs[roomExit.GetObjId()].Exists = false; this._regenerateAllExits = true; } } class TextFormatterResult { text: string; nobr: boolean; } class TextFormatter { // the Player generates style tags for us // so all we need to do is have some kind of <color> <fontsize> <justify> tags etc. // it would actually be a really good idea for the player to handle the <wait> and <clear> tags too...? bold: boolean; italic: boolean; underline: boolean; colour: string = ""; fontSize: number = 0; defaultFontSize: number = 0; align: string = ""; fontFamily: string = ""; foreground: string = ""; OutputHTML(input: string): TextFormatterResult { var output: string = ""; var position: number = 0; var codePosition: number = 0; var finished: boolean = false; var nobr: boolean = false; input = input.replace(/&/g, "&amp;").replace(/\</g, "&lt;").replace(/\>/g, "&gt;").replace(/\n/g, "<br />"); if (Right(input, 3) == "|xn") { nobr = true; input = Left(input, Len(input) - 3); } do { codePosition = input.indexOf("|", position); if (codePosition == -1) { output += this.FormatText(input.substr(position)); finished = true; // can also have size codes } else { output += this.FormatText(input.substr(position, codePosition - position)); position = codePosition + 1; var oneCharCode: string = ""; var twoCharCode: string = ""; if (position < input.length) { oneCharCode = input.substr(position, 1); } if (position < (input.length - 1)) { twoCharCode = input.substr(position, 2); } var foundCode: boolean = true; switch (twoCharCode) { case "xb": this.bold = false; break; case "xi": this.italic = false; break; case "xu": this.underline = false; break; case "cb": this.colour = ""; break; case "cr": this.colour = "red"; break; case "cl": this.colour = "blue"; break; case "cy": this.colour = "yellow"; break; case "cg": this.colour = "green"; break; case "jl": this.align = ""; break; case "jc": this.align = "center"; break; case "jr": this.align = "right"; break; default: foundCode = false; break; } if (foundCode) { position += 2; } else { foundCode = true; switch (oneCharCode) { case "b": this.bold = true; break; case "i": this.italic = true; break; case "u": this.underline = true; break; case "n": output += "<br />"; break; default: foundCode = false; break; } if (foundCode) { position += 1; } } if (!foundCode) { if (oneCharCode == "s") { // |s00 |s10 etc. if (position < (input.length - 2)) { var sizeCode: string = input.substr(position + 1, 2); var fontSize: number = parseInt(sizeCode); if (!isNaN(fontSize)) { this.fontSize = fontSize; foundCode = true; position += 3; } } } } if (!foundCode) { output += "|"; } } } while (!(finished || position >= input.length)); var result = new TextFormatterResult(); result.text = output; result.nobr = nobr; return result; } FormatText(input: string): string { if (input.length == 0) { return input; } var output: string = ""; if (this.align.length > 0) { output += '<div style="text-align:' + this.align + '">'; } var fontSize = this.fontSize; if (fontSize == 0) fontSize = this.defaultFontSize; output += '<span style="font-family:' + this.fontFamily + ';font-size:' + fontSize.toString() + 'pt">'; if (this.colour.length > 0) { output += '<span style="color:' + this.colour + '">'; } else if (this.foreground.length > 0) { output += '<span style="color:' + this.foreground + '">'; } if (this.bold) { output += "<b>"; } if (this.italic) { output += "<i>"; } if (this.underline) { output += "<u>"; } output += input; if (this.underline) { output += "</u>"; } if (this.italic) { output += "</i>"; } if (this.bold) { output += "</b>"; } if (this.colour.length > 0) { output += "</span>"; } output += "</span>"; if (this.align.length > 0) { output += "</div>"; } return output; } } var libraries: StringDictionary = {}; libraries["stdverbs.lib"] = `!library !asl-version <400> !name <Additional verbs> !version <1.0> !author <Alex Warren> ! This library adds default responses for a number of common commands that players might use in a game. It also allows players to type multiple commands on the same command line. ' STDVERBS.LIB v1.0 ' for Quest 4.0 ' Copyright © 2007 Axe Software. Please do not modify this library. !addto game verb <buy> msg <You can't buy #(quest.lastobject):article#.> verb <climb> msg <You can't climb #(quest.lastobject):article#.> verb <drink> msg <You can't drink #(quest.lastobject):article#.> verb <eat> msg <You can't eat #(quest.lastobject):article#.> verb <hit> msg <You can't hit #(quest.lastobject):article#.> verb <kill> msg <You can't kill #(quest.lastobject):article#.> verb <kiss> msg <I don't think #(quest.lastobject):article# would like that.> verb <knock> msg <You can't knock #(quest.lastobject):article#.> verb <lick> msg <You can't lick #(quest.lastobject):article#.> verb <listen to> msg <You listen, but #(quest.lastobject):article# makes no sound.> verb <lock> msg <You can't lock #(quest.lastobject):article#.> verb <move> msg <You can't move #(quest.lastobject):article#.> verb <pull> msg <You can't pull #(quest.lastobject):article#.> verb <push> msg <You can't push #(quest.lastobject):article#.> verb <read> msg <You can't read #(quest.lastobject):article#.> verb <search> msg <You can't search #(quest.lastobject):article#.> verb <show> msg <You can't show #(quest.lastobject):article#.> verb <sit on> msg <You can't sit on #(quest.lastobject):article#.> verb <smell; sniff> msg <You sniff, but #(quest.lastobject):article# doesn't smell of much.> verb <taste> msg <You can't taste #(quest.lastobject):article#.> verb <throw> msg <You can't throw #(quest.lastobject):article#.> verb <tie> msg <You can't tie #(quest.lastobject):article#.> verb <touch> msg <You can't touch #(quest.lastobject):article#.> verb <turn on> msg <You can't turn #(quest.lastobject):article# on.> verb <turn off> msg <You can't turn #(quest.lastobject):article# off.> verb <turn> msg <You can't turn #(quest.lastobject):article#.> verb <unlock> msg <You can't unlock #(quest.lastobject):article#.> verb <untie> msg <You can't untie #(quest.lastobject):article#.> verb <wear> msg <You can't wear #(quest.lastobject):article#.> command <ask #stdverbs.command#> msg <You get no reply.> command <listen> msg <You can't hear much.> command <jump> msg <You jump, but nothing happens.> command <tell #stdverbs.command#> msg <You get no reply.> command <sit down; sleep> msg <No time for lounging about now.> command <wait> msg <Time passes.> command <xyzzy> msg <Surprisingly, absolutely nothing happens.> command <#stdverbs.command#. #stdverbs.command2#; _ #stdverbs.command#, then #stdverbs.command2#; _ #stdverbs.command#, and then #stdverbs.command2#; _ #stdverbs.command#, #stdverbs.command2#; _ #stdverbs.command# and then #stdverbs.command2#; _ #stdverbs.command# then #stdverbs.command2#> { exec <#stdverbs.command#> exec <#stdverbs.command2#> } command <#stdverbs.command#.> exec <#stdverbs.command#> !end`; libraries["standard.lib"] = `!library '---------------------------------------------------------------------- 'Filename: standard.lib 'Version: beta 3a ( minor bug fix of beta 3 ) 'Type: ASL Library ( for Quest 2.0/2.1 only ) 'By: A.G. Bampton (originally 10/08/1999) 'Revision: 21/12/1999 'Purpose/ See STDLIB.RTF for details of what this library does 'Usage: and how to use it. ' 'WARNING: I STRONGLY ADVISE YOU NEVER CHANGE ANY CODE IN THIS ' LIBRARY! It's complete and functional 'as is' and if ' it has been altered I will not be able to offer any ' support for it's use. Tailor/modify the way it works ' in external code - either within your 'ASL' game code ' or, IF YOU ARE USING QUEST PRO AND CAN COMPILE YOUR ' GAME TO A 'CAS' FILE ONLY, by including a customising ' library as per 'library_demo.asl' my standard library ' demo. '---------------------------------------------------------------------- !asl-version <200> !addto game command <look at #object#> do <Look_Proc> command <x #object#> do <Look_Proc> command <drop #object# in #container#> do <Put_In_Container_Proc> command <drop #object# down> do <Drop_Proc> command <drop #object#> do <Drop_Proc> command <give #give_com_string#> do <Alternate_Give_Proc> command <take #object# from #character#> do <Take_Back_Proc> command <take #character#'s #object#> do <Take_Back_Proc> command <take #character#s #object#> do <Take_Back_Proc> command <take #character#' #object#> do <Take_Back_Proc> command <take #object#> do <Special_Take_Proc> command <customdrop #object# in #container#> do <Put_In_Container_Proc> command <customdrop #object#> do <Drop_Proc> command <customtake #object# from #character#> do <Take_Back_Proc> command <customtake #object#> do <Special_Take_Proc> !end !addto synonyms examine; inspect = look at drop the; put the; put down the; put down; put = drop give back the; give back; give the = give get the; get; take back the; take back; take the = take out of the; out of; back from the; back from; from the = from in to; in to the; into the; into; inside the; inside = in back to the; back to; to the = to !end '------------------------------------------------------------------- 'The rest of this library is appended to the calling ASL file define procedure <Alternate_Give_Proc> setvar <found_to;0> for <to_true;1;$lengthof(#give_com_string#)$> do <to_test> if not is <%found_to%;0> then { exec <give #give_com_string#;normal> setvar <found_to;0> } else { for <space_true;1;$lengthof(#give_com_string#)$> do <space_test> setstring <give_char;$left(#give_com_string#;%found_space%)$> setstring <give_obj;$mid(#give_com_string#;%found_space%)$> exec <give #give_obj# to #give_char#;normal> } end define define procedure <to_test> setstring <to_test_for;$mid(o to c;2;4)$> setstring <test_part;$mid(#give_com_string#;%to_true%;4)$> if is <#to_test_for#;#test_part#> then setvar <found_to;%to_true%> end define define procedure <space_test> setstring <to_test_for;$mid(c o;2;1)$> setstring <test_part;$mid(#give_com_string#;%space_true%;1)$> if is <#to_test_for#;#test_part#> then setvar <found_space;%space_true%> end define define procedure <Look_Proc> if not is <#standard.lib.version#;> then { if is <$instr(#standard.lib.characters#;#object#)$;0> then { setstring <where_it_is;$locationof(#object#)$> if not is <$instr(#standard.lib.containers#;#where_it_is#)$;0> then { if not is <$instr(#standard.lib.characters#;#where_it_is#)$;0> then { if here <#where_it_is#> then { moveobject <#object#;#quest.currentroom#> showobject <#object#> exec <look at #object#;normal> moveobject <#object#;#where_it_is#> } else { exec <look at #object#;normal> } } else { if here <#where_it_is#> or got <#where_it_is#> then { moveobject <#object#;#quest.currentroom#> showobject <#object#> exec <look at #object#;normal> moveobject <#object#;#where_it_is#> } else { exec <look at #object#;normal> } } } else { if got <#object#> then { moveobject <#object#;#quest.currentroom#> showobject <#object#> exec <look at #object#;normal> do <Check_Contents_Proc> hideobject <#object#> moveobject <#object#;#where_it_is#> } else { exec <look at #object#;normal> if here <#object#> then { do <Check_Contents_Proc> } } } } else { exec <look at #object#;normal> if here <#object#> then { do <Check_Contents_Proc> } } } else { do <Old_Look_Proc> } end define define procedure <Check_Contents_Proc> if not is <$instr(#standard.lib.containers#;#object#)$;0> then { setstring <where_we_were;#quest.currentroom#> outputoff goto <#object#> if is <$lengthof(#quest.objects#)$;0> then { goto <#where_we_were#> outputon } else { setstring <parsed_list;$gettag(#object#;prefix)$ __ $parse_object_list$> goto <#where_we_were#> outputon msg <#parsed_list#> } } end define define function <parse_object_list> setvar <found_comma;0> for <last_comma;1;$lengthof(#quest.formatobjects#)$> { do <Last_Comma_Proc> } if not is <%found_comma%;0> then { setvar <remaining;%last_comma%-%found_comma%> setvar <remaining;%remaining%-1> setvar <found_comma;%found_comma%-1> setstring <left_part;$left(#quest.formatobjects#;__ %found_comma%)$> setstring <right_part;$right(#quest.formatobjects#;__ %remaining%)$> setstring <parsed_object_list;#left_part# and #right_part#.> } if is <%found_comma%;0> then { setstring <parsed_object_list;#quest.formatobjects#.> } return <#parsed_object_list#> end define define procedure <Last_Comma_Proc> setstring <test_part;$mid(#quest.formatobjects#;%last_comma%;1)$> if is <#test_part#;,> then setvar <found_comma;%last_comma%> end define define procedure <Drop_Proc> if is <$instr(#standard.lib.characters#;#object#)$;0> then { do <override_permitted> if is <#override#;yes> then { if got <#object#> then { lose <#object#> moveobject <#object#;#quest.currentroom#> showobject <#object#> setvar <custom_message; $lengthof(#std.lib.message.drop#)$> if is <%custom_message%; 0> then msg <You drop the #object#.> else msg <#std.lib.message.drop#.> } else { setvar <custom_message; $lengthof(#std.lib.message.notcarried#)$> if is <%custom_message%; 0> then msg <You're not holding the #object#.> else msg <#std.lib.message.notcarried#.> } } } else msg <Sorry, I don't understand '#quest.originalcommand#'.> end define define procedure <Special_Take_Proc> if not is <#standard.lib.version#;> then { if is <$instr(#standard.lib.characters#;#object#)$;0> then { do <override_permitted> if is <#override#;yes> then { setstring <where_it_is;$locationof(#object#)$> if not is <$instr(#standard.lib.containers#;#where_it_is#)$;0> then { if not is <$instr(#standard.lib.characters#;#where_it_is#)$;0> then { if here <#where_it_is#> then { exec <take #object# from #where_it_is#> } else exec <take #object#;normal> } else { if here <#where_it_is#> or got <#where_it_is#> then { exec <take #object# from #where_it_is#> } else exec <take #object#;normal> } } else { if got <#object#> then { setvar <custom_message; $lengthof(#std.lib.message.alreadygot#)$> if is <%custom_message%; 0> then { msg <You already have it.> } else { msg <#std.lib.message.alreadygot#.> } } else { if here <#object#> then { exec <take #object#;normal> } else { exec <take #object#;normal> } } } } } else msg <Sorry, I don't understand '#quest.originalcommand#'.> } else { do <Old_Special_Take_Proc> } end define define procedure <Take_Back_Proc> if not is <#standard.lib.version#;> then { if not is <$instr(#standard.lib.containers#;#character#)$;0> then { if is <$instr(#standard.lib.characters#;#character#)$;0> then { setstring <container;#character#> } else { setstring <container;#object#> } do <override_permitted> if is <#override#;yes> then { if here <#character#> or got <#container#> then { if is <$locationof(#object#)$;#character#> then { moveobject <#object#;#quest.currentroom#> give <#object#> hideobject <#object#> setvar <custom_message; $lengthof(#std.lib.message.takefrom#)$> if is <%custom_message%; 0> then { if is <$gettag(#character#;look)$;character> then { msg <You reach out and take the #object# from $capfirst(#character#)$.> } else msg <You take the #object# out of the #character#.> } else msg <#std.lib.message.takefrom#.> } else { setvar <custom_message; $lengthof(#std.lib.message.objnotheld#)$> if is <%custom_message%;0> then { if is <$gettag(#character#;look)$;character> then { msg <You can't do that, $capfirst(#character#)$ doesn't have the #object#.> } else msg <You can't do that, the #object# isn't in the #character#.> } else msg <#std.lib.message.objnotheld#.> } } else { setvar <custom_message; $lengthof(#std.lib.message.charnothere#)$> if is <%custom_message%; 0> then { if is <$gettag(#character#;look)$;character> then { msg <You can't do that, $capfirst(#character#)$ isn't here.> } else msg <You can't do that, the #character# isn't here.> } else msg <#std.lib.message.charnothere#.> } } } else msg <Sorry, I don't understand '#quest.originalcommand#'.> } else { do <Old_Take_Back_Proc> } end define define procedure <Put_In_Container_Proc> do <override_permitted> if is <#override#;yes> then { if is <#object#;#container#> then do <Put_In_Self_Proc> else { setstring <test_prefix;$gettag(#container#;prefix)$> if is <$lengthof(#test_prefix#)$;0> then do <Not_A_Container_Proc> else do <Put_In_Container_Verified_Proc> } } else msg <Sorry, I don't understand '#quest.originalcommand#'.> end define define procedure <Not_A_Container_Proc> setvar <custom_message; $lengthof(#std.lib.message.notacontainer#)$> if is <%custom_message%; 0> then msg <It's not possible to do that.> else msg <#std.library.message.notacontainer#.> end define define procedure <Put_In_Self_Proc> setvar <custom_message; $lengthof(#std.lib.message.putinself#)$> if is <%custom_message%; 0> then msg <That would be some feat if you could manage it!> else msg <#std.library.message.putinself#.> end define define procedure <Put_In_Container_Verified_Proc> if is <$gettag(#container#;look)$;character> then { msg <( assuming you meant "|iGive #object# to $capfirst(#container#)$"|xi. )> exec <give #object# to #container#> } else if is <$gettag(#object#;look)$;character> and here <#object#> then do <Put_Char_In_Obj_Proc> else if is <$gettag(#object#;look)$;character> then do <Character_Not_Here_Proc> else { if got <#object#> and got <#container#> then do <Put_It_In_Proc> else { if got <#object#> and here <#container#> then do <Put_It_In_Proc> else { if got <#object#> then do <No_Container_Here_Proc> else { do <Nothing_To_Put_In_Proc> } } } } end define define procedure <Put_Char_In_Obj_Proc> setvar <custom_message; $lengthof(#std.lib.message.putcharinobj#)$> if is <%custom_message%; 0> then msg <You can't do that with $capfirst(#object#)$.> else msg <#std.lib.message.putcharinobj#.> end define define procedure <No_Container_Here_Proc> setvar <custom_message; $lengthof(#std.lib.message.nocontainerhere#)$> if is <%custom_message%; 0> then msg <The #container# isn't available for you __ to put things in at the moment.> else msg <#std.library.message.nocontainerhere#.> end define define procedure <Character_Not_Here_Proc> setvar <custom_message; $lengthof(#std.lib.message.charnothere#)$> if is <%custom_message%; 0> then msg <$capfirst(#object#)$ isn't here.> else msg <#std.lib.message.charnothere#.> end define define procedure <Nothing_To_Put_In_Proc> setvar <custom_message; $lengthof(#std.lib.message.nothingtoputin#)$> if is <%custom_message%; 0> then msg <You don't appear to be holding the #object#.> else msg <#std.lib.message.nothingtoputin#.> end define define procedure <Put_It_In_Proc> lose <#object#> moveobject <#object#;#container#> showobject <#object#@#container#> setvar <custom_message; $lengthof(#std.lib.message.putincontainer#)$> if is <%custom_message%; 0> then msg <You put the #object# into the #container#.> else msg <#std.lib.message.putincontainer#.> end define define procedure <override_permitted> setstring <override;#reset#> if is <$left(#quest.command#;6)$;custom> then { if is <#std.lib.override#;yes> then { setstring <std.lib.override;#reset#> setstring <override;yes> } else { setstring <override;#reset#> } } else setstring <override;yes> end define define procedure <standard_lib_setup> setstring <reset;> setstring <std.lib.message.override;> setstring <std.lib.message.drop;> setstring <std.lib.message.notcarried;> setstring <std.lib.message.alreadygot;> setstring <std.lib.message.takefrom;> setstring <std.lib.message.objnotheld;> setstring <std.lib.message.charnothere;> setstring <std.lib.message.nocontainerhere;> setstring <std.lib.message.notacontainer;> setstring <std.lib.message.putincontainer;> setstring <std.lib.message.nothingtoputin;> setstring <std.lib.message.putcharinobj;> setstring <std.lib.message.putinself;> end define '==== Following code included for backward compatibility only ==== define procedure <Old_Look_Proc> if got <#object#> then { moveobject <#object#;#quest.currentroom#> showobject <#object#> exec <look at #object#;normal> do <Old_Contents_Proc> hideobject <#object#> } else { setstring <where_it_is;$locationof(#object#)$> if here <#where_it_is#> or got <#where_it_is#> then { moveobject <#object#;#quest.currentroom#> showobject <#object#> exec <look at #object#;normal> moveobject <#object#;#where_it_is#> do <Old_Contents_Proc> } else { exec <look at #object#;normal> do <Old_Contents_Proc> } } end define define procedure <Old_Contents_Proc> if is <$locationof(#object#)$;#quest.currentroom#> or got <#object#> then { setstring <Where_We_Were;#quest.currentroom#> outputoff goto <#object#> if is <$lengthof(#quest.objects#)$;0> then { goto <#Where_We_Were#> outputon } else { outputon msg <$gettag(#object#;prefix)$ #quest.formatobjects#.> outputoff goto <#Where_We_Were#> outputon } } end define define procedure <Old_Special_Take_Proc> do <override_permitted> if is <#override#;yes> then { setstring <where_it_is;$locationof(#object#)$> if here <#where_it_is#> or got <#where_it_is#> then exec <take #object# from #where_it_is#> else { if got <#object#> then { setvar <custom_message; $lengthof(#std.lib.message.alreadygot#)$> if is <%custom_message%; 0> then msg <You already have it.> else msg <#std.lib.message.alreadygot#.> } else exec <take #object#;normal> } } else msg <Sorry, I don't understand '#quest.originalcommand#'.> end define define procedure <Old_Take_Back_Proc> do <override_permitted> if is <#override#;yes> then { if here <#character#> or got <#character#> then { if is <$locationof(#object#)$;#character#> then { moveobject <#object#;#quest.currentroom#> give <#object#> hideobject <#object#> setvar <custom_message; $lengthof(#std.lib.message.takefrom#)$> if is <%custom_message%; 0> then { if is <$gettag(#character#;look)$;character> then { msg <You reach out and take the #object# from $capfirst(#character#)$.> } else msg <You take the #object# out of the #character#.> } else msg <#std.lib.message.takefrom#.> } else { setvar <custom_message; $lengthof(#std.lib.message.objnotheld#)$> if is <%custom_message%;0> then { if is <$gettag(#character#;look)$;character> then { msg <You can't do that, $capfirst(#character#)$ doesn't have the #object#.> } else msg <You can't do that, the #object# isn't in the #character#.> } else msg <#std.lib.message.objnotheld#.> } } else { setvar <custom_message; $lengthof(#std.lib.message.charnothere#)$> if is <%custom_message%; 0> then { if is <$gettag(#character#;look)$;character> then { msg <You can't do that, $capfirst(#character#)$ isn't here.> } else msg <You can't do that, the #character# isn't here.> } else msg <#std.lib.message.charnothere#.> } } else msg <Sorry, I don't understand '#quest.originalcommand#'.> end define `; libraries["q3ext.qlb"] = `!library !deprecated !asl-version <300> ' N.B. THIS IS RELEASE 6 FOR QUEST 3.02 OR LATER !addto game command <examine in #q3ext.qlb.object#> do <q3ext.qlb.ExamProc> command <examine #q3ext.qlb.object#> do <q3ext.qlb.ExamProc> command <look in #q3ext.qlb.object#> do <q3ext.qlb.ExamProc> command <look at #q3ext.qlb.object#> do <q3ext.qlb.LookProc> command <look #q3ext.qlb.object#> do <q3ext.qlb.LookProc> command <give #q3ext.qlb.give#> do <q3ext.qlb.GiveProc> command <drop #q3ext.qlb.object# in #q3ext.qlb.container#> do <q3ext.qlb.PutInProc> command <drop #q3ext.qlb.object#> exec <drop $q3ext.qlb.objname(#q3ext.qlb.object#)$;normal> command <take #q3ext.qlb.object# from #q3ext.qlb.container#> do <q3ext.qlb.TakeBackProc> command <take #q3ext.qlc.container#'s #q3ext.qlb.object#> do <q3ext.qlb.TakeBackProc> command <take #q3ext.qlb.container#s #q3ext.qlb.object#> do <q3ext.qlb.TakeBackProc> command <take #q3ext.qlb.container#' #q3ext.qlb.object#> do <q3ext.qlb.TakeBackProc> command <take #q3ext.qlb.object#> do <q3ext.qlb.SpecialTakeProc> command <read #q3ext.qlb.object#> do <q3ext.qlb.ReadProc> command <wear #q3ext.qlb.object#> do <q3ext.qlb.WearProc> command <unwear #q3ext.qlb.object#> do <q3ext.qlb.UnWearProc> command <open #q3ext.qlb.object#> do <q3ext.qlb.OpenProc> command <close #q3ext.qlb.object#> do <q3ext.qlb.CloseProc> !end !addto synonyms of; the = x = examine put; put down = drop give back = give pick up; pick; get; take back = take out of; back from = from in to; into; inside = in back to = to don; drop on = wear take off; remove = unwear shut = close talk = speak look at in = examine go = go to to to = to !end '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* This is a dummy room - only needed for the force_refresh procedure to function * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define room <q3ext.qlb.limbo> look <Just a dummy!> end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* This procedure implements an alternative room description - optional usage * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define procedure <q3ext.qlb.DescribeRoomProc> set string <q3ext.qlb.indescription;$gettag(#quest.currentroom#;indescription)$> if is <#q3ext.qlb.indescription#;> then { msg <|nYou are in $gettag(#quest.currentroom#;prefix)$ |b|cl#quest.currentroom#.|cb|xb|xn> } else { msg <|n#q3ext.qlb.indescription#$gettag(#quest.currentroom#;prefix)$ |b|cl#quest.currentroom#.|cb|xb|xn> } set string <q3ext.qlb.ObjList;> set string <q3ext.qlb.CharList;> for each object in <#quest.currentroom#> { if property <#quest.thing#;invisible> or property <#quest.thing#;hidden> then { } else { if property <#quest.thing#;human> then { set <q3ext.qlb.CharList;#q3ext.qlb.CharList# |b#quest.thing#|xb, > } else{ set <q3ext.qlb.ObjList;#q3ext.qlb.ObjList# $objectproperty(#quest.thing#;prefix)$> set <q3ext.qlb.ObjList;#q3ext.qlb.ObjList# |b#quest.thing#|xb, > } } } if ($lengthof(#q3ext.qlb.CharList#)$ >0) then { set numeric <q3ext.qlb.LengthOf;$lengthof(#q3ext.qlb.CharList#)$ - 1> set <q3ext.qlb.CharList;$left(#q3ext.qlb.CharList#;%q3ext.qlb.LengthOf%)$> set <q3ext.qlb.CharList;$q3ext.qlb.parsed(#q3ext.qlb.CharList#)$> if ($instr(#q3ext.qlb.CharList#;_and_)$ >0) then { msg < (#q3ext.qlb.CharList# are also here.)|xn> } else { msg < (#q3ext.qlb.CharList# is also here.)|xn> } } msg <|n|n$parameter(1)$|n> if ($lengthof(#q3ext.qlb.ObjList#)$ >0) then { set <q3ext.qlb.LengthOf;$lengthof(#q3ext.qlb.ObjList#)$ - 1> set <q3ext.qlb.ObjList;$left(#q3ext.qlb.ObjList#;%q3ext.qlb.LengthOf%)$> set <q3ext.qlb.ObjList;$q3ext.qlb.parsed(#q3ext.qlb.ObjList#)$> if ($instr(#q3ext.qlb.ObjList#;_and_)$ >0) then { msg <There are #q3ext.qlb.ObjList# here.|n> } else { msg <There is #q3ext.qlb.ObjList# here.|n> } } if not is <#quest.doorways.dirs#;> then { msg <You can move #quest.doorways.dirs#.> } if not is <#quest.doorways.places#;> then { msg <You can go to #quest.doorways.places#.> } if not is <#quest.doorways.out#;> then { msg <You can go out to |b#quest.doorways.out.display#|xb.> } end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* All regular 'take' commands are directed here to be tested for special needs * '* The code redirects to other procedures if object is in a container, and also * '* checks the player doesn't already have the item & prints message if he does. * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define procedure <q3ext.qlb.SpecialTakeProc> set string <q3ext.qlb.containedby;$q3ext.qlb.containedby$> if (#q3ext.qlb.containedby# = nil) then { if got <#q3ext.qlb.object#> then { msg <You already have the #q3ext.qlb.object#.> } else { exec <take #q3ext.qlb.object#;normal> } } else { do <q3ext.qlb.TakeBackProc> } end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* This code is called if an object is taken that is in a container * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define procedure <q3ext.qlb.TakeBackProc> set string <q3ext.qlb.containedby;$q3ext.qlb.containedby$> if (#q3ext.qlb.containedby# = nil) then { msg <(assuming you meant to take the #q3ext.qlb.object#).> exec <take #q3ext.qlb.object#> } else { if here <#q3ext.qlb.containedby#> or got <#q3ext.qlb.containedby#> then { if not property <#q3ext.qlb.containedby#; closed> then { move <#q3ext.qlb.object#;#quest.currentroom#> } } outputoff exec <take #q3ext.qlb.object#;normal> outputoff set string <q3ext.qlb.wherenow;#quest.currentroom#> goto <q3ext.qlb.limbo> goto <#q3ext.qlb.wherenow#> outputon if got <#q3ext.qlb.object#> then { if property <#q3ext.qlb.containedby#;human> then { msg <You take the #q3ext.qlb.object# from $capfirst(#q3ext.qlb.containedby#)$.> } else { msg <You take the #q3ext.qlb.object# out of the #q3ext.qlb.containedby#.> } } else { exec <take #q3ext.qlb.object#;normal> } } end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* Code called when an object is 'given to' or 'put into' a container * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define procedure <q3ext.qlb.GiveProc> set numeric <q3ext.qlb.ToPos;$instr(#q3ext.qlb.give#;_to_)$> if (%q3ext.qlb.ToPos% <> 0) then { set string <q3ext.qlb.GiveObj;$left(#q3ext.qlb.give#;%q3ext.qlb.ToPos%)$> set string <q3ext.qlb.GiveObj;$q3ext.qlb.realname(#q3ext.qlb.Giveobj#)$> set <q3ext.qlb.ToPos;%q3ext.qlb.ToPos% + 4> set string <q3ext.qlb.GiveTo;$mid(#q3ext.qlb.give#;%q3ext.qlb.ToPos%)$> set string <q3ext.qlb.GiveTo;$q3ext.qlb.realname(#q3ext.qlb.GiveTo#)$> if not property <#q3ext.qlb.GiveObj#; unworn> and action <#q3ext.qlb.GiveObj#;wear> then { msg <You'll have to take $objectproperty(#q3ext.qlb.GiveObj#;pronoun)$ off first.> } else { if here <#q3ext.qlb.GiveObj#> or got <#q3ext.qlb.GiveObj#> then { if here <#q3ext.qlb.GiveTo#> or got <#q3ext.qlb.GiveTo#> then { if property <#q3ext.qlb.GiveTo#;container> and not property <#q3ext.qlb.GiveTo#; closed> then { if got <#q3ext.qlb.GiveTo#> then { outputoff exec <drop #q3ext.qlb.GiveTo#> outputon exec <give #q3ext.qlb.GiveObj# to $q3ext.qlb.objname(#q3ext.qlb.GiveTo#)$; normal> outputoff exec <take #q3ext.qlb.GiveTo#> do <force_refresh> outputon } else { exec <give #q3ext.qlb.GiveObj# to $q3ext.qlb.objname(#q3ext.qlb.GiveTo#)$; normal> do <force_refresh> } } else { if property <#q3ext.qlb.GiveObj#;human > then { msg <You try, but $capfirst(#q3ext.qlb.GiveObj#)$ isn't interested.> } else { msg <Hard as you try, you find you cannot do that|xn> if property <#q3ext.qlb.GiveTo#; closed> then { msg < while the #q3ext.qlb.GiveTo# is closed.> } else { msg <.|n> } } } } else { if property <#q3ext.qlb.GiveTo#;human> then { msg <$capfirst(#q3ext.qlb.GiveObj#)$ isn't here.> } else { msg <The #q3ext.qlb.GiveTo# isn't available.> } } } else { if property <#q3ext.qlb.GiveObj#;human > then { msg <$capfirst(#q3ext.qlb.GiveObj#)$ isn't here.> } else { msg <The #q3ext.qlb.GiveObj# isn't available.> } } } } else { '*** Deals with 'Give character the object' style. for <q3ext.qlb.SpaceTrue;1;$lengthof(#q3ext.qlb.give#)$> do <q3ext.qlb.SpaceTest> set string <q3ext.qlb.GiveTo;$left(#q3ext.qlb.give#;%q3ext.qlb.FoundSpace%)$> set string <q3ext.qlb.GiveObj;$mid(#q3ext.qlb.give#;%q3ext.qlb.FoundSpace%)$> exec <give #q3ext.qlb.GiveObj# to #q3ext.qlb.GiveTo#> } end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* A utility procedure, called to find the positions of spaces in player input * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define procedure <q3ext.qlb.SpaceTest> set string <q3ext.qlb.Space;$mid(c o;2;1)$> set string <q3ext.qlb.TestPart;$mid(#q3ext.qlb.give#;%q3ext.qlb.SpaceTrue%;1)$> if is <#q3ext.qlb.space#;#q3ext.qlb.TestPart#> then set numeric <q3ext.qlb.FoundSpace;%q3ext.qlb.SpaceTrue%> end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* This procedure deals with examining containers & objects in containers. * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define procedure <q3ext.qlb.ExamProc> set <q3ext.qlb.object; $q3ext.qlb.objname(#q3ext.qlb.object#)$> set <q3ext.qlb.object; $q3ext.qlb.wornfix()$> set string <q3ext.qlb.containedby;$q3ext.qlb.containedby$> set string <q3ext.qlb.whereat;#quest.currentroom#> if (#q3ext.qlb.containedby# = nil) then { if action <#q3ext.qlb.object#; open> then { if property <#q3ext.qlb.object#; closed> then { if ($objectproperty(#q3ext.qlb.object#; closedexam)$ = null) then { msg <Nothing out of the ordinary.> } else { msg <$objectproperty(#q3ext.qlb.object#; closedexam)$.> } } else { if ($objectproperty(#q3ext.qlb.object#; openexam)$ = null) then { msg <Nothing out of the ordinary.> } else { msg <$objectproperty(#q3ext.qlb.object#; openexam)$.> } } } else { exec <examine #q3ext.qlb.object#;normal> } if property <#q3ext.qlb.object#;container> then { if here <#q3ext.qlb.object#> or got <#q3ext.qlb.object#> then { doaction <#q3ext.qlb.object#;contents> } } } else { if here <#q3ext.qlb.containedby#> or got <#q3ext.qlb.containedby#> then { if not property <#q3ext.qlb.containedby#; closed> then { outputoff goto <#q3ext.qlb.containedby#_inventory> outputon if action <#q3ext.qlb.object#; open> then { if property <#q3ext.qlb.object#; closed> then { if ($objectproperty(#q3ext.qlb.object#; closedexam)$ = null) then { msg <Nothing out of the ordinary.> } else { msg <$objectproperty(#q3ext.qlb.object#; closedexam)$.> } } else { if ($objectproperty(#q3ext.qlb.object#; openexam)$ = null) then { msg <Nothing out of the ordinary.> } else { msg <$objectproperty(#q3ext.qlb.object#; openexam)$.> } } } else { exec <examine #q3ext.qlb.object#;normal> } outputoff goto <#q3ext.qlb.whereat#> outputon } else { exec <examine #q3ext.qlb.object#;normal> } } else { exec <examine #q3ext.qlb.object#;normal> } } end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* This procedure deals with 'looking at' objects held in containers. * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define procedure <q3ext.qlb.LookProc> set <q3ext.qlb.object; $q3ext.qlb.realname(#q3ext.qlb.object#)$> set <q3ext.qlb.object; $q3ext.qlb.wornfix()$> set string <q3ext.qlb.containedby;$q3ext.qlb.containedby$> set string <q3ext.qlb.whereat;#quest.currentroom#> if (#q3ext.qlb.containedby# = nil) then { exec <look at $q3ext.qlb.objname(#q3ext.qlb.object#)$;normal> } else { if here <#q3ext.qlb.containedby#> or got <#q3ext.qlb.containedby#> then { if not property <#q3ext.qlb.containedby#; closed> then { outputoff goto <#q3ext.qlb.containedby#_inventory> outputon exec <look at $q3ext.qlb.objname(#q3ext.qlb.object#)$;normal> outputoff goto <#q3ext.qlb.whereat#> outputon } else { exec <look at $q3ext.qlb.objname(#q3ext.qlb.object#)$;normal> } } else { exec <look at $q3ext.qlb.objname(#q3ext.qlb.object#)$;normal> } } end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* Redirects 'put into' so that it is processed by the 'give to' routine, these * '* are functionally identical so no need to have duplicate code * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define procedure <q3ext.qlb.PutInProc> exec <give #q3ext.qlb.object# to #q3ext.qlb.container#> end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* A utility procedure, returns the position of the last comma in a passed string * '* Used to replace the last comma with 'and' when parsing output strings * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define procedure <q3ext.qlb.LastCommaProc> set string <q3ext.qlb.TestPart;$mid(#q3ext.qlb.Param#;%q3ext.qlb.LastComma%;1)$> if is <#q3ext.qlb.TestPart#;,> then set <q3ext.qlb.FoundComma;%q3ext.qlb.LastComma%> end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* The 'read' command procedure. * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define procedure <q3ext.qlb.ReadProc> set <q3ext.qlb.object;$q3ext.qlb.realname(#q3ext.qlb.object#)$> if property <#q3ext.qlb.object#;readable> then { doaction <#q3ext.qlb.object#;read> if not is <$objectproperty(#q3ext.qlb.object#;readaction)$; nil> then { doaction <#q3ext.qlb.object#;readaction> } } else { msg <There's nothing to read!> } end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* The 'wear' command procedure. * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define procedure <q3ext.qlb.WearProc> set <q3ext.qlb.object;$q3ext.qlb.realname(#q3ext.qlb.object#)$> msg <#q3ext.qlb.object#.....> if got <#q3ext.qlb.object#> then { if action <#q3ext.qlb.object#;wear> then { if ($objectproperty(#q3ext.qlb.object#;sex)$ = %q3ext.qlb.playersex%) then { do <q3ext.qlb.CheckWearProc> } else { msg <On second thoughts you decide that the |xn> msg <#q3ext.qlb.object# |xn> if (%q3ext.qlb.playersex% = 1) then { msg <won't suit a man like you at all.> } else { msg <won't suit a woman like you at all.> } } } else { msg <You cannot wear the #q3ext.qlb.object#.> } } else { msg <You are not carrying the #q3ext.qlb.object#.> } end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* The 'CheckWear' procedure - this checks the sense of wear commands * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define procedure <q3ext.qlb.CheckWearProc> set numeric <q3ext.qlb.wearable;0> if ($objectproperty(#q3ext.qlb.object#;topcover)$ <> 0) and __ ($objectproperty(#q3ext.qlb.object#;topcover)$ <= %q3ext.qlb.topcovered%) then { set <q3ext.qlb.wearable;%q3ext.qlb.wearable% + 1> } if ($objectproperty(#q3ext.qlb.object#;headcover)$ <> 0) and __ ($objectproperty(#q3ext.qlb.object#;headcover)$ <= %q3ext.qlb.headcovered%) then { set <q3ext.qlb.wearable;%q3ext.qlb.wearable% + 1> } if ($objectproperty(#q3ext.qlb.object#;feetcover)$ <> 0) and __ ($objectproperty(#q3ext.qlb.object#;feetcover)$ <= %q3ext.qlb.feetcovered%) then { set <q3ext.qlb.wearable;%q3ext.qlb.wearable% + 1> } if ($objectproperty(#q3ext.qlb.object#;handscover)$ <> 0) and __ ($objectproperty(#q3ext.qlb.object#;handscover)$ <= %q3ext.qlb.handscovered%) then { set <q3ext.qlb.wearable;%q3ext.qlb.wearable% + 1> } ' - disallow for coats (don't affect ability to put on lower torso clothes) set <q3ext.qlb.tempcovered;%q3ext.qlb.botcovered%> if (%q3ext.qlb.tempcovered% > 63) and __ ($objectproperty(#q3ext.qlb.object#;botcover)$ < 33) then { set <q3ext.qlb.tempcovered;%q3ext.qlb.tempcovered% - 64> } ' - disallow for skirts and dresses (like coats!) if (%q3ext.qlb.tempcovered% > 31) and __ ($objectproperty(#q3ext.qlb.object#;botcover)$ < 16) and __ ($objectproperty(#q3ext.qlb.object#;botcover)$ <> 4) then { set <q3ext.qlb.tempcovered;%q3ext.qlb.tempcovered% - 32> } ' - disallow wearing of skirts/dresses and trousers simultaneously if (%q3ext.qlb.tempcovered% > 15) then { set <q3ext.qlb.tempcovered;%q3ext.qlb.tempcovered% + 16> } if ($objectproperty(#q3ext.qlb.object#;botcover)$ <> 0) and __ ($objectproperty(#q3ext.qlb.object#;botcover)$ <= %q3ext.qlb.tempcovered%) then { set <q3ext.qlb.wearable;%q3ext.qlb.wearable% + 1> } if (%q3ext.qlb.wearable% =0) then { doaction <#q3ext.qlb.object#;wear> property <#q3ext.qlb.object#; not unworn> set <q3ext.qlb.topcovered;%q3ext.qlb.topcovered% + $objectproperty(#q3ext.qlb.object#;topcover)$> set <q3ext.qlb.headcovered;%q3ext.qlb.headcovered% + $objectproperty(#q3ext.qlb.object#;headcover)$> set <q3ext.qlb.handscovered;%q3ext.qlb.handscovered% + $objectproperty(#q3ext.qlb.object#;handscover)$> set <q3ext.qlb.feetcovered;%q3ext.qlb.feetcovered% + $objectproperty(#q3ext.qlb.object#;feetcover)$> set <q3ext.qlb.botcovered;%q3ext.qlb.botcovered% + $objectproperty(#q3ext.qlb.object#;botcover)$> } else { msg <Given what you are already wearing - that makes no sense at all.> } end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* The 'unwear' command procedure. * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define procedure <q3ext.qlb.UnWearProc> set <q3ext.qlb.object;$q3ext.qlb.realname(#q3ext.qlb.object#)$> if not property <#q3ext.qlb.object#; unworn> then { if action <#q3ext.qlb.object#;unwear> then { do <q3ext.qlb.CheckUnwearProc> } else { msg <You cannot do that.> } } else { msg <You aren't wearing the #q3ext.qlb.object#.> } end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* The 'CheckUnwear' procedure. * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define procedure <q3ext.qlb.CheckUnwearProc> set numeric <q3ext.qlb.wearable;0> set <q3ext.qlb.tempcovered; %q3ext.qlb.topcovered% /2> if ($objectproperty(#q3ext.qlb.object#;topcover)$ <> 0) and __ ($objectproperty(#q3ext.qlb.object#;topcover)$ <= %q3ext.qlb.tempcovered%) then { set <q3ext.qlb.wearable;%q3ext.qlb.wearable% + 1> } set <q3ext.qlb.tempcovered; %q3ext.qlb.headcovered% /2> if ($objectproperty(#q3ext.qlb.object#;headcover)$ <> 0) and __ ($objectproperty(#q3ext.qlb.object#;headcover)$ <= %q3ext.qlb.tempcovered%) then { set <q3ext.qlb.wearable;%q3ext.qlb.wearable% + 2> } set <q3ext.qlb.tempcovered; %q3ext.qlb.feetcovered% /2> if ($objectproperty(#q3ext.qlb.object#;feetcover)$ <> 0) and __ ($objectproperty(#q3ext.qlb.object#;feetcover)$ <= %q3ext.qlb.tempcovered%) then { set <q3ext.qlb.wearable;%q3ext.qlb.wearable% + 4> } set <q3ext.qlb.tempcovered; %q3ext.qlb.handscovered% /2> if ($objectproperty(#q3ext.qlb.object#;handscover)$ <> 0) and __ ($objectproperty(#q3ext.qlb.object#;handscover)$ <= %q3ext.qlb.tempcovered%) then { set <q3ext.qlb.wearable;%q3ext.qlb.wearable% + 8> } ' - disallow for coats (don't affect ability to take off lower torso clothes) set <q3ext.qlb.tempcovered;%q3ext.qlb.botcovered%> if (%q3ext.qlb.tempcovered% > 63) then { set <q3ext.qlb.tempcovered;%q3ext.qlb.tempcovered% - 64> } ' - disallow for skirts and dresses (like coats!) if (%q3ext.qlb.tempcovered% > 31) and __ ($objectproperty(#q3ext.qlb.object#;botcover)$ <> 4) then { set <q3ext.qlb.tempcovered;%q3ext.qlb.tempcovered% - 32> } set <q3ext.qlb.tempcovered;%q3ext.qlb.tempcovered% /2> if ($objectproperty(#q3ext.qlb.object#;botcover)$ <> 0) and __ ($objectproperty(#q3ext.qlb.object#;botcover)$ <= %q3ext.qlb.tempcovered%) then { set <q3ext.qlb.wearable;%q3ext.qlb.wearable% + 16> } if (%q3ext.qlb.wearable% =0) then { doaction <#q3ext.qlb.object#;unwear> property <#q3ext.qlb.object#; unworn> set <q3ext.qlb.topcovered;%q3ext.qlb.topcovered% - $objectproperty(#q3ext.qlb.object#;topcover)$> set <q3ext.qlb.headcovered;%q3ext.qlb.headcovered% - $objectproperty(#q3ext.qlb.object#;headcover)$> set <q3ext.qlb.handscovered;%q3ext.qlb.handscovered% - $objectproperty(#q3ext.qlb.object#;handscover)$> set <q3ext.qlb.feetcovered;%q3ext.qlb.feetcovered% - $objectproperty(#q3ext.qlb.object#;feetcover)$> set <q3ext.qlb.botcovered;%q3ext.qlb.botcovered% - $objectproperty(#q3ext.qlb.object#;botcover)$> } else { msg <Given what you are wearing, that isn't possible.> } end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* Open and close commands for 'openable' type * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define procedure <q3ext.qlb.OpenProc> set <q3ext.qlb.object; $q3ext.qlb.realname(#q3ext.qlb.object#)$> if action <#q3ext.qlb.object#; open> then { doaction <#q3ext.qlb.object#; open> } else msg <You can't do that.> end define define procedure <q3ext.qlb.CloseProc> set <q3ext.qlb.object; $q3ext.qlb.realname(#q3ext.qlb.object#)$> if action <#q3ext.qlb.object#; close> then { doaction <#q3ext.qlb.object#; close> } else msg <You can't do that.> end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* This forces the inventory window to be refreshed - Quest doesn't do it itself! * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define procedure <force_refresh> outputoff set string <q3ext.qlb.wherenow;#quest.currentroom#> goto <q3ext.qlb.limbo> goto <#q3ext.qlb.wherenow#> outputon end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* This is called to initialise the library * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define procedure <q3ext.qlb.setup> ' These are defaults - making the player male and naked! - it will probably be ' required to set these variables differently in the startscript AFTER calling ' this setup routine ' 'q3ext.qlb.playersex' should be set to 1 for a male player, 2 for a female. set numeric <q3ext.qlb.headcovered;0> set numeric <q3ext.qlb.handscovered;0> set numeric <q3ext.qlb.feetcovered;0> set numeric <q3ext.qlb.topcovered;0> set numeric <q3ext.qlb.botcovered;0> set numeric <q3ext.qlb.tempcovered;0> set numeric <q3ext.qlb.playersex;1> set numeric <q3ext.qlb.version;6> if (%q3ext.qlb.version% < $parameter(1)$) then { msg <WARNING!|n|nThis game requires Version $parameter(1)$ (or later) of _ the Q3EXT.QLB library, you appear to have Version %q3ext.qlb.version%. _ |n|nPlease obtain the latest release of the library before trying to run this _ game.|n|n|w> } end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* FUNCTION DEFINITIONS FOLLOW * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* Returns passed string that was comma separated list 'parsed' to read naturally. * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define function <q3ext.qlb.parsed> set numeric <q3ext.qlb.FoundComma;0> set string <q3ext.qlb.Param;$parameter(1)$> for <q3ext.qlb.LastComma;1;$lengthof(#q3ext.qlb.Param#)$> { do <q3ext.qlb.LastCommaProc> } if not is <%q3ext.qlb.FoundComma%;0> then { set numeric <q3ext.qlb.remaining;%q3ext.qlb.LastComma%-%q3ext.qlb.FoundComma%> set <q3ext.qlb.remaining;%q3ext.qlb.remaining%-1> set <q3ext.qlb.FoundComma;%q3ext.qlb.FoundComma%-1> set string <q3ext.qlb.LeftPart;$left(#q3ext.qlb.Param#;__ %q3ext.qlb.FoundComma%)$> set string <q3ext.qlb.RightPart;$right(#q3ext.qlb.Param#;__ %q3ext.qlb.remaining%)$> set string <q3ext.qlb.parsed;#q3ext.qlb.LeftPart# and #q3ext.qlb.RightPart#> } if is <%q3ext.qlb.FoundComma%;0> then { set string <q3ext.qlb.parsed;#q3ext.qlb.Param#> } return <#q3ext.qlb.parsed#> end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* The following function returns the name of the object in who's container the * '* looked at object is held, or 'nil' if the object isn't in a container. * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define function <q3ext.qlb.containedby> set <q3ext.qlb.object; $q3ext.qlb.realname(#q3ext.qlb.object#)$> set string <q3ext.qlb.containedby;$locationof(#q3ext.qlb.object#)$> set numeric <q3ext.qlb.LengthOf;$lengthof(#q3ext.qlb.containedby#)$> if (%q3ext.qlb.LengthOf% < 11) then { set <q3ext.qlb.containedby;nil> } if (%q3ext.qlb.LengthOf% > 11) then { set <q3ext.qlb.containedby;$right(#q3ext.qlb.containedby#;10)$> } if (#q3ext.qlb.containedby# <> _inventory) then { set <q3ext.qlb.containedby;nil> } if (#q3ext.qlb.containedby# = _inventory) then { set <q3ext.qlb.containedby;$locationof(#q3ext.qlb.object#)$> set <q3ext.qlb.LengthOf;%q3ext.qlb.LengthOf%-10> set <q3ext.qlb.containedby;$left(#q3ext.qlb.containedby#;%q3ext.qlb.LengthOf%)$> } return <#q3ext.qlb.containedby#> end define define function <q3ext.qlb.wornfix> set string <q3ext.qlb.wornfix;#q3ext.qlb.object#> if action <#q3ext.qlb.object#; wear> and not property <#q3ext.qlb.object#; unworn> then { set <q3ext.qlb.wornfix;#q3ext.qlb.object# [worn]> } return <#q3ext.qlb.wornfix#> end define define function <q3ext.qlb.objname> set string <q3ext.qlb.objname;$parameter(1)$> set <q3ext.qlb.objname;$q3ext.qlb.realname(#q3ext.qlb.objname#)$> set <q3ext.qlb.objname;$displayname(#q3ext.qlb.objname#)$> return <#q3ext.qlb.objname#> end define define function <q3ext.qlb.realname> set numeric <q3ext.qlb.found;0> set string <q3ext.qlb.objname;$parameter(1)$> set string <q3ext.qlb.lobjname;$lcase(#q3ext.qlb.objname#)$> for each object in <#quest.currentroom#> { set string <q3ext.qlb.display;$displayname(#quest.thing#)$> set string <q3ext.qlb.display;$lcase(#q3ext.qlb.display#)$> set string <q3ext.qlb.realname;#quest.thing#> set string <q3ext.qlb.realname;$lcase(#q3ext.qlb.realname#)$> if ( $instr(#q3ext.qlb.display#;#q3ext.qlb.lobjname#)$ > 0 ) or _ ( $instr(#q3ext.qlb.lobjname#;#q3ext.qlb.realname#)$ > 0 ) then { set <q3ext.qlb.objname;#quest.thing#> set <q3ext.qlb.found;1> } } if (%q3ext.qlb.found% = 0) then { for each object in inventory { set string <q3ext.qlb.display;$displayname(#quest.thing#)$> set string <q3ext.qlb.display;$lcase(#q3ext.qlb.display#)$> set string <q3ext.qlb.realname;#quest.thing#> set string <q3ext.qlb.realname;$lcase(#q3ext.qlb.realname#)$> if ( $instr(#q3ext.qlb.display#;#q3ext.qlb.lobjname#)$ > 0 ) or _ ( $instr(#q3ext.qlb.lobjname#;#q3ext.qlb.realname#)$ > 0 ) then { set <q3ext.qlb.objname;#quest.thing#> set <q3ext.qlb.found;1> } } } if (%q3ext.qlb.found% = 0) then { for each object in game { set string <q3ext.qlb.display;$displayname(#quest.thing#)$> set string <q3ext.qlb.display;$lcase(#q3ext.qlb.display#)$> set string <q3ext.qlb.realname;#quest.thing#> set string <q3ext.qlb.realname;$lcase(#q3ext.qlb.realname#)$> if ( $instr(#q3ext.qlb.display#;#q3ext.qlb.lobjname#)$ > 0 ) or _ ( $instr(#q3ext.qlb.lobjname#;#q3ext.qlb.realname#)$ > 0 ) then { set <q3ext.qlb.objname;#quest.thing#> } } } return <#q3ext.qlb.objname#> end define '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '* TYPE DEFINITIONS FOLLOW * '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define type <human> human type <container> displaytype=Person action <take> { set string <q3ext.qlb.object; $mid(#quest.command#;6)$> msg <You can't take $capfirst(#q3ext.qlb.object#)$!> } action <speak> { set string <q3ext.qlb.object; $mid(#quest.command#;10)$> msg <$capfirst(#q3ext.qlb.object#)$ doesn't reply to you.> } action <give anything> { if property <#q3ext.qlb.GiveTo#;container> then { msg <|n$capfirst(#q3ext.qlb.GiveTo#)$ accepts the #q3ext.qlb.GiveObj#.> move <#q3ext.qlb.GiveObj#;#q3ext.qlb.GiveTo#_inventory> } else { msg <$capfirst(#q3ext.qlb.GiveTo#)$ doesn't seem to want the #q3ext.qlb.GiveObj#.> } } end define ' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define type <container> container action <contents> { if not property <#q3ext.qlb.object#; closed> then { outputoff goto <#q3ext.qlb.object#_inventory> set string <q3ext.qlb.whatsheld;$gettag(#q3ext.qlb.object#_inventory;prefix)$$q3ext.qlb.parsed(#quest.formatobjects#)$.> if ($lengthof(#quest.objects#)$ = 0) then set <q3ext.qlb.whatsheld;> outputon msg <#q3ext.qlb.whatsheld#> outputoff goto <#q3ext.qlb.whereat#> outputon } } action <give anything> { msg <You put the #q3ext.qlb.GiveObj# in the #q3ext.qlb.GiveTo#.> move <#q3ext.qlb.GiveObj#; #q3ext.qlb.GiveTo#_inventory> } end define ' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define type <object> prefix = a take = nil action <take> { if ($objectproperty(#q3ext.qlb.object#;take)$=nil) then { msg <You pick up the #q3ext.qlb.object#.> } else { msg <$objectproperty(#q3ext.qlb.object#;take)$.> } move <#q3ext.qlb.object#;inventory> do <force_refresh> } end define ' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define type <scenery> invisible prefix = a pronoun = that notake = nil action <take> { if ($objectproperty(#q3ext.qlb.object#;notake)$=nil) then { msg <Taking $objectproperty(#q3ext.qlb.object#;pronoun)$ would serve no useful purpose.> } else { msg <$objectproperty(#q3ext.qlb.object#;notake)$.> } } end define ' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define type <readable> readable readmessage = You start to read but it is so incredibly dull you decide not to bother. readaction = nil action <read> { set string <q3ext.qlb.objname;$thisobject$> msg <$objectproperty(#q3ext.qlb.objname#;readmessage)$> } end define ' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ' * The openable type * ' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define type <openable> closed properties <closeddesc = null> properties <opendesc = null> properties <closingdesc = null> properties <openingdesc = null> properties <closedexam = null> properties <openexam = null> prefix = a action <open> { set string <q3ext.qlb.opened; $thisobject$> if property <$thisobject$; closed> then { property <$thisobject$; not closed> if ($objectproperty(#q3ext.qlb.opened#; openingdesc)$ = null) then { msg <You open the #q3ext.qlb.object#.> } else { msg <$objectproperty(#q3ext.qlb.opened#; openingdesc)$> } } else msg <The #q3ext.qlb.object# is already open.> } action <close> { set string <q3ext.qlb.closed; $thisobject$> if not property <$thisobject$;closed> then { property <$thisobject$; closed> if ($objectproperty(#q3ext.qlb.closed#; closingdesc)$ = null) then { msg <You close the #q3ext.qlb.object#.> } else { msg <$objectproperty(#q3ext.qlb.closed#; closingdesc)$.> } } else msg <The #q3ext.qlb.object# is already closed.> } action <look> { set string <q3ext.qlb.lookedat; $thisobject$> if property <$thisobject$; closed> then { if ($objectproperty(#q3ext.qlb.lookedat#; closeddesc)$ = null) then { set string <q3ext.qlb.lookmessage ;The #q3ext.qlb.lookedat# is closed> } else { set string <q3ext.qlb.lookmessage ;$objectproperty(#q3ext.qlb.lookedat#; closeddesc)$.> } } else { if ($objectproperty(#q3ext.qlb.lookedat#; opendesc)$ = null) then { set string <q3ext.qlb.lookmessage ;The #q3ext.qlb.lookedat# is open> } else { set string <q3ext.qlb.lookmessage ;$objectproperty(#q3ext.qlb.lookedat#; opendesc)$.> } } msg <#q3ext.qlb.lookmessage#.> } end define ' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ' * This clothing type is not used directly but inherited by specific clothes. * ' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define type <clothing> type <object> unworn headcover = 0 handscover = 0 feetcover = 0 topcover = 0 botcover = 0 sex = 1 pronoun = it wearmessage = You put it on. unwearmessage = You take it off. properties <alias=$thisobject$> action <wear> { set string <q3ext.qlb.objname;$thisobject$> msg <$objectproperty(#q3ext.qlb.objname#;wearmessage)$> property <#q3ext.qlb.objname#;alias=#q3ext.qlb.objname# [worn]> move <#q3ext.qlb.objname#;inventory> do <force_refresh> } action <unwear> { set string <q3ext.qlb.objname;$thisobject$> msg <$objectproperty(#q3ext.qlb.objname#;unwearmessage)$> property <#q3ext.qlb.objname#;alias=$thisobject$> do <force_refresh> } end define ' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ' * This lib defines 15 specific clothing objects, and most of these can be used * ' * to good effect for other garments - the defined objects are listed together * ' * with other garments that work similarly for game purposes. * ' * * ' * DEFINED GARMENT : ALSO USABLE FOR THESE GARMENTS * ' * hat : any headwear * ' * gloves : any handwear * ' * shoes : boots, outer footwear generally * ' * socks : stockings * ' * tights : pantie hose * ' * undies : panties, briefs - lower portion underwear generally * ' * teddy : uhm.. any underthing that covers like a teddy! * ' * trousers : jeans, shorts (not the underwear variety) * ' * dress : coverall * ' * skirt : kilt maybe? * ' * vest : bra, other 'top only' undergarment * ' * shirt : blouse, T-Shirt etc. * ' * sweater : pullover, sweatshirt - '2nd layer' top garment * ' * jacket : fleece, parka, anorak, short coat of whatever type * ' * coat : any long length outermost garment like a coat * ' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define type <shoes> type <clothing> feetcover = 4 wearmessage = You put them on. unwearmessage = You take them off. pronoun = them properties <prefix=a pair of> end define define type <socks> type <clothing> feetcover = 2 wearmessage = You put them on. unwearmessage = You take them off. pronoun = them properties <prefix=a pair of> end define define type <tights> type <clothing> feetcover = 2 botcover = 8 pronoun = them wearmessage = You put them on. unwearmessage = You take them off. properties <prefix=a pair of> end define define type <hat> type <clothing> headcover = 2 wearmessage = You put it on. unwearmessage = You take it off. properties <prefix=a> end define define type <gloves> type <clothing> handscover = 2 wearmessage = You put them on. unwearmessage = You take them off. pronoun = them properties <prefix=a pair of> end define define type <vest> type <clothing> topcover = 2 wearmessage = You put it on. unwearmessage = You take it off. properties <prefix=a> end define define type <shirt> type <clothing> topcover = 8 wearmessage = You put it on. unwearmessage = You take it off. properties <prefix=a> end define define type <teddy> type <clothing> topcover = 4 botcover = 4 wearmessage = You put it on. unwearmessage = You take it off. properties <prefix=a> end define define type <undies> type <clothing> botcover = 2 wearmessage = You put them on. unwearmessage = You take them off. pronoun = them properties <prefix=a pair of> end define define type <dress> type <clothing> topcover = 8 botcover = 32 wearmessage = You put it on. unwearmessage = You take it off. properties <prefix=a> end define define type <skirt> type <clothing> botcover = 32 wearmessage = You put it on. unwearmessage = You take it off. properties <prefix=a> end define define type <trousers> type <clothing> botcover = 16 wearmessage = You put them on. unwearmessage = You take them off. pronoun = them properties <prefix=a pair of> end define define type <sweater> type <clothing> topcover = 16 wearmessage = You put it on. unwearmessage = You take it off. properties <prefix=a> end define define type <jacket> type <clothing> topcover = 32 wearmessage = You put it on. unwearmessage = You take it off. properties <prefix=a> end define define type <coat> type <clothing> topcover = 64 botcover = 64 wearmessage = You put it on. unwearmessage = You take it off. properties <prefix=a> end define ' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *`; libraries["typelib.qlb"] = `!library !deprecated !asl-version <311> !name <MaDbRiT's Type Library> !version <1.009 06-Sep-2003> !author <MaDbRiT (Al Bampton)> !help <typelib.pdf> ! This library adds a whole set of types, with related actions and properties to Quest. ! It is easy to use from Q.D.K. but be sure to read the manual before you start. '===================================================== '== This is MaDbRiT's QUEST Types Library @06-09-03 == '== It will only work with Quest 3.11 build 137 or == '== later This version is specifically designed to == '== be easily usable from Q.D.K. == '===================================================== '== !!!! PLEASE READ THE MANUAL !!!! == '== !!!! NEVER CHANGE THIS FILE !!!! == '===================================================== '====================================== '== Add these lines to the gameblock == '====================================== !addto game command <look at #TLSdObj#; look #TLSdObj#; l #TLSdObj#> do <TLPlook> command <examine #TLSdObj#; inspect #TLSdObj#; x #TLSdObj#> do <TLPexamine> command <open #TLSdObj#> do <TLPopen> command <close #TLSdObj#; shut #TLSdObj#> do <TLPclose> command <take #TLSdObj# from #TLSiObj#> do <TLPtake> command <take #TLSdObj# off> do <TLPunWear> command <take #TLSdObj#> do <TLPtake> command <drop #TLSdObj# into #TLSiObj#> do <TLPputIn> command <drop #TLSdObj# on> do <TLPwear> command <drop #TLSdObj# down; drop down #TLSdObj#; drop #TLSdObj#> do <TLPdrop> command <give #TLSdObj# to #TLSiObj#;give #TLSiObj# the #TLSdObj#> do <TLPgive> command <read #TLSdObj#> do <TLPread> command <wear #TLSdObj#> do <TLPwear> command <unwear #TLSdObj#> do <TLPunWear> description { do <TLProomDescription> } startscript do <TLPstartup> ' nodebug !end '=========================================== '== Add some synonyms used in the library == '=========================================== !addto synonyms back; back from; out of =from inside; in to; in =into look into = examine put =drop don; drop on = wear take off; remove = unwear shut = close talk = speak !end '================================================== '== A couple of dummy rooms, used by the library == '================================================== define room <TLRcontainers> end define define room <TLRcontents> end define '================ '== PROCEDURES == '================ '=========================================================== '== Configure the library for use - called in startscript == '=========================================================== define procedure <TLPstartup> set string <TLSplayerRoom;> set string <TLScontentList;> set string <TLStemp;> set string <TLSrealName;> set string <TLSlist;> set string <TLStempName;> set string <TLMnotOpenable;Try as you might, you find that __ is just not possible.> set string <TLMnotClosable;Try as you might, you find that __ is just not possible.> set string <TLMtaken;Taken.> set string <TLMalreadyTaken;You have already got> set string <TLMdontHaveDObj;You don't seem to have that.> set string <TLMnoNeed;You realise there is no need __ to do that and change your mind.> set string <TLSthisObj;> set string <TLSobjAlias;> set string <TLSindescription;> set string <TLSalias;> set string <TLSobjList;> set string <TLScharList;> set numeric <TLNcomma;0> set numeric <TLNcount;0> set numeric <TLNlength;0> set numeric <TLNsizeLimit;0> set numeric <TLNweightLimit;0> set numeric <TLNheadCovered;0> set numeric <TLNhandsCovered;0> set numeric <TLNfeetCovered;0> set numeric <TLNtopCovered;0> set numeric <TLNbotCovered;0> set numeric <TLNtempCovered;0> set numeric <TLNwearable;0> set numeric <TLNlengthOf;0> '*** ' TLNplayerSex' should be set to 1 for a male player, 2 for a female. '*** set numeric <TLNplayerSex;1> for each object in game { if type <#quest.thing#;TLTcontainable> then { if (#(quest.thing):isIn#<>nil) then { move <#quest.thing#;TLRcontainers> } } if type <#quest.thing#;TLTclothing> then { property <#quest.thing#;displayname=$displayname(#quest.thing#)$> if property <#quest.thing#;worn> then { move <#quest.thing#;inventory> property <#quest.thing#;alias=#(quest.thing):displayname# [worn]> set <TLNtopCovered;%TLNtopCovered% + #(quest.thing):topcover#> set <TLNheadCovered;%TLNheadCovered% + #(quest.thing):headcover#> set <TLNhandsCovered;%TLNhandsCovered% + #(quest.thing):handscover#> set <TLNfeetCovered;%TLNfeetCovered% + #(quest.thing):feetcover#> set <TLNbotCovered;%TLNbotCovered% + #(quest.thing):botcover#> } } } end define '================================== '== Alternative room description == '================================== define procedure <TLProomDescription> set <TLSindescription;$gettag(#quest.currentroom#;indescription)$> set <TLSalias;$gettag(#quest.currentroom#;alias)$> if is <#TLSindescription#;> then { if is <#TLSalias#;> then { msg <You are in $gettag(#quest.currentroom#;prefix)$ |b|cl#quest.currentroom#.|cb|xb|xn> } else { msg <You are in $gettag(#quest.currentroom#;prefix)$ |b|cl#TLSalias#.|cb|xb|xn> } } else { if is <#TLSalias#;> then { msg <#TLSindescription# $gettag(#quest.currentroom#;prefix)$ |b|cl#quest.currentroom#.|cb|xb|xn> } else { msg <#TLSindescription# $gettag(#quest.currentroom#;prefix)$ |b|cl#TLSalias#.|cb|xb|xn> } } msg <|n#quest.lookdesc#|n> set <TLSobjList;> set <TLScharList;> for each object in <#quest.currentroom#> { set <TLSthisObj;#quest.thing#> if property <#quest.thing#;invisible> or property <#quest.thing#;hidden> then { } else { if type <#quest.thing#;TLTactor> then { if property <#quest.thing#;named> then { set <TLScharList;#TLScharList# |b$capfirst(#@quest.thing#)$|xb, > } else set <TLScharList;#TLScharList# #(quest.thing):prefix# |b#@quest.thing#|xb, > } else{ set <TLSobjList;#TLSobjList# #(quest.thing):prefix#> set <TLSobjList;#TLSobjList# |b#@quest.thing#|xb, > } } } if ($lengthof(#TLScharList#)$ >0) then { set <TLNlengthOf;$lengthof(#TLScharList#)$ - 1> set <TLScharList;$left(#TLScharList#;%TLNlengthOf%)$> set <TLScharList;$TLFcontentFormat(#TLScharList#)$> if ($instr(#TLScharList#;_and_)$ >0) then { msg <#TLScharList# are here.|n> } else { msg <#TLScharList# is here.|n> } } if ($lengthof(#TLSobjList#)$ >0) then { set <TLNlengthOf;$lengthof(#TLSobjList#)$ - 1> set <TLSobjList;$left(#TLSobjList#;%TLNlengthOf%)$> set <TLSobjList;$TLFcontentFormat(#TLSobjList#)$> if ($instr(#TLSobjList#;_and_)$ >0) then { msg <You can see #TLSobjList# here.|n> } else { msg <You can see #TLSobjList# here.|n> } } if not is <#quest.doorways.dirs#;> then { msg <You can move #quest.doorways.dirs#.> } if not is <#quest.doorways.places#;> then { msg <You can go to #quest.doorways.places#.> } if not is <#quest.doorways.out#;> then { msg <You can go out to |b#quest.doorways.out.display#|xb.> } end define '================================================================ '== Override the inbuilt LOOK function - need extra capability == '================================================================ define procedure <TLPlook> do <TLPfillContents> set <TLSdObj;$TLFgetObjectName(#TLSdObj#)$> if (#TLSdObj# <> !) then { if ($locationof(#TLSdObj#)$=TLRcontents) then { move <#TLSdObj#;#quest.currentroom#> } exec <look at #TLSdObj#;normal> if type <#TLSdObj#;TLTcontainable> then { if (#(TLSdObj):isIn#<>nil) then { move <#TLSdObj#;TLRContents> } } } else exec <look #TLSdObj#;normal> do <TLPemptyContents> end define '=================================================================== '== Override the inbuilt EXAMINE function - need extra capability == '=================================================================== define procedure <TLPexamine> do <TLPfillContents> set <TLSdObj;$TLFgetObjectName(#TLSdObj#)$> if (#TLSdObj# <> !) then { if ($locationof(#TLSdObj#)$=TLRcontents) then { move <#TLSdObj#;#quest.currentroom#> } do <TLPexamineContainer> if type <#TLSdObj#;TLTcontainable> then { if (#(TLSdObj):isIn#<>nil) then { move <#TLSdObj#;TLRContents> } } } else do <TLPexamineContainer> do <TLPemptyContents> end define '================================================================ '== Tests examined object & calls contents action where needed == '================================================================ define procedure <TLPexamineContainer> exec <x #TLSdObj#;normal> if type <#TLSdObj#;TLTcontainer> then { doaction <#TLSdObj#;contents> } end define '================================================================ '== Override the inbuilt TAKE function - need extra capability == '================================================================ define procedure <TLPtake> do <TLPfillContents> set <TLSdObj;$TLFgetObjectName(#TLSdObj#)$> if (#TLSdObj# <> !) then { if ($locationof(#TLSdObj#)$<>inventory) then { move <#TLSdObj#;#quest.currentroom#> if property <#TLSdObj#;takeable> then { doaction <#TLSdObj#;take> if property <#TLSdObj#;isIn> then { property <#TLSdObj#;isIn=nil> } } else { msg <#(TLSdObj):noTake#> if property <#TLSdObj#;isIn> then { if (#(TLSdObj):isIn#<> nil) then { move <#TLSdObj#;TLRcontents> } } } } else msg <#TLMalreadyTaken# #(TLSdObj):article#.> } else doaction <#TLSdObj#;take> do <TLPemptyContents> end define '================================================================ '== Override the inbuilt DROP function - need extra capability == '================================================================ define procedure <TLPdrop> do <TLPfillContents> set <TLSdObj;$TLFgetObjectName(#TLSdObj#)$> if (#TLSdObj# <> !) then { if property <#TLSdObj#;worn> then { msg <You'll have to take #(TLSdObj):article# off first.> } else exec <drop #TLSTemp#;normal> } else exec <drop #TLStemp#;normal> end define '================================================================ '== Override the inbuilt GIVE function - need extra capability == '================================================================ define procedure <TLPgive> do <TLPfillContents> set <TLSdObj;$TLFgetObjectName(#TLSdObj#)$> set <TLSiObj;$TLFgetObjectName(#TLSiObj#)$> if (#TLSdObj#=!) then { exec <look at #TLSdObj#;normal> } else { if (#TLSIObj#=!) then { exec <look at #TLSIObj#;normal> } else { if property <#TLSdObj#;worn> then { msg <You'll have to take #(TLSdObj):article# off first.> } else { do <TLPcheckGive> } } } do <TLPemptyContents> end define '============================================================= '== Tests objects & redirects or runs standard give routine == '============================================================= define procedure <TLPcheckGive> if type <#TLSdObj#;TLTcontainable> or type <#TLSiObj#;TLTcontainer> then { do <TLPcheckIObj> } else { exec <give #TLSdObj# to #TLSiObj#;normal> } end define '========================================================= '== 3 utility procedures - manipulate contained objects == '========================================================= define procedure <TLPfillContents> for each object in <TLRcontainers> { if got <#(quest.thing):isIn#> or here <#(quest.thing):isIn#> then { if not property <#(quest.thing):isIn#;closed> then { move <#quest.thing#;TLRcontents> } } } end define define procedure <TLPvalidContents> for each object in <TLRcontents> { if (#(quest.thing):isIn# <> #TLSdobj# ) then { move <#quest.thing#;TLRcontainers> } } end define define procedure <TLPemptyContents> for each object in <TLRcontents> { move <#quest.thing#;TLRcontainers> } end define '=================================== '== Handle the added OPEN command == '=================================== define procedure <TLPopen> do <TLPfillContents> set <TLSdObj;$TLFgetObjectName(#TLSdObj#)$> if (#TLSdObj# <> !) then { do <TLPopenObj> } else exec <look #TLSdObj#;normal> do <TLPemptyContents> end define '================================================================== '== Tests open-ed object & calls open action or denial as needed == '================================================================== define procedure <TLPopenObj> if type <#TLSdObj#;TLTclosable> then { doaction <#TLSdObj#;open> } else msg <#TLMnotOpenable#> end define '==================================== '== Handle the added CLOSE command == '==================================== define procedure <TLPclose> do <TLPfillContents> set <TLSdObj;$TLFgetObjectName(#TLSdObj#)$> if (#TLSdObj# <> !) then { do <TLPcloseObj> } else exec <look #TLSdObj#;normal> do <TLPemptyContents> end define '=================================================================== '== Tests close-d object & calls close action or denial as needed == '=================================================================== define procedure <TLPcloseObj> if type <#TLSdObj#;TLTclosable> then { doaction <#TLSdObj#;close> } else msg <#TLMnotClosable#> end define '===================================== '== Handle the added PUT IN command == '===================================== define procedure <TLPputIn> do <TLPfillContents> set <TLSdObj;$TLFgetObjectName(#TLSdObj#)$> ' set <TLSiObj;$TLFgetObjectName(#TLSiObj#)$> set <TLSiObj;$TLFgetObjectName(#TLSiObj#)$> if (#TLSdObj# <> !) then { do <TLPcheckIObj> } else msg <#TLMdontHaveDObj#> do <TLPemptyContents> end define '=========================================== '== Test the indirect object is available == '=========================================== define procedure <TLPcheckIObj> if (#TLSiObj# <> !) then { do <TLPcheckContainer> } else { if property <#TLSiObj#;named> then msg <$displayname(TLSiObj)$ isn't here.> else msg <The $displayname(TLSiObj)$ isn't here.> } end define '====================================== '== Test for container & containable == '====================================== define procedure <TLPcheckContainer> if not type <#TLSiObj#;TLTcontainer> then { msg <You can't put things in $TLFnamed(#TLSiObj#)$.> } else { if property <#TLSiObj#;closed> then { msg <You'll have to open $TLFnamed(#TLSiObj#)$...> } else { if not type <#TLSdObj#;TLTcontainable> then { msg <You can't put $TLFnamed(#TLSdObj#)$ in anything.> } else do <TLPcontainerLimits> } } end define '====================================== '== Both legal objects, check limits == '====================================== define procedure <TLPcontainerLimits> if (#(TLSdObj):isIn#<>#TLSiObj#) then { set <TLNsizeLimit;$TLFsizeHeld(#TLSiObj#)$> set <TLNweightLimit;$TLFweightHeld(#TLSiObj#)$> set <TLNsizeLimit;#(TLSiObj):sizeLimit# - %TLNsizeLimit%> set <TLNweightLimit;#(TLSiObj):weightLimit# - %TLNweightLimit%> if (%TLNsizeLimit% < #(TLSdObj):size#) then { msg <#(TLSdObj):tooBig#> } else { if (%TLNweightLimit% < #(TLSdObj):weight#) then { msg <#(TLSdObj):tooHeavy#> } else { move <#TLSdObj#;TLRcontainers> property <#TLSdOBJ#;isIn=#TLSiObj#> doaction <#TLSdObj#;contained> } } } else msg <#TLMnoNeed#> end define '=================================== '== The 'read' command procedure. == '=================================== define procedure <TLPread> do <TLPfillContents> set <TLSdObj;$TLFgetObjectName(#TLSdObj#)$> if (#TLSdObj# <> !) then { if type <#TLSdObj#;TLTreadable> then { doaction <#TLSdObj#;read> } else msg <There's nothing to read!> } else exec <look #TLSdObj#;normal> do <TLPemptyContents> end define '=================================== '== The 'wear' command procedure. == '=================================== define procedure <TLPwear> do <TLPfillContents> set <TLSdObj;$TLFgetObjectName(#TLSdObj#)$> if (#TLSdObj# <> !) then { if action <#TLSdObj#;wear> then { if (#(TLSdObj):sex# = %TLNplayerSex%) then { do <TLPcheckWear> } else { msg <On second thoughts you decide that the |xn> msg <#TLSdObj# |xn> if (%TLNplayerSex% = 1) then { msg <won't suit a man like you at all.> } else msg <won't suit a woman like you at all.> } } else { if (#(TLSdObj):noWear#= default) then { msg <You cannot wear $TLFnamed(#TLSdObj#)$!> } else { msg <#(TLSdObj):noWear#> } } } else msg <$TLFnamed(#TLStemp#)$ isn't here.> do <TLPemptyContents> end define '======================================================================== '== The 'checkWear' procedure - this checks the sense of wear commands == '======================================================================== define procedure <TLPcheckWear> set <TLNwearable;0> if (#(TLSdObj):topcover# <> 0) and (#(TLSdObj):topcover# <= %TLNtopCovered%) then { set <TLNwearable;%TLNwearable% + 1> } if (#(TLSdObj):headcover# <> 0) and (#(TLSdObj):headcover# <= %TLNheadCovered%) then { set <TLNwearable;%TLNwearable% + 1> } if (#(TLSdObj):feetcover# <> 0) and (#(TLSdObj):feetcover# <= %TLNfeetCovered%) then { set <TLNwearable;%TLNwearable% + 1> } if (#(TLSdObj):handscover# <> 0) and (#(TLSdObj):handscover# <= %TLNhandsCovered%) then { set <TLNwearable;%TLNwearable% + 1> } ' - disallow for coats (don't affect ability to put on lower torso clothes) set <TLNtempCovered;%TLNbotCovered%> if (%TLNtempCovered% > 63) and (#(TLSdObj):botcover# < 33) then { set <TLNtempCovered;%TLNtempCovered% - 64> } ' - disallow for skirts and dresses (like coats!) if (%TLNtempCovered% > 31) and (#(TLSdObj):botcover# < 16) and __ (#(TLSdObj):botcover# <> 4) then { set <TLNtempCovered;%TLNtempCovered% - 32> } ' - disallow wearing of skirts/dresses and trousers simultaneously if (%TLNtempCovered% > 15) then { set <TLNtempCovered;%TLNtempCovered% + 16> } if (#(TLSdObj):botcover# <> 0) and (#(TLSdObj):botcover# <= %TLNtempCovered%) then { set <TLNwearable;%TLNwearable% + 1> } if (%TLNwearable% =0) then { doaction <#TLSdObj#;wear> property <#TLSdObj#; worn> set <TLNtopCovered;%TLNtopCovered% + #(TLSdObj):topcover#> set <TLNheadCovered;%TLNheadCovered% + #(TLSdObj):headcover#> set <TLNhandsCovered;%TLNhandsCovered% + #(TLSdObj):handscover#> set <TLNfeetCovered;%TLNfeetCovered% + #(TLSdObj):feetcover#> set <TLNbotCovered;%TLNbotCovered% + #(TLSdObj):botcover#> } else { msg <Given what you are already wearing - that makes no sense at all.> } end define '===================================== '== The 'unwear' command procedure. == '===================================== define procedure <TLPunWear> do <TLPfillContents> set <TLSdObj;$TLFgetObjectName(#TLSdObj#)$> if (#TLSdObj# <> !) then { if property <#TLSdObj#; worn> then { if action <#TLSdObj#;unwear> then { do <TLPcheckUnWear> } else msg <You can't do that.> } else msg <You can't do that.> } else msg <You aren't wearing $TLFnamed(#TLStemp#)$.> do <TLPemptyContents> end define '================================== '== The 'CheckUnwear' procedure. == '================================== define procedure <TLPcheckUnWear> set <TLNwearable;0> set <TLNtempCovered; %TLNtopCovered% /2> if (#(TLSdObj):topcover# <> 0) and (#(TLSdObj):topcover# <= %TLNtempCovered%) then { set <TLNwearable;%TLNwearable% + 1> } set <TLNtempCovered; %TLNheadCovered% /2> if (#(TLSdObj):headcover# <> 0) and (#(TLSdObj):headcover# <= %TLNtempCovered%) then { set <TLNwearable;%TLNwearable% + 2> } set <TLNtempCovered; %TLNfeetCovered% /2> if (#(TLSdObj):feetcover# <> 0) and (#(TLSdObj):feetcover# <= %TLNtempCovered%) then { set <TLNwearable;%TLNwearable% + 4> } set <TLNtempCovered; %TLNhandsCovered% /2> if (#(TLSdObj):handscover# <> 0) and (#(TLSdObj):handscover# <= %TLNtempCovered%) then { set <TLNwearable;%TLNwearable% + 8> } ' - disallow for coats (don't affect ability to take off lower torso clothes) set <TLNtempCovered;%TLNbotCovered%> if (%TLNtempCovered% > 63) then { set <TLNtempCovered;%TLNtempCovered% - 64> } ' - disallow for skirts and dresses (like coats!) if (%TLNtempCovered% > 31) and (#(TLSdObj):botcover# <> 4) then { set <TLNtempCovered;%TLNtempCcovered% - 32> } set <TLNtempCovered;%TLNtempCovered% /2> if (#(TLSdObj):botcover# <> 0) and (#(TLSdObj):botcover# <= %TLNtempCovered%) then { set <TLNwearable;%TLNwearable% + 16> } if (%TLNwearable% =0) then { doaction <#TLSdObj#;unwear> property <#TLSdObj#; not worn> set <TLNtopCovered;%TLNtopCovered% - #(TLSdObj):topcover#> set <TLNheadCovered;%TLNheadCovered% - #(TLSdObj):headcover#> set <TLNhandsCovered;%TLNhandsCovered% - #(TLSdObj):handscover#> set <TLNfeetCovered;%TLNfeetCovered% - #(TLSdObj):feetcover#> set <TLNbotCovered;%TLNbotCovered% - #(TLSdObj):botcover#> } else { msg <Given what you are wearing, that isn't possible.> } end define '=============== '== FUNCTIONS == '=============== '======================================================== '== Returns object real name, checking three locations == '======================================================== define function <TLFgetObjectName> set <TLStemp;$parameter(1)$> set <TLSrealName;$getobjectname(#TLStemp#)$> 'msg <DEBUG #TLStemp# #TLSrealName#> if (#TLSrealName#=!) then { set <TLSrealName;$getobjectname(#TLStemp#;TLRcontents)$> } if (#TLSrealName#=!) then { set <TLSrealName;$getobjectname(#TLStemp# [worn])$> if (#TLSrealName#=!) then { set <TLSrealName;$getobjectname(#TLStemp# [worn];TLRcontents)$> } } return <#TLSrealName#> end define '===================================================== '== Replaces last comma in parsed string with "and" == '===================================================== define function <TLFcontentFormat> set <TLStemp;$parameter(1)$> set <TLNlength;$lengthof(#TLStemp#)$> set <TLNcomma;0> for <TLNcount; 1; %TLNlength%; 1> { if ($mid(#TLStemp#;%TLNcount%;1)$ =,) then { set <TLNcomma;%TLNcount%> } } if (%TLNcomma% <>0) then { set <TLNcomma;%TLNcomma%-1> set <TLSlist;$left(#TLStemp#;%TLNcomma%)$ and> set <TLNcomma;%TLNcomma%+2> set <TLSlist;#TLSlist#$mid(#TLStemp#;%TLNcomma%)$> } else set <TLSlist;#TLStemp#> return <#TLSlist#> end define '================================================= '== Returns sizes / weights held in a container == '================================================= define function <TLFsizeHeld> set <TLNsizeLimit;0> for each object in <TLRcontents> { if (#(quest.thing):isIn#=#TLSiObj#) then { set <TLNsizeLimit;%TLNsizeLimit% + #(quest.thing):size#> } } return <%TLNsizeLimit%> end define define function <TLFweightHeld> set <TLNweightLimit;0> for each object in <TLRcontents> { if (#(quest.thing):isIn#=#TLSiObj#) then { set <TLNweightLimit;%TLNweightLimit% + #(quest.thing):weight#> } } return <%TLNweightLimit%> end define '======================================================== '== Returns proper name or 'the object' as appropriate == '======================================================== define function <TLFnamed> set <TLStempName;$parameter(1)$> if property <#TLStempName#;named> then { set <TLStempName;$capfirst(#TLStempName#)$> } else set <TLStempName;the #TLStempName#> return <#TLStempName#> end define '====================== '== TYPE DEFINITIONS == '====================== define type <TLTactor> listHeader = He is carrying noSpeak = He says nothing. article = he displaytype = person named action <speak> { set <TLSthisObj;$thisobject$> msg <#(TLSthisObj):noSpeak#> } end define '===================================================================== '== The TLTcontainer type: object that you can put other objects in == '===================================================================== define type <TLTcontainer> listHeader=It contains sizeLimit=100 weightLimit=100 action <contents> { do <TLPvalidContents> outputoff set <TLSplayerRoom;#quest.currentroom#> goto <TLRcontents> set <TLScontentList;#quest.formatobjects#> goto <#TLSplayerRoom#> outputon set <TLSthisObj;$thisobject$> if type <#TLSthisObj#;TLTClosable> then { if property <#TLSthisObj#;closed> then { set <TLScontentList;> msg <#(TLSthisObj):closedDesc#> } } if ($lengthof(#TLScontentList#)$ > 0) then { msg <#(TLSdObj):listHeader# #TLScontentList#.> } } end define '========================================================================= '== The TLTcontainable type: object that can be put into a TLTcontainer == '========================================================================= define type <TLTcontainable> isIn=nil size=25 weight=25 tooBig=It is too big to fit. tooHeavy=It is too heavy for that. action <contained> msg <O.K.> end define '================================================================= '== The TLTclosable type: object that can be opened and closed == '================================================================= define type <TLTclosable> closed closedDesc=(It is closed, you cannot see inside.) isClosedDesc=It is already closed. isOpenedDesc=It is already open. closingDesc=You close it. openingDesc=You open it. article=it action <open> { set <TLSthisObj;$thisobject$> if property <#TLSthisObj#;closed> then { doaction <#TLSthisObj#;opened> property <#TLSthisObj#;not closed> } else { msg <#(TLSthisObj):isOpenedDesc#> } } action <close> { set <TLSthisObj;$thisobject$> if property <#TLSthisObj#;closed> then { msg <#(TLSthisObj):isClosedDesc#> } else { doaction <#TLSthisObj#;closed> property <#TLSthisObj#;closed> } } action <opened> { msg <#(TLSthisObj):openingDesc#> } action <closed> { msg <#(TLSthisObj):closingDesc#> } end define '============================================= '== The TLTreadable type: a readable object == '============================================= define type <TLTreadable> readmessage = You start to read but it is so incredibly dull you decide not to bother. action <read> { set <TLSdObj;$thisobject$> msg <#(TLSdObj):readmessage#> } end define '==================================================== '== The TLTobject type: a visible, takeable object == '==================================================== define type <TLTobject> takeable action <take> { set <TLSthisObj;$thisobject$> move <#TLSthisObj#;inventory> msg <#TLMtaken#> if property <#TLSthisObj#;TLTcontainable> then { property <#TLSthisObj#;isIn=nil> } } end define '================================================= '== The TLTscenery type: fixed, unlisted object == '================================================= define type <TLTscenery> invisible end define '============================================================ '== The default type: common functionality for all objects == '============================================================ !addto type <default> 'define type <default> prefix=a article=it displaytype=object noTake = Taking that would serve no useful purpose. noWear = default 'end define !end '================================================================================ '== This clothing type is not used directly but inherited by specific clothes. == '================================================================================ define type <TLTclothing> type <TLTobject> headcover = 0 handscover = 0 feetcover = 0 topcover = 0 botcover = 0 sex = 1 article = it wearmessage = You put it on. unwearmessage = You take it off. properties <displayname=$thisobject$> action <wear> { set <TLSdObj;$thisobject$> msg <#(TLSdObj):wearmessage#> property <#TLSdObj#;alias=#(TLSdObj):displayname# [worn]> move <#TLSdObj#;inventory> } action <unwear> { set <TLSdObj;$thisobject$> msg <#(TLSdObj):unwearmessage#> property <#TLSdObj#;alias=#(TLSdObj):displayname#> } end define ' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ' * This lib defines 15 specific clothing objects, and most of these can be used * ' * to good effect for other garments - the defined objects are listed together * ' * with other garments that work similarly for game purposes. * ' * * ' * DEFINED GARMENT : ALSO USABLE FOR THESE GARMENTS * ' * hat : any headwear * ' * gloves : any handwear * ' * shoes : boots, outer footwear generally * ' * socks : stockings * ' * tights : pantie hose * ' * undies : panties, briefs - lower portion underwear generally * ' * teddy : uhm.. any underthing that covers like a teddy! * ' * trousers : jeans, shorts (not the underwear variety) * ' * dress : coverall * ' * skirt : kilt maybe? * ' * vest : bra, other 'top only' undergarment * ' * shirt : blouse, T-Shirt etc. * ' * sweater : pullover, sweatshirt - '2nd layer' top garment * ' * jacket : fleece, parka, anorak, short coat of whatever type * ' * coat : any long length outermost garment like a coat * ' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * define type <TLTshoes> type <TLTclothing> feetcover = 4 wearmessage = You put them on. unwearmessage = You take them off. article = them prefix=a pair of end define define type <TLTsocks> type <TLTclothing> feetcover = 2 wearmessage = You put them on. unwearmessage = You take them off. article = them prefix=a pair of end define define type <TLTtights> type <TLTclothing> feetcover = 2 botcover = 8 article = them wearmessage = You put them on. unwearmessage = You take them off. prefix=a pair of end define define type <TLThat> type <TLTclothing> headcover = 2 wearmessage = You put it on. unwearmessage = You take it off. prefix=a end define define type <TLTgloves> type <TLTclothing> handscover = 2 wearmessage = You put them on. unwearmessage = You take them off. article = them prefix=a pair of end define define type <TLTvest> type <TLTclothing> topcover = 2 wearmessage = You put it on. unwearmessage = You take it off. prefix=a end define define type <TLTshirt> type <TLTclothing> topcover = 8 wearmessage = You put it on. unwearmessage = You take it off. prefix=a end define define type <TLTteddy> type <TLTclothing> topcover = 4 botcover = 4 wearmessage = You put it on. unwearmessage = You take it off. prefix=a end define define type <TLTundies> type <TLTclothing> botcover = 2 wearmessage = You put them on. unwearmessage = You take them off. article = them prefix=a pair of end define define type <TLTdress> type <TLTclothing> topcover = 8 botcover = 32 wearmessage = You put it on. unwearmessage = You take it off. prefix=a end define define type <TLTskirt> type <TLTclothing> botcover = 32 wearmessage = You put it on. unwearmessage = You take it off. prefix=a end define define type <TLTtrousers> type <TLTclothing> botcover = 16 wearmessage = You put them on. unwearmessage = You take them off. article = them prefix=a pair of end define define type <TLTsweater> type <TLTclothing> topcover = 16 wearmessage = You put it on. unwearmessage = You take it off. prefix=a end define define type <TLTjacket> type <TLTclothing> topcover = 32 wearmessage = You put it on. unwearmessage = You take it off. prefix=a end define define type <TLTcoat> type <TLTclothing> topcover = 64 botcover = 64 wearmessage = You put it on. unwearmessage = You take it off. prefix=a end define '========================== '== INTERFACE FOR Q.D.K. == '========================== !QDK 'script <MaDbRiTs Types Library> ' command <Initialise the library (use in startscript); TLPstartup> ' display <Initialise MaDbRiTs Types Library.> object <Basics> type <Regular object; TLTobject> type <Scenery (not takeable or described) object; TLTscenery> property <Make regular object not takeable;not takeable> property <Not takeable msg;noTake;text> property <Not wearable msg;noWear;text> object <Readable> type <Readable object;TLTreadable> property <Message if read;readMessage;text> action <Action if read;read> object <Containers> type <Container object (can have things put in it); TLTcontainer> property <Header for listing;listHeader;text> property <Size Limit;sizeLimit;text> property <Weight Limit;weightLimit;text> type <Containable object (can be put in things); TLTcontainable> property <Size;size;text> property <Weight;weight;text> property <Start game inside;isIn;objects> property <Msg if Too Big;tooBig;text> property <Msg if Too Heavy;tooHeavy;text> action <Action when contained;contained> object <Actor> type <Actor can carry things;TLTcontainer> property <Header for listing;listHeader;text> property <Size Limit;sizeLimit;text> property <Weight Limit;weightLimit;text> type <Actor; TLTactor> property <Actor not named. (e.g. 'the sailor' not 'Jack');not named> property <Default speak reply;noSpeak;text> action <Script if spoken to;speak> object <Closables> type <Closable object NOTE Following properties all have useful defaults;TLTclosable> property <Start open?;not closed> property <Closed text (container);closedDesc;text> property <Is closed description;isClosedDesc;text> property <Closing description;closingDesc;text> property <Is open description;isOpenDesc;text> property <Opening description;openingDesc;text> action <Script when opened;opened> action <Script when closed;closed> object <Clothing 1> type <Sweater;TLTsweater> type <Shirt;TLTshirt> type <Vest (top half underwear / bra etc.);TLTvest> type <Teddy (or 1 piece swimsuit etc.);TLTteddy> type <Underwear (shorts or briefs);TLTundies> type <Socks;TLTsocks> type <Tights (a.k.a. Panty Hose);TLTtights> type <Dress;TLTdress> type <Skirt;TLTskirt> type <Trousers;TLTtrousers> type <Shoes;TLTshoes> type <Hat NOTE Clothing continues on next tab!;TLThat> object <Clothing 2> type <Gloves;TLTgloves> type <Jacket (short coat);TLTjacket> type <Coat (long coat) NOTE Properties below have defaults! See the manual;TLTcoat> property <Msg when put on;wearmessage;text> property <Msg when taken off;unwearmessage;text> property <Head cover value;headcover;text> property <Hands cover value;handscover;text> property <Feet cover value;feetcover;text> property <Top cover value;topcover;text> property <Bottom cover value;botcover;text> property <Sex;sex;text> property <Start game worn?;worn> !end `; libraries["net.lib"] = `!library !asl-version <350> !name <QuestNet Standard Library> !version <1.0> !author <Alex Warren> ! This library adds useful additional QuestNet functions. We recommend you include this library in all QuestNet (multiplayer) games. ' NET.LIB v1.0 ' for QuestNet Server 3.5 ' Copyright © 2004 Axe Software. Please do not modify this library. !QDK object <QuestNet> type <This object can be &given to other players; giveable> !end define type <giveable> action <give to anything> { if ( #quest.give.object.name# = player%userid% ) then { msg <It is silly to give things to yourself!> } else { if property <#quest.give.object.name#; netplayer> then { move <$thisobject$; #quest.give.object.name#> msg <You give $name(#quest.give.object.name#)$ the $thisobjectname$.> msgto <#quest.give.object.name#; |b$name(%userid%)$|xb has given you a |b$thisobjectname$|xb.> if action <$thisobject$; gain> then { with <#quest.give.object.name#> { doaction <$thisobject$; gain> } } if action <$thisobject$; lose> then { doaction <$thisobject$; lose> } } else { msg <The $displayname(#quest.give.object.name#)$ doesn't want that.> } } } end define `;
the_stack
const { registerSuite } = intern.getInterface('object'); const { assert } = intern.getPlugin('chai'); import * as sinon from 'sinon'; import { debounce, deepAssign, deepMixin, throttle, uuid, mixin, partial, guaranteeMinimumTimeout } from '../../../src/core/util'; import { Handle } from '../../../src/core/Destroyable'; const TIMEOUT = 3000; let timerHandle: Handle | null; function destroyTimerHandle() { if (timerHandle) { timerHandle.destroy(); timerHandle = null; } } registerSuite('util functions', { '.deepAssign()'() { const source: { a: number; b: { enumerable: boolean; configurable: boolean; writable: boolean; value: number; }; c: { d: number; e: any[]; }; } = Object.create( { a: 1 }, { b: { enumerable: false, configurable: true, writable: true, value: 2 } } ); source.c = { d: 3, e: [4, [5], { f: 6 }] }; const object: {} = Object.create(null); const assignedObject: {} & typeof source = deepAssign(object, source); assert.strictEqual(object, assignedObject, 'deepAssign should return the modified target object'); assert.isUndefined(assignedObject.a, 'deepAssign should not copy inherited properties'); assert.isUndefined(assignedObject.b, 'deepAssign should not copy non-enumerable properties'); assert.strictEqual(assignedObject.c.d, 3); assert.strictEqual(assignedObject.c.e.length, 3); assert.notStrictEqual(assignedObject.c.e[1], source.c.e[1], 'deepAssign should perform a deep copy'); assert.notStrictEqual(assignedObject.c.e[2], source.c.e[2], 'deepAssign should perform a deep copy'); assert.notStrictEqual(assignedObject.c.e, source.c.e, 'deepAssign should perform a deep copy'); }, '.deepAssign() merges nested object on to the target'() { const target = { apple: 0, banana: { weight: 52, price: 100, details: { colour: 'brown', texture: 'soft' } }, cherry: 97 }; const source = { banana: { price: 200, details: { colour: 'yellow' } }, durian: 100 }; const assignedObject = deepAssign(target, source); assert.deepEqual(assignedObject, { apple: 0, banana: { weight: 52, price: 200, details: { colour: 'yellow', texture: 'soft' } }, cherry: 97, durian: 100 }); }, '.deepAssign() objects with circular references'() { const target: any = { nested: { baz: 'foo', qux: 'baz' } }; target.cyclical = target; const source: any = { nested: { foo: 'bar', bar: 'baz', baz: 'qux' } }; source.cyclical = source; const assignedObject = deepAssign(target, source); assert.deepEqual(assignedObject.nested, { foo: 'bar', bar: 'baz', baz: 'qux', qux: 'baz' }); }, '.deepAssign with a source with two properties holding the same reference'() { const target: any = {}; const foo = { foo: 'bar' }; const source: any = { bar: foo, baz: foo, qux: { foo, bar: { foo } } }; const assignedObject = deepAssign(target, source); assert.deepEqual(assignedObject, { bar: { foo: 'bar' }, baz: { foo: 'bar' }, qux: { foo: { foo: 'bar' }, bar: { foo: { foo: 'bar' } } } }); }, '.mixin()'() { const source: { a: number; c: number; nested: { a: number; }; b: number; hidden: number; } = Object.create({ a: 1 }); source.c = 3; source.nested = { a: 5 }; Object.defineProperty(source, 'b', { enumerable: true, get: function() { return 2; } }); Object.defineProperty(source, 'hidden', { enumerable: false, value: 4 }); const object: {} = Object.create(null); const mixedObject = mixin(object, source); assert.strictEqual(object, mixedObject, 'mixin should return the modified target object'); assert.strictEqual(mixedObject.a, 1, 'mixin should copy inherited properties'); assert.strictEqual(mixedObject.b, 2); assert.strictEqual(mixedObject.c, 3); assert.isUndefined(mixedObject.hidden, 'mixin should not copy non-enumerable properties'); assert.strictEqual(mixedObject.nested, source.nested, 'mixin should perform a shallow copy'); assert.strictEqual(mixedObject.nested.a, 5); }, '.mixin() - multiple sources'() { const source1 = { a: 12, b: false }; const source2 = { c: 'string' }; const mixedObject = mixin({}, source1, source2); assert.strictEqual(mixedObject.a, 12); assert.strictEqual(mixedObject.b, false); assert.strictEqual(mixedObject.c, 'string'); }, '.deepMixin()'() { const source: { nested: { a: number; b: any[]; }; a: number; b: number; c: number; d: Date; e: RegExp; hidden: number; } = Object.create({ nested: { a: 1, b: [2, [3], { f: 4 }] } }); source.a = 1; source.c = 3; source.d = new Date(); source.e = /abc/; Object.defineProperty(source, 'b', { enumerable: true, get: function() { return 2; } }); Object.defineProperty(source, 'hidden', { enumerable: false, value: 4 }); const object: {} = Object.create(null); const mixedObject: {} & typeof source = deepMixin(object, source); assert.strictEqual(object, mixedObject, 'deepMixin should return the modified target object'); assert.strictEqual(mixedObject.a, 1); assert.strictEqual(mixedObject.b, 2); assert.strictEqual(mixedObject.c, 3); assert.strictEqual(mixedObject.d, source.d, 'deepMixin should not deep copy Date object'); assert.strictEqual(mixedObject.e, source.e, 'deepMixin should not deep copy RegExp object'); assert.isUndefined(mixedObject.hidden, 'deepMixin should not copy non-enumerable properties'); assert.strictEqual(mixedObject.nested.a, 1, 'deepMixin should copy inherited properties'); assert.notStrictEqual(mixedObject.nested, source.nested, 'deepMixin should perform a deep copy'); assert.notStrictEqual(mixedObject.nested.b, source.nested.b, 'deepMixin should perform a deep copy'); assert.notStrictEqual(mixedObject.nested.b[1], source.nested.b[1], 'deepMixin should perform a deep copy'); assert.notStrictEqual(mixedObject.nested.b[2], source.nested.b[2], 'deepMixin should perform a deep copy'); }, '.deepMixin() merges nested object on to the target'() { const target = Object.create({ apple: 0, banana: { weight: 52, price: 100, details: { colour: 'brown', texture: 'soft' } }, cherry: 97 }); const source = Object.create({ banana: { price: 200, details: { colour: 'yellow' } }, durian: 100 }); const assignedObject = deepMixin(target, source); assert.deepEqual(assignedObject, { apple: 0, banana: { weight: 52, price: 200, details: { colour: 'yellow', texture: 'soft' } }, cherry: 97, durian: 100 }); }, '.deepMixin() objects with circular references'() { let target: any = { nested: { baz: 'foo', qux: 'baz' } }; target.cyclical = target; target = Object.create(target); let source: any = { nested: { foo: 'bar', bar: 'baz', baz: 'qux' } }; source.cyclical = source; source = Object.create(source); const assignedObject = deepMixin(target, source); assert.deepEqual(assignedObject.nested, { foo: 'bar', bar: 'baz', baz: 'qux', qux: 'baz' }); }, '.partial()'() { const ending = 'jumps over the lazy dog'; const finish = partial( function(this: any) { const start = this && this.start ? [this.start] : []; return start.concat(Array.prototype.slice.call(arguments)).join(' '); }, 'jumps', 'over' ); function Sentence(this: any, start: string = '') { this.start = start; } Sentence.prototype.finish = finish; assert.strictEqual( finish('the lazy dog'), ending, 'The arguments supplied to `partial` should be prepended to the arguments list of the ' + 'original function.' ); assert.strictEqual( finish(), 'jumps over', 'The arguments supplied to `partial` should still be used even if no arguments are passed to the ' + 'wrapped function.' ); assert.strictEqual( new (<any>Sentence)('The quick brown fox').finish('the lazy dog'), 'The quick brown fox ' + ending, 'A function passed to `partial` should inherit its context.' ); }, 'v4 uuid'() { const firstId = uuid(); assert.isDefined(firstId); assert.match( firstId, new RegExp('^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$', 'ig') ); const secondId = uuid(); assert.match( secondId, new RegExp('^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$', 'ig') ); assert.notEqual(firstId, secondId); }, guaranteeMinimumTimeout: { destroy(this: any) { const dfd = this.async(1000); const spy = sinon.spy(); timerHandle = guaranteeMinimumTimeout(spy, 100); setTimeout(function() { destroyTimerHandle(); }, 50); setTimeout( dfd.callback(function() { assert.strictEqual(spy.callCount, 0); }), 110 ); }, timeout(this: any) { const dfd = this.async(1000); const startTime = Date.now(); timerHandle = guaranteeMinimumTimeout( dfd.callback(function() { const dif = Date.now() - startTime; assert.isTrue(dif >= 100, 'Delay was ' + dif + 'ms.'); }), 100 ); }, 'timeout no delay'(this: any) { const dfd = this.async(1000); timerHandle = guaranteeMinimumTimeout( dfd.callback(function() { // test will timeout if not called }) ); }, 'timeout zero delay'(this: any) { const dfd = this.async(1000); timerHandle = guaranteeMinimumTimeout( dfd.callback(function() { // test will timeout if not called }), 0 ); } }, debounce: { 'preserves context'(this: any) { const dfd = this.async(TIMEOUT); // FIXME let foo = { bar: debounce( dfd.callback(function(this: any) { assert.strictEqual(this, foo, 'Function should be executed with correct context'); }), 0 ) }; foo.bar(); }, 'receives arguments'(this: any) { const dfd = this.async(TIMEOUT); const testArg1 = 5; const testArg2 = 'a'; const debouncedFunction = debounce( dfd.callback(function(a: number, b: string) { assert.strictEqual(a, testArg1, 'Function should receive correct arguments'); assert.strictEqual(b, testArg2, 'Function should receive correct arguments'); }), 0 ); debouncedFunction(testArg1, testArg2); }, 'debounces callback'(this: any) { const dfd = this.async(TIMEOUT); const debouncedFunction = debounce( dfd.callback(function() { assert.isAbove( Date.now() - lastCallTick, 10, 'Function should not be called until period has elapsed without further calls' ); // Typically, we expect the 3rd invocation to be the one that is executed. // Although the setTimeout in 'run' specifies a delay of 5ms, a very slow test environment may // take longer. If 25+ ms has actually elapsed, then the first or second invocation may end up // being eligible for execution. }), 25 ); let runCount = 1; let lastCallTick: number; function run() { lastCallTick = Date.now(); debouncedFunction(); runCount += 1; if (runCount < 4) { setTimeout(run, 5); } } run(); } }, throttle: { 'preserves context'(this: any) { const dfd = this.async(TIMEOUT); // FIXME const foo = { bar: throttle( dfd.callback(function(this: any) { assert.strictEqual(this, foo, 'Function should be executed with correct context'); }), 0 ) }; foo.bar(); }, 'receives arguments'(this: any) { const dfd = this.async(TIMEOUT); const testArg1 = 5; const testArg2 = 'a'; const throttledFunction = throttle( dfd.callback(function(a: number, b: string) { assert.strictEqual(a, testArg1, 'Function should receive correct arguments'); assert.strictEqual(b, testArg2, 'Function should receive correct arguments'); }), 0 ); throttledFunction(testArg1, testArg2); }, 'throttles callback'(this: any) { const dfd = this.async(TIMEOUT); let callCount = 0; let cleared = false; const throttledFunction = throttle( dfd.rejectOnError(function(a: string) { callCount++; assert.notStrictEqual(a, 'b', 'Second invocation should be throttled'); // Rounding errors? // Technically, the time diff should be greater than 24ms, but in some cases // it is equal to 24ms. assert.isAbove( Date.now() - lastRunTick, 23, 'Function should not be called until throttle delay has elapsed' ); lastRunTick = Date.now(); if (callCount > 1) { destroyTimerHandle(); cleared = true; dfd.resolve(); } }), 25 ); let runCount = 1; let lastRunTick = 0; function run() { throttledFunction('a'); throttledFunction('b'); runCount += 1; if (runCount < 10 && !cleared) { timerHandle = guaranteeMinimumTimeout(run, 5); } } run(); assert.strictEqual(callCount, 1, 'Function should be called as soon as it is first invoked'); } } });
the_stack
import React, { useState, useEffect, useRef } from "react"; import Match, { MatchData, MatchResult } from "../../models/Match"; import { Map } from "../../models/Map"; import { HeroesByRole, Hero, HeroRoles, HeroRole } from "../../models/Hero"; import Season from "../../models/Season"; import Account from "../../models/Account"; import DayTimeApproximator, { DayOfWeek, TimeOfDay } from "../../models/DayTimeApproximator"; import MapSelect from "../MapSelect"; import HeroSelect from "../HeroSelect"; import RoleSelect from "../RoleSelect"; import TimeOfDayEmoji from "../TimeOfDayEmoji"; import DayOfWeekEmoji from "../DayOfWeekEmoji"; import GroupMembersField from "../GroupMembersField"; import "./MatchForm.css"; import LinkButton from "../LinkButton"; import { Flex, ButtonPrimary } from "@primer/components"; const shouldEnableRankField = (openQueue: boolean, role?: HeroRole | null) => { if (role) { return true; } return openQueue; }; const roleForHero = (hero: Hero): HeroRole => { for (const role of HeroRoles) { if (HeroesByRole[role].includes(hero)) { return role; } } // Shouldn't reach this return "Damage"; }; const dateTimeStrFrom = (date: Date) => { const year = date.getFullYear(); const month = date.getMonth() + 1; let monthStr = month.toString(); if (month <= 9) { monthStr = `0${month}`; } const day = date.getDate(); let dayStr = day.toString(); if (day <= 9) { dayStr = `0${day}`; } const hour = date.getHours(); let hourStr = hour.toString(); if (hour <= 9) { hourStr = `0${hour}`; } const minute = date.getMinutes(); let minuteStr = minute.toString(); if (minute <= 9) { minuteStr = `0${minute}`; } return `${year}-${monthStr}-${dayStr}T${hourStr}:${minuteStr}`; }; interface Props { joinedVoice?: boolean; playOfTheGame?: boolean; allyThrower?: boolean; allyLeaver?: boolean; allyCheater?: boolean; enemyThrower?: boolean; enemyLeaver?: boolean; enemyCheater?: boolean; playedAt?: Date; dayOfWeek?: DayOfWeek; timeOfDay?: TimeOfDay; isPlacement?: boolean; isLastPlacement?: boolean; id?: string; comment?: string; map?: Map; season: Season; openQueue: boolean; priorMatches: Match[]; role?: HeroRole | null; rank?: number; accountID: string; result?: MatchResult; onUpdate?: (id?: string) => void; onCreate?: (id?: string) => void; theme: string; heroes?: string; group?: string; latestGroup?: string | null; groupSize?: number; } interface MatchValidityProps { group?: string; groupSize: number; rank?: number; result?: MatchResult; isPlacement?: boolean; role: HeroRole | null; openQueue: boolean; } const minRank = 0; const maxRank = 5000; const maxGroupSize = 6; const isMatchValid = ({ rank, isPlacement, result, role, groupSize, group, openQueue }: MatchValidityProps) => { if (typeof rank !== "number" || rank < minRank || rank > maxRank) { if (isPlacement && !result) { return false; } if (!isPlacement) { return false; } } if (!openQueue && (typeof role !== "string" || role.length < 1)) { return false; } if (groupSize && groupSize > maxGroupSize) { return false; } if (group && group.split(",").length > maxGroupSize) { return false; } return true; }; const explodeHeroesString = (heroesStr: string) => { return heroesStr .split(",") .map(str => str.trim()) .filter(str => str && str.length > 0); }; type RoleCounts = { [role in HeroRole]?: number; }; type PlayTimes = { initialPlayedAt?: Date; initialDayOfWeek?: DayOfWeek; initialTimeOfDay?: TimeOfDay; }; const getPlayTimes = (props: Props): PlayTimes => { let playedAt = props.playedAt; let dayOfWeek = props.dayOfWeek; let timeOfDay = props.timeOfDay; if (!props.id && !playedAt) { playedAt = new Date(); dayOfWeek = DayTimeApproximator.dayOfWeek(playedAt); timeOfDay = DayTimeApproximator.timeOfDay(playedAt); } return { initialPlayedAt: playedAt, initialDayOfWeek: dayOfWeek, initialTimeOfDay: timeOfDay }; }; type PlacementStatus = { initialIsPlacement: boolean; initialIsLastPlacement: boolean; }; const getPlacementStatus = (props: Props): PlacementStatus => { let isPlacement = props.isPlacement; let isLastPlacement = props.isLastPlacement; if (typeof isPlacement !== "boolean") { const priorPlacements = props.priorMatches.filter(m => m.isPlacement); if (props.openQueue) { // no role queue isPlacement = priorPlacements.length < 10; isLastPlacement = priorPlacements.length === 9; } else { // role queue const placementCountsByRole: RoleCounts = {}; for (const placement of priorPlacements) { if (placement.role) { placementCountsByRole[placement.role] = (placementCountsByRole[placement.role] || 0) + 1; } } // definitely logging a placement match because haven't finished placements for any role isPlacement = Object.values(placementCountsByRole).every( count => typeof count === "number" && count < 5 ); } } return { initialIsLastPlacement: isLastPlacement || false, initialIsPlacement: isPlacement }; }; const MatchForm = (props: Props) => { const placementMatchResultField = useRef<HTMLSelectElement | null>(); const matchRankField = useRef<HTMLInputElement | null>(); const { initialPlayedAt, initialTimeOfDay, initialDayOfWeek } = getPlayTimes( props ); const { initialIsLastPlacement, initialIsPlacement } = getPlacementStatus( props ); const [playedAt, setPlayedAt] = useState(initialPlayedAt); const [timeOfDay, setTimeOfDay] = useState(initialTimeOfDay); const [dayOfWeek, setDayOfWeek] = useState(initialDayOfWeek); const [isPlacement, setIsPlacement] = useState(initialIsPlacement); const [isLastPlacement, setIsLastPlacement] = useState( initialIsLastPlacement ); const [enableRankField, setEnableRankField] = useState( shouldEnableRankField(props.openQueue, props.role) ); const [rank, setRank] = useState<number | undefined>( props.id ? props.rank : undefined ); const [latestRank, setLatestRank] = useState<number | undefined>(props.rank); const [result, setResult] = useState<MatchResult | undefined>(props.result); const [comment, setComment] = useState(props.comment || ""); const [map, setMap] = useState<Map | undefined>(props.map); const [group, setGroup] = useState(props.group || ""); const [groupSize, setGroupSize] = useState(props.groupSize || 1); const [groupMembers, setGroupMembers] = useState<string[]>([]); const [heroes, setHeroes] = useState(props.heroes || ""); const [role, setRole] = useState<HeroRole | null>(props.role || null); const [joinedVoice, setJoinedVoice] = useState( typeof props.joinedVoice === "boolean" ? props.joinedVoice : false ); const [playOfTheGame, setPlayOfTheGame] = useState( typeof props.playOfTheGame === "boolean" ? props.playOfTheGame : false ); const [allyThrower, setAllyThrower] = useState( typeof props.allyThrower === "boolean" ? props.allyThrower : false ); const [allyLeaver, setAllyLeaver] = useState( typeof props.allyLeaver === "boolean" ? props.allyLeaver : false ); const [allyCheater, setAllyCheater] = useState( typeof props.allyCheater === "boolean" ? props.allyCheater : false ); const [enemyThrower, setEnemyThrower] = useState( typeof props.enemyThrower === "boolean" ? props.enemyThrower : false ); const [enemyLeaver, setEnemyLeaver] = useState( typeof props.enemyLeaver === "boolean" ? props.enemyLeaver : false ); const [enemyCheater, setEnemyCheater] = useState( typeof props.enemyCheater === "boolean" ? props.enemyCheater : false ); const [isValid, setIsValid] = useState( isMatchValid({ rank, isPlacement, result, role, openQueue: props.openQueue, groupSize, group }) ); const refreshGroupMembers = async () => { const { accountID, season } = props; const members = await Account.findAllGroupMembers(accountID, season); setGroupMembers(members); }; const onSubmit = async () => { if (!isValid) { return; } const data: MatchData = { comment, map, group, groupSize, accountID: props.accountID, heroes, playedAt, allyThrower, allyLeaver, allyCheater, enemyThrower, enemyLeaver, enemyCheater, playOfTheGame, joinedVoice, season: props.season.number, openQueue: props.openQueue, role: role || undefined, isPlacement, _id: props.id, result }; if (typeof rank === "number") { data.rank = rank; } const match = new Match(data); await match.save(); if (props.id) { if (props.onUpdate) { props.onUpdate(match._id); } } else if (props.onCreate) { props.onCreate(match._id); } }; const onFormFieldUpdate = () => { setIsValid( isMatchValid({ rank, isPlacement, result, role, openQueue: props.openQueue, groupSize, group }) ); }; const onCommentChange = (event: React.ChangeEvent<HTMLInputElement>) => { setComment(event.target.value); onFormFieldUpdate(); }; const onMapChange = (map?: Map | null) => { if (map) { setMap(map); } else { setMap(undefined); } onFormFieldUpdate(); }; const onRankChange = (event: React.ChangeEvent<HTMLInputElement>) => { let rankStr = event.target.value; if (rankStr.length > 0) { setRank(parseInt(rankStr, 10)); } else { setRank(undefined); } onFormFieldUpdate(); }; const onResultChange = (event: React.ChangeEvent<HTMLSelectElement>) => { const newResult = event.target.value; if (newResult.length > 0) { setResult(newResult as MatchResult); } else { setResult(undefined); } onFormFieldUpdate(); }; const onGroupChange = (group: string, groupSize: number) => { setGroup(group); setGroupSize(groupSize); onFormFieldUpdate(); }; const onGroupSizeChange = (event: React.ChangeEvent<HTMLSelectElement>) => { let groupSizeStr = event.target.value; if (groupSizeStr.length > 0) { setGroupSize(parseInt(groupSizeStr, 10)); } else { setGroupSize(1); } onFormFieldUpdate(); }; const onPlayedAtChange = (event: React.ChangeEvent<HTMLInputElement>) => { let playedAtStr = event.target.value; if (playedAtStr.length > 0) { setPlayedAt(new Date(playedAtStr)); setDayOfWeek(DayTimeApproximator.dayOfWeek(playedAtStr)); setTimeOfDay(DayTimeApproximator.timeOfDay(playedAtStr)); } else { setPlayedAt(undefined); setDayOfWeek(undefined); setTimeOfDay(undefined); } onFormFieldUpdate(); }; const onDayOfWeekTimeOfDayChange = ( event: React.ChangeEvent<HTMLSelectElement> ) => { const dayOfWeekTimeOfDay = event.target.value; if (dayOfWeekTimeOfDay.indexOf("-") < 0) { setDayOfWeek(undefined); setTimeOfDay(undefined); onFormFieldUpdate(); return; } const parts = dayOfWeekTimeOfDay.split("-"); if (dayOfWeek !== parts[0] || timeOfDay !== parts[1]) { setPlayedAt(undefined); } setDayOfWeek(parts[0] as DayOfWeek); setTimeOfDay(parts[1] as TimeOfDay); onFormFieldUpdate(); }; const changeHeroesString = ( heroesStr: string, hero: Hero, isSelected: boolean ) => { const heroes = explodeHeroesString(heroesStr); const heroIndex = heroes.indexOf(hero); if (isSelected && heroIndex < 0) { heroes.push(hero); } if (!isSelected && heroIndex > -1) { delete heroes[heroIndex]; } return heroes.join(", "); }; const getPriorPlacementsInRole = (role: HeroRole) => { return props.priorMatches.filter(m => m.role === role && m.isPlacement); }; const getLatestRankInRole = (role: HeroRole) => { const priorMatchesInRole = props.priorMatches.filter( m => m.role === role && typeof m.rank === "number" ); const latestMatchInRole = priorMatchesInRole[priorMatchesInRole.length - 1]; if (latestMatchInRole) { return latestMatchInRole.rank; } }; const onRoleChange = (newRole: HeroRole) => { const { openQueue } = props; const heroesInRole = HeroesByRole[newRole]; const oldSelectedHeroes = explodeHeroesString(heroes); const selectedHeroes = oldSelectedHeroes.filter( hero => heroesInRole.indexOf(hero as Hero) > -1 ); const priorPlacementMatchesInRole = getPriorPlacementsInRole(newRole); setRole(newRole); setHeroes(selectedHeroes.join(", ")); if (!openQueue) { if (priorPlacementMatchesInRole.length < 5) { setIsPlacement(true); setIsLastPlacement(priorPlacementMatchesInRole.length === 4); } else { setIsPlacement(false); setIsLastPlacement(false); } setLatestRank(getLatestRankInRole(newRole)); setEnableRankField(typeof newRole === "string" && newRole.length > 0); } else { setEnableRankField(true); } onFormFieldUpdate(); }; const onHeroChange = (hero: Hero, isSelected: boolean) => { const newHeroes = changeHeroesString(heroes, hero, isSelected); setHeroes(newHeroes); const { openQueue } = props; if (!openQueue) { if (isSelected && (typeof role !== "string" || role.length < 1)) { const newRole = roleForHero(hero); setRole(newRole); const priorPlacementMatchesInRole = getPriorPlacementsInRole(newRole); if (priorPlacementMatchesInRole.length < 5) { setIsPlacement(true); setIsLastPlacement(priorPlacementMatchesInRole.length === 4); } else { setIsPlacement(false); setIsLastPlacement(false); } const newLatestRank = getLatestRankInRole(newRole); if (typeof latestRank === "number") { setLatestRank(newLatestRank); } } else if (!isSelected && newHeroes.length < 1) { setRole(null); setIsLastPlacement(false); setLatestRank(undefined); } } else { setRole(null); } onFormFieldUpdate(); }; const onAllyThrowerChange = (event: React.ChangeEvent<HTMLInputElement>) => { setAllyThrower(event.target.checked); onFormFieldUpdate(); }; const onAllyLeaverChange = (event: React.ChangeEvent<HTMLInputElement>) => { setAllyLeaver(event.target.checked); onFormFieldUpdate(); }; const onAllyCheaterChange = (event: React.ChangeEvent<HTMLInputElement>) => { setAllyCheater(event.target.checked); onFormFieldUpdate(); }; const onEnemyThrowerChange = (event: React.ChangeEvent<HTMLInputElement>) => { setEnemyThrower(event.target.checked); onFormFieldUpdate(); }; const onEnemyLeaverChange = (event: React.ChangeEvent<HTMLInputElement>) => { setEnemyLeaver(event.target.checked); onFormFieldUpdate(); }; const onEnemyCheaterChange = (event: React.ChangeEvent<HTMLInputElement>) => { setEnemyCheater(event.target.checked); onFormFieldUpdate(); }; const onPlayOfTheGameChange = ( event: React.ChangeEvent<HTMLInputElement> ) => { setPlayOfTheGame(event.target.checked); onFormFieldUpdate(); }; const onJoinedVoiceChange = (event: React.ChangeEvent<HTMLInputElement>) => { setJoinedVoice(event.target.checked); onFormFieldUpdate(); }; const { season, latestGroup, theme, accountID, openQueue } = props; const dayOfWeekTimeOfDay = `${dayOfWeek}-${timeOfDay}`; useEffect(() => { setEnableRankField(shouldEnableRankField(openQueue, role)); refreshGroupMembers(); setIsValid( isMatchValid({ rank, role, isPlacement, openQueue, groupSize, group, result }) ); }, [ accountID, rank, role, isPlacement, season, groupSize, group, result, latestRank, isLastPlacement, comment, map, heroes, playedAt, playOfTheGame, joinedVoice, allyThrower, allyLeaver, allyCheater, enemyThrower, enemyLeaver, enemyCheater, openQueue ]); useEffect(() => { // Already have new SR and match result, no need to focus the field if (result && typeof rank === "number") { return; } // New SR field is shown and disabled, can't focus it if (!isPlacement && !enableRankField) { return; } // Role selection is required first if (!openQueue && !role) { return; } if (placementMatchResultField.current) { placementMatchResultField.current.focus(); } else if (matchRankField.current) { matchRankField.current.focus(); } }, [ placementMatchResultField, matchRankField, result, rank, enableRankField, openQueue, role, isPlacement ]); return ( <form onSubmit={evt => { evt.preventDefault(); onSubmit(); }} className="mb-4" > <div className="clearfix"> <div className="col-md-12 col-lg-6 float-left pr-3-lg"> {!openQueue && ( <div className="form-group mt-0"> <span className="f3 mr-4">Role played:</span> <RoleSelect selectedRole={role} theme={theme} onChange={onRoleChange} /> </div> )} <div className="d-flex-md mb-2 flex-items-center-md flex-justify-between-md"> <div className="form-group my-0 d-flex flex-items-center"> {isPlacement ? ( <label htmlFor="match-result" className="label-lg mr-2 no-wrap"> Placement match result: </label> ) : ( <label htmlFor="match-rank" className="label-lg mr-2 no-wrap"> New{" "} <span className="tooltipped tooltipped-n" aria-label="Skill Rating" > SR </span> : </label> )} {isPlacement ? ( <select className="form-select select-lg" value={result} required autoFocus={openQueue} id="match-result" onChange={onResultChange} ref={el => (placementMatchResultField.current = el)} > <option value=""></option> <option value="win">Win</option> <option value="loss">Loss</option> <option value="draw">Draw</option> </select> ) : ( <input id="match-rank" type="number" required autoFocus={openQueue} ref={el => (matchRankField.current = el)} className="form-control sr-field" value={rank || ""} onChange={onRankChange} placeholder={ typeof latestRank === "number" ? latestRank.toString() : "" } disabled={!enableRankField} /> )} </div> <dl className="form-group my-0 ml-4"> <dt> <label htmlFor="match-map"> <span className="ion ion-md-pin mr-1" /> Map: </label> </dt> <dd> <MapSelect map={map} onChange={onMapChange} /> </dd> </dl> </div> {isPlacement && isLastPlacement && ( <dl className="form-group mt-0"> <dt> <label htmlFor="match-rank" className="sr-field-label"> {role && !openQueue ? `Where did you place as a ${role}?` : "Where did you place?"} </label> </dt> <dd> <input id="match-rank" type="number" className="form-control sr-field" value={rank} onChange={onRankChange} placeholder={latestRank ? latestRank.toString() : ""} /> </dd> </dl> )} <dl className="form-group mt-0"> <dt> <label htmlFor="match-comment"> <span className="ion ion-md-list mr-1" /> Comment: </label> </dt> <dd> <input id="match-comment" type="text" className="form-control width-full" value={comment} onChange={onCommentChange} placeholder="Notes about this game" /> </dd> </dl> <fieldset className="Box pt-2 pb-3 px-3"> <legend className="h5"> <span className="ion ion-md-people mr-1" /> Your group </legend> <GroupMembersField group={group} groupMembers={groupMembers} onGroupChange={onGroupChange} latestGroup={latestGroup} /> <dl className="form-group mb-0"> <dt> <label htmlFor="match-group-size"> How many people did you queue with? </label> </dt> <dd> <select id="match-group-size" className="form-select" value={groupSize} onChange={onGroupSizeChange} > <option value="1">Nobody (solo queue)</option> <option value="2">1 other person</option> <option value="3">2 other people</option> <option value="4">3 other people</option> <option value="5">4 other people</option> <option value="6">5 other people (6-stack)</option> </select> </dd> </dl> </fieldset> <div className="d-flex"> <div className="form-checkbox mr-4"> <label> <input type="checkbox" checked={playOfTheGame} onChange={onPlayOfTheGameChange} /> <span className="ion ion-md-trophy mr-1" /> Play of the game </label> <p className="note">Did you get play of the game?</p> </div> <div className="form-checkbox"> <label> <input type="checkbox" checked={joinedVoice} onChange={onJoinedVoiceChange} /> <span className="ion ion-md-mic mr-1" /> Joined voice chat </label> <p className="note">Did you join voice chat?</p> </div> </div> <div className="mb-3"> <div className="text-bold"> Did anyone try to sabotage the game? </div> <div className="float-left col-lg-4 col-md-5"> <div className="form-checkbox mr-4 mb-0 mt-1"> <label className="text-normal no-wrap text-ally"> <input type="checkbox" checked={allyThrower} onChange={onAllyThrowerChange} /> Thrower on my team </label> </div> <div className="form-checkbox mr-4 my-1"> <label className="text-normal no-wrap text-ally"> <input type="checkbox" checked={allyLeaver} onChange={onAllyLeaverChange} /> Leaver on my team </label> </div> <div className="form-checkbox mr-4 my-1"> <label className="text-normal no-wrap text-ally"> <input type="checkbox" checked={allyCheater} onChange={onAllyCheaterChange} /> Cheater on my team </label> </div> </div> <div className="float-left col-lg-5 col-md-7"> <div className="form-checkbox mb-0 mt-1"> <label className="text-normal no-wrap text-enemy"> <input type="checkbox" checked={enemyThrower} onChange={onEnemyThrowerChange} /> Thrower on the enemy team </label> </div> <div className="form-checkbox my-1"> <label className="text-normal no-wrap text-enemy"> <input type="checkbox" checked={enemyLeaver} onChange={onEnemyLeaverChange} /> Leaver on the enemy team </label> </div> <div className="form-checkbox my-1"> <label className="text-normal no-wrap text-enemy"> <input type="checkbox" checked={enemyCheater} onChange={onEnemyCheaterChange} /> Cheater on the enemy team </label> </div> </div> </div> </div> <div className="col-md-12 col-lg-6 float-right pl-3-lg"> <dl className="form-group my-0"> <dt className="text-bold">Heroes played:</dt> <dd> <HeroSelect role={role} theme={theme} heroes={heroes} season={season} onToggle={onHeroChange} /> </dd> </dl> <dl className="form-group mt-0"> <dt> <label className="f6" htmlFor="match-played-at"> <span className="ion ion-md-time mr-1" /> When did you play? </label> </dt> <dd> <input id="match-played-at" type="datetime-local" className="input-sm form-control datetime-local-control" value={playedAt ? dateTimeStrFrom(playedAt) : ""} onChange={onPlayedAtChange} /> {dayOfWeek && timeOfDay ? ( <span className="d-inline-block ml-2"> <DayOfWeekEmoji dayOfWeek={dayOfWeek} />{" "} <TimeOfDayEmoji timeOfDay={timeOfDay} /> </span> ) : null} <select className="input-sm form-select ml-2" value={dayOfWeekTimeOfDay} aria-label="When did you generally play the game?" onChange={onDayOfWeekTimeOfDayChange} > <option value="">Choose a day and time</option> <option value="weekday-morning">Weekday morning</option> <option value="weekday-afternoon">Weekday afternoon</option> <option value="weekday-evening">Weekday evening</option> <option value="weekday-night">Weekday night</option> <option value="weekend-morning">Weekend morning</option> <option value="weekend-afternoon">Weekend afternoon</option> <option value="weekend-evening">Weekend evening</option> <option value="weekend-night">Weekend night</option> </select> </dd> </dl> </div> </div> <Flex alignItems="center" justifyContent="flex-end"> {props.id && props.onUpdate && ( <LinkButton mr={3} onClick={() => props.onUpdate && props.onUpdate()}> Cancel edit </LinkButton> )} <ButtonPrimary type="submit" variant="large" disabled={!isValid} >Save match</ButtonPrimary> </Flex> </form> ); }; export default MatchForm;
the_stack
import * as React from "react"; import { Button, Checkbox, FormControl, FormLabel, FormHelperText, Divider, Input, IconButton, Radio, Select, Switch, Textarea, Badge, Code, Kbd, Tag, Breadcrumb, Link, Avatar, Icon, Dot, Image, InfoIcon, XCricleIcon, CheckCircleIcon, ExclamationIcon, Alert, Spinner, useMessage, useNotification, cx, } from "@vechaiui/react"; import { Menu, Listbox, Dialog, Popover, Portal, RadioGroup, Disclosure, Transition, } from "@headlessui/react"; import { ArrowsExpandIcon, DuplicateIcon, ShareIcon, CalendarIcon, TagIcon, HashtagIcon, CheckIcon, SelectorIcon, XIcon, SunIcon, StarIcon, MoonIcon, ChevronUpIcon, ChevronRightIcon, UserCircleIcon, BellIcon, ShieldCheckIcon, } from "@heroicons/react/outline"; import * as Slider from "@radix-ui/react-slider"; import * as Tabs from "@radix-ui/react-tabs"; import { useTheme, themes } from "@components/theme-controller"; function RadioGroupDemo() { const themes = [ { value: "light", name: "Light", icon: SunIcon, }, { value: "dark", name: "Dark", icon: MoonIcon, }, { value: "system", name: "System", icon: StarIcon, }, ]; const [value, setValue] = React.useState(themes[0].value); return ( <RadioGroup value={value} onChange={setValue}> <RadioGroup.Label className="sr-only">Radius</RadioGroup.Label> <div className="inline-flex p-0.5 space-x-0 rounded-md bg-neutral-200 dark:bg-neutral-700"> {themes.map((item) => ( <RadioGroup.Option key={item.name} value={item.value} className={({ checked, }) => `inline-flex appearance-none items-center justify-center rounded-md select-none relative whitespace-nowrap align-middle outline-none font-semibold text-xs px-4 py-1.5 focus:outline-none ${ checked ? "bg-white text-primary-500 shadow dark:bg-neutral-800" : "text-neutral-600 dark:text-neutral-400" } `} > <Icon as={item.icon} label="radio-group" className="w-4 h-4 mr-1" /> <span>{item.name}</span> </RadioGroup.Option> ))} </div> </RadioGroup> ); } function Complexity() { return ( <Menu as="div" className="relative inline-block w-full"> <Menu.Button as={Button} variant="solid" color="primary"> Actions </Menu.Button> <Transition show as={React.Fragment} enter="transition ease-out duration-100" enterFrom="transform opacity-0 scale-95" enterTo="transform opacity-100 scale-100" leave="transition ease-in duration-75" leaveFrom="transform opacity-100 scale-100" leaveTo="transform opacity-0 scale-95" > <Menu.Items static className={cx( "relative z-dropdown w-full mt-2 origin-top-left rounded-md shadow-sm outline-none", "bg-white border border-gray-200", "dark:bg-neutral-800 dark:border-gray-700" )} > <div className="px-1 py-1"> <Menu.Item> {({ active, disabled }) => ( <button disabled={disabled} aria-disabled={disabled} className={cx( "flex rounded items-center w-full px-3 h-8 flex-shrink-0 text-sm text-left cursor-base focus:outline-none", active && "bg-neutral-100 dark:bg-neutral-700", disabled && "disabled:opacity-60 disabled:cursor-not-allowed" )} > <Icon as={ArrowsExpandIcon} label="arrows-expand" className={cx( "w-4 h-4 mr-2", active ? "" : "text-neutral-500" )} /> <span className="flex-1">Fullscreen</span> <Kbd>⌘F</Kbd> </button> )} </Menu.Item> <Menu.Item> {({ active, disabled }) => ( <button disabled={disabled} aria-disabled={disabled} className={cx( "flex rounded items-center w-full px-3 h-8 flex-shrink-0 text-sm text-left cursor-base focus:outline-none", active && "bg-neutral-100 dark:bg-neutral-700", disabled && "disabled:opacity-60 disabled:cursor-not-allowed" )} > <Icon as={DuplicateIcon} label="duplicate" className={cx( "w-4 h-4 mr-2", active ? "" : "text-neutral-500" )} /> <span className="flex-1">Copy</span> <Kbd>⌘⇧C</Kbd> </button> )} </Menu.Item> <Menu.Item> {({ active, disabled }) => ( <button disabled={disabled} aria-disabled={disabled} className={cx( "flex rounded items-center w-full px-3 h-8 flex-shrink-0 text-sm text-left cursor-base focus:outline-none", active && "bg-neutral-100 dark:bg-neutral-700", disabled && "disabled:opacity-60 disabled:cursor-not-allowed" )} > <Icon as={ShareIcon} label="share" className={cx( "w-4 h-4 mr-2", active ? "" : "text-neutral-500" )} /> <span className="flex-1">Share</span> </button> )} </Menu.Item> <Divider orientation="horizontal" className="border-neutral-200 dark:border-neutral-700" /> <Menu.Item> {({ active, disabled }) => ( <button disabled={disabled} aria-disabled={disabled} className={cx( "flex rounded items-center w-full px-3 h-8 flex-shrink-0 text-sm text-left cursor-base focus:outline-none", active && "bg-neutral-100 dark:bg-neutral-700", disabled && "disabled:opacity-60 disabled:cursor-not-allowed" )} > <Icon as={CalendarIcon} label="calendar" className={cx( "w-4 h-4 mr-2", active ? "" : "text-neutral-500" )} /> <span className="flex-1">Due Date</span> <Kbd>⌘D</Kbd> </button> )} </Menu.Item> <Menu.Item> {({ active, disabled }) => ( <button disabled={disabled} aria-disabled={disabled} className={cx( "flex rounded items-center w-full px-3 h-8 flex-shrink-0 text-sm text-left cursor-base focus:outline-none", active && "bg-neutral-100 dark:bg-neutral-700", disabled && "disabled:opacity-60 disabled:cursor-not-allowed" )} > <Icon as={TagIcon} label="tag" className={cx( "w-4 h-4 mr-2", active ? "" : "text-neutral-500" )} /> <span className="flex-1">Priority</span> </button> )} </Menu.Item> <Menu.Item> {({ active, disabled }) => ( <button disabled={disabled} aria-disabled={disabled} className={cx( "flex rounded items-center w-full px-3 h-8 flex-shrink-0 text-sm text-left cursor-base focus:outline-none", active && "bg-neutral-100 dark:bg-neutral-700", disabled && "disabled:opacity-60 disabled:cursor-not-allowed" )} > <Icon as={HashtagIcon} label="hashtag" className={cx( "w-4 h-4 mr-2", active ? "" : "text-neutral-500" )} /> <span className="flex-1">Unsubscribe</span> <Kbd>⌘⇧U</Kbd> </button> )} </Menu.Item> </div> </Menu.Items> </Transition> </Menu> ); } function DialogDemo() { return ( <div className={cx( "relative flex flex-col w-full rounded shadow-lg", "bg-white border border-gray-200", "dark:bg-neutral-800 dark:border-neutral-700", "max-w-md px-2" )} > <header className={cx("px-3 pt-3 pb-2 relative text-lg font-semibold")}> Confirm deletion </header> <button className={cx( "absolute text-sm cursor-base text-gray-600 dark:text-gray-400 hover:text-primary-400 hover:text-primary-500 top-4 right-4" )} > <XIcon className="w-4 h-4" /> </button> <Divider orientation="horizontal" className="border-neutral-200 dark:border-neutral-700" /> <div className={cx("px-3 py-2 flex-1")}> <p className="mb-4 text-sm font-normal text-muted"> To delete your project, please enter the name of your project{" "} <b>pepelele</b>. Once deleted this project will be unrecoverable. </p> <FormControl> <FormLabel htmlFor="name" id="name-label"> Confirm name </FormLabel> <Input id="name" color="red" /> </FormControl> </div> <Divider orientation="horizontal" className="border-neutral-200 dark:border-neutral-700" /> <footer className={cx("flex space-x-4 justify-end px-3 py-2")}> <Button>Cancel</Button> <Button variant="solid" color="red"> Delete </Button> </footer> </div> ); } function TabsDemo() { const tabs = [ { value: "tab1", name: "Account", content: "Tab one content", icon: UserCircleIcon, }, { value: "tab2", name: "Notifications", content: "Tab second content", icon: BellIcon, }, // { // value: "tab3", // name: "Security", // content: "Tab third content", // icon: ShieldCheckIcon, // }, ]; return ( <Tabs.Root className="flex flex-col" defaultValue="tab1"> <Tabs.List aria-label="tabs example" className={cx( "flex flex-row justify-start", "border-b border-neutral-200 dark:border-neutral-700" )} > {tabs.map((tab) => ( <Tabs.Trigger key={tab.value} value={tab.value} className={cx( "flex items-center justify-center px-3 py-2 -mb-px text-sm text-center whitespace-nowrap cursor-base focus:outline-none", "text-neutral-900 bg-transparent border-b-2 border-transparent", "hover:border-neutral-300", "selected:border-primary-500", // dark "dark:text-neutral-100", "dark:hover:border-neutral-600", "dark:selected:border-primary-500" )} > <Icon as={tab.icon} label="icon" className="w-4 h-4 mr-2" /> <span>{tab.name}</span> {tab.value === "tab2" && <Badge className="ml-2">18</Badge>} </Tabs.Trigger> ))} </Tabs.List> {tabs.map((tab) => ( <Tabs.Content key={tab.value} value={tab.value} className="p-4 flex-grow-1" > {tab.content} </Tabs.Content> ))} </Tabs.Root> ); } export default function Gallery() { const { colorScheme, setColorScheme } = useTheme(); const toggleTheme = () => { const idx = themes.findIndex((theme) => theme.id === colorScheme); const next = idx === themes.length - 1 ? 0 : idx + 1; setColorScheme(themes[next].id); }; return ( <div className="relative w-screen h-screen overflow-hidden"> <div className="relative w-full max-w-5xl py-20 mx-auto"> <Button className="absolute righ-0 top-2" size="sm" onClick={toggleTheme} > Toggle Theme </Button> <div className="grid grid-flow-col grid-rows-3 gap-16"> <div className="row-span-3" style={{ minWidth: 245, maxWidth: 245 }}> <div className="space-y-4"> <Complexity /> <TabsDemo /> </div> </div> <div className="grid grid-cols-2 col-span-2 row-span-3 gap-16"> <div className="space-y-4"> <div className="flex space-x-4"> <Input placeholder="Input" /> <Input disabled value="Disabled" /> </div> <Input defaultValue="Default" /> <div className="flex space-x-4"> <Select placeholder="Placeholder" className="w-1/2"> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> </Select> <Select disabled placeholder="Placeholder" className="w-1/2"> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> </Select> </div> </div> <div className="flex flex-col space-y-4"> <div className="flex space-x-8"> <Checkbox.Group inline={false} value={["sasuke"]} className="flex flex-col space-y-2" > <Checkbox value="naruto">Regualar</Checkbox> <Checkbox value="sasuke">Selected</Checkbox> <Checkbox value="sakura" disabled> Disabled </Checkbox> </Checkbox.Group> <Radio.Group defaultValue="2" inline={false} className="flex flex-col space-y-2" > <Radio value="1">Regualar</Radio> <Radio value="2">Selected</Radio> <Radio value="3" disabled> Disabled </Radio> </Radio.Group> </div> <Slider.Root defaultValue={[25, 75]} className="relative flex items-center h-4 select-none" > <Slider.Track className="relative w-full h-1 bg-neutral-200 dark:bg-whiteAlpha-300 flex-grow-1"> <Slider.Range className="absolute h-full rounded-full bg-primary-500 dark:bg-primary-200" /> </Slider.Track> <Slider.Thumb className="block w-4 h-4 bg-white border rounded-full border-neutral-300 focus:outline-none focus:border-primary-500 focus:ring-1 focus:ring-primary-500" /> <Slider.Thumb className="block w-4 h-4 bg-white border rounded-full border-neutral-300 focus:outline-none focus:border-primary-500 focus:ring-1 focus:ring-primary-500" /> </Slider.Root> </div> <div> <div className="grid grid-cols-3 gap-2"> <Button>Button</Button> <Button color="primary">Button</Button> <Button color="orange">Button</Button> <Button variant="solid">Button</Button> <Button variant="solid" color="primary"> Button </Button> <Button variant="solid" color="orange"> Button </Button> <Button variant="ghost">Button</Button> <Button variant="ghost" color="primary"> Button </Button> <Button variant="ghost" color="orange"> Button </Button> <div className="col-span-3"> <Button className="w-full" variant="light" color="red"> Button </Button> </div> </div> </div> <div className="space-y-2"> <div className="flex flex-row space-x-4"> <div className="space-y-4"> <FormControl className="flex items-center"> <Switch defaultChecked id="light" /> <FormLabel htmlFor="light" className="mb-0 ml-2"> Light </FormLabel> </FormControl> <FormControl className="flex items-center"> <Switch id="dark" /> <FormLabel htmlFor="dark" className="mb-0 ml-2"> Dark </FormLabel> </FormControl> </div> <div className="flex flex-wrap"> <Tag className="mb-2 mr-2">Default</Tag> <Tag color="primary" className="mb-2 mr-2"> <Tag.Label>Primary</Tag.Label> <Tag.CloseButton className="text-primary-600 dark:text-primary-400" /> </Tag> <Tag color="orange" className="mb-2 mr-2"> <Tag.Label>Orange</Tag.Label> <Tag.CloseButton className="text-orange-600 dark:text-orange-400" /> </Tag> {/* <Tag variant="solid" className="mb-2 mr-2"> Default </Tag> */} <Tag variant="solid" color="primary" className="mb-2 mr-2"> <Tag.Label>Primary</Tag.Label> <Tag.CloseButton className="text-white dark:text-primary-400" /> </Tag> <Tag variant="solid" color="orange" className="mb-2 mr-2"> <Tag.Label>Orange</Tag.Label> <Tag.CloseButton className="text-white dark:text-orange-400" /> </Tag> </div> </div> <div className="flex flex-wrap"> {/* <Tag variant="light" className="mb-2 mr-2"> <Dot className="mr-2" /> <Tag.Label>Default</Tag.Label> </Tag> */} <Tag color="primary" variant="light" className="mb-2 mr-2"> <Dot className="mr-2" color="primary" /> <Tag.Label>Primary</Tag.Label> <Tag.CloseButton className="text-primary-600 dark:text-primary-400" /> </Tag> <Tag color="orange" variant="light" className="mb-2 mr-2"> <Dot className="mr-2" color="orange" /> <Tag.Label>Orange</Tag.Label> <Tag.CloseButton className="text-orange-600 dark:text-orange-400" /> </Tag> <Tag color="red" variant="light" className="mb-2 mr-2"> <Dot className="mr-2" color="red" /> <Tag.Label>Red</Tag.Label> <Tag.CloseButton className="text-red-600 dark:text-red-400" /> </Tag> </div> <RadioGroupDemo /> </div> </div> </div> <div className="grid grid-cols-2 gap-16 mt-8"> <div className="w-full space-y-4"> <Alert variant="solid" className="alert-yellow"> Flash message goes here. <Alert.CloseButton className="alert-close-button-yellow" /> </Alert> <Alert color="orange" variant="subtle"> Flash message goes here. <Alert.CloseButton /> </Alert> <Alert color="red" variant="left-accent"> Flash message goes here. <Alert.CloseButton /> </Alert> <div className="flex items-center space-x-4"> <Avatar.Group size="lg" max={2}> <Avatar name="Bruce Wayne" src="https://images.unsplash.com/photo-1531259683007-016a7b628fc3" /> <Avatar name="Captain America " src="https://images.unsplash.com/photo-1569003339405-ea396a5a8a90" /> <Avatar name="Spiderman" src="https://images.unsplash.com/photo-1604200213928-ba3cf4fc8436" /> <Avatar name="Wonder Woman" src="https://bit.ly/prosper-baba" /> <Avatar name="Christian Nwamba" src="https://bit.ly/code-beast" /> </Avatar.Group> <div className="flex space-x-2"> <Badge variant="solid">1</Badge> <Badge color="primary" variant="solid"> 1 </Badge> </div> <div className="flex space-x-2"> <Kbd>⌘</Kbd> <Kbd>shift</Kbd> </div> <div className="flex space-x-2"> <Code>New Issue</Code> <Code>Cmd/Ctrl</Code> </div> <div className="flex space-x-2"> <Spinner /> <Spinner className="text-primary-500" /> </div> </div> </div> <div> <DialogDemo /> </div> </div> </div> </div> ); }
the_stack
import * as path from 'path'; import * as fs from 'fs'; import { homedir } from 'os'; import { remote, ipcRenderer as ipc } from 'electron'; import * as encoding from 'encoding-japanese'; const config = remote.getGlobal('config') as Config; const home_dir = config.hide_title_bar ? '' : homedir(); const on_darwin = process.platform === 'darwin'; function noop() { /* do nothing */ } let watching_path = remote.require('./initial_path.js')(config.default_watch_path || ''); let onPathButtonPushed = noop; let onSearchButtonPushed = noop; let onTOCButtonPushed = noop; function getMainDrawerPanel() { return document.getElementById('main-drawer') as MainDrawerPanel; } /* tslint:disable no-unused-variable*/ function onPrintButtonPushed(): void { remote.getCurrentWindow().webContents.print(); } /* tslint:enable no-unused-variable*/ function getLintArea() { return document.getElementById('lint-area') as LintResultArea; } function make_title(p: string): string { if (!p || config.hide_title_bar) { return 'Shiba'; } if (p.startsWith(home_dir)) { return make_title(`~${p.slice(home_dir.length)}`); } return `Shiba (${p})`; } function getScroller(): Scroller { const selected: string = getMainDrawerPanel().selected; if (selected === null) { return null; } if (selected === 'drawer') { const panel: HeaderPanel = document.querySelector('paper-header-panel[drawer]'); return panel.scroller; } else { return document.getElementById('viewer-wrapper'); } } function scrollContentBy(x: number, y: number) { const scroller = getScroller(); if (!scroller) { return; } if (x !== 0) { scroller.scrollLeft += x; } if (y !== 0) { scroller.scrollTop += y; } } function setChildToViewerWrapper(new_child: HTMLElement): void { const target = document.getElementById('viewer-wrapper'); if (target.hasChildNodes()) { target.replaceChild(new_child, target.firstChild); } else { target.appendChild(new_child); } } function openMarkdownDoc(file_path: string, modifier_key: boolean) { // Note: // This callback is called when open other document is opened. ipc.send('shiba:notify-path', file_path); if (modifier_key) { document.title = make_title(file_path); watching_path = file_path; } } function renderMarkdownPreview(file: string) { const exts = config.file_ext.markdown; const font_size = config.markdown.font_size; const isGitHubStyle = config.markdown.css_path.endsWith('/github-markdown.css'); fs.readFile(file, null, (err: Error, bytes: Buffer) => { if (err) { console.error(err); return; } // Note: // ASCII, BINARY and UTF32 are detection only, not convertable. const enc = encoding.detect(bytes); const markdown = !enc || enc === 'UTF8' || enc === 'ASCII' || enc === 'BINARY' || enc === 'UTF32' ? bytes.toString() : Buffer.from(encoding.convert(bytes, 'UTF8', enc)).toString(); let markdown_preview = document.getElementById('current-markdown-preview') as MarkdownPreview; if (markdown_preview !== null) { markdown_preview.document = markdown; return; } markdown_preview = document.createElement('markdown-preview') as MarkdownPreview; markdown_preview.id = 'current-markdown-preview'; if (font_size !== '') { markdown_preview.fontSize = font_size; } if (!isGitHubStyle) { markdown_preview.isGithubStyle = false; } markdown_preview.exts = exts; markdown_preview.openMarkdownDoc = openMarkdownDoc; markdown_preview.onDocumentUpdated = () => getLintArea().showLintResult(); markdown_preview.onSanitizationError = (message, reason) => { console.log(message, reason); getLintArea().sanitize_error = { header: message, body: reason, }; }; setChildToViewerWrapper(markdown_preview); // Clear sanitization error before parsing markdown doc to detect HTML is broken getLintArea().sanitize_error = null; // Parse is run here markdown_preview.document = markdown; }); // Note: // This is a workaround to show linter result lazily. const lint = getLintArea(); lint.already_previewed = false; lint.messages = undefined; } function renderHtmlPreview(file: string) { let html_preview = document.getElementById('current-html-preview') as HTMLIFrameElement; if (html_preview !== null) { html_preview.src = 'file://' + file; return; } html_preview = document.createElement('iframe'); // html_preview = document.createElement('webview'); html_preview.id = 'current-html-preview'; html_preview.className = 'current-html-preview'; html_preview.onload = function(_) { // Note: // Adjust html_preview.setAttribute('height', html_preview.contentWindow.document.body.scrollHeight + 'px'); }; html_preview.setAttribute('seamless', ''); html_preview.setAttribute('sandbox', 'allow-same-origin allow-top-navigation allow-forms allow-scripts'); html_preview.setAttribute('height', window.innerHeight + 'px'); html_preview.src = 'file://' + file; // XXX: Escape double " and & setChildToViewerWrapper(html_preview); } function getDialogDefaultPath() { try { const stats = fs.lstatSync(watching_path); if (stats.isDirectory()) { return watching_path; } return path.dirname(watching_path); } catch (e) { // Note: Path not found return ''; } } function prepareMarkdownStyle(markdown_config: { css_path: string; code_theme: string }) { const { css_path, code_theme } = markdown_config; const markdown_css_link = document.createElement('link'); markdown_css_link.rel = 'stylesheet'; markdown_css_link.href = css_path; document.head.appendChild(markdown_css_link); if (code_theme === '') { return; } const code_theme_css_link = document.createElement('link'); code_theme_css_link.rel = 'stylesheet'; code_theme_css_link.href = `../../node_modules/highlight.js/styles/${code_theme}.css`; document.head.appendChild(code_theme_css_link); if (code_theme !== 'github' && css_path.endsWith('/github-markdown.css')) { console.warn('github-markdown.css overrides background color of code block.'); } } function reloadPreview() { if (document.getElementById('current-markdown-preview') !== null) { renderMarkdownPreview(watching_path); } else if (document.getElementById('current-html-preview') !== null) { renderHtmlPreview(watching_path); } else { // Did not preview yet return; } // Finally start animation document.getElementById('reload-button').classList.add('rotate'); } function shouldWatch(file: string) { const ext = path.extname(file).substr(1); for (const kind of Object.keys(config.file_ext)) { const exts = config.file_ext[kind]; if (exts.indexOf(ext) !== -1) { return true; } } return false; } (function() { const lint = getLintArea(); if (config.voice.enabled) { lint.voice_src = config.voice.source; } if (config.hide_title_bar) { lint.enable_inset = config.hide_title_bar; } prepareMarkdownStyle(config.markdown); function chooseFileOrDirWithDialog() { const filters = [ { name: 'Markdown', extensions: config.file_ext.markdown, }, { name: 'HTML', extensions: config.file_ext.html, }, ]; const properties = ['openFile'] as ('openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory')[]; if (on_darwin) { // Note: // On Windows and Linux an open dialog can not be both a file selector // and a directory selector, so if you set properties to // ['openFile', 'openDirectory'] on these platforms, a directory // selector will be shown. properties.push('openDirectory'); } const paths = remote.dialog.showOpenDialog({ title: 'Choose file or directory to watch', defaultPath: getDialogDefaultPath(), filters, properties, }); if (!paths || paths.length === 0) { return ''; } return paths[0]; } ipc.on('shiba:notify-content-updated', (_: any, kind: string, file: string) => { const button = document.getElementById('reload-button'); button.classList.add('rotate'); const base = document.querySelector('base'); base.setAttribute('href', 'file://' + path.dirname(file) + path.sep); switch (kind) { case 'markdown': { renderMarkdownPreview(file); break; } case 'html': { renderHtmlPreview(file); break; } default: // Do nothing break; } }); ipc.on('shiba:notify-linter-result', (_: any, messages: LintMessage[]) => { lint.messages = messages; const button = document.getElementById('lint-button'); if (messages.length === 0) { button.style.color = '#d99e5f'; } else { button.style.color = '#ce3c4a'; } }); ipc.on('return-lint-url', (_: any, url: string) => { lint.lint_url = url; }); onPathButtonPushed = function() { const chosen = chooseFileOrDirWithDialog(); if (chosen === '') { return; } watching_path = chosen; document.title = make_title(watching_path); ipc.send('shiba:notify-path', watching_path); }; if (watching_path === '') { onPathButtonPushed(); } else { ipc.send('shiba:notify-path', watching_path); document.title = make_title(watching_path); } const searcher = document.getElementById('builtin-page-searcher') as BuiltinSearch; onSearchButtonPushed = function() { searcher.toggle(); }; const toc = document.getElementById('table-of-contents') as TOCComponent; onTOCButtonPushed = function() { const preview = document.getElementById('current-markdown-preview') as MarkdownPreview; if (preview === null) { // TODO: Error handling return; } toc.toggle(preview.currentOutline); }; toc.scrollCallback = function(h: Heading) { const preview = document.getElementById('current-markdown-preview') as MarkdownPreview; if (preview !== null) { preview.scrollToHeading(getScroller(), h); } }; const cancel_event = function(e: Event) { e.preventDefault(); }; document.body.addEventListener('dragenter', cancel_event); document.body.addEventListener('dragover', cancel_event); document.body.addEventListener('drop', event => { event.preventDefault(); const files = event.dataTransfer.files; if (files.length === 0) { return; } const p: string = (files[0] as any).path; if (!p) { console.log('Failed to get the path of dropped file'); return; } if (!shouldWatch(p)) { console.log(`Unknown kind of file (checking file extensions), iginored: ${p}`); return; } watching_path = p; ipc.send('shiba:notify-path', p); document.title = make_title(p); }); const chooser: PawFilechooser = document.querySelector('paw-filechooser'); chooser.onFileChosen = (file: string) => { watching_path = file; ipc.send('shiba:notify-path', file); document.title = make_title(file); }; const reload_button = document.getElementById('reload-button'); reload_button.onclick = () => reloadPreview(); reload_button.classList.add('animated'); const reload_anime_listener = () => { reload_button.classList.remove('rotate'); }; reload_button.addEventListener('animationend', reload_anime_listener); if (!config.drawer.responsive) { const drawer: any = document.getElementById('main-drawer'); drawer.forceNarrow = true; } const menu = document.getElementById('menu'); if (!config.menu.visible) { menu.style.display = 'none'; } else if (config.hide_title_bar && on_darwin) { const spacer = document.getElementById('inset-spacer'); spacer.style.height = '25px'; // Note: // Tweak width of menu bar. // Width of traffic lights gets wider when a title bar is hidden. menu.style.width = '80px'; } const receiver = new Keyboard.Receiver(config.shortcuts); receiver.on('Lint', () => getMainDrawerPanel().togglePanel()); receiver.on('PageUp', () => scrollContentBy(0, -window.innerHeight / 2)); receiver.on('PageDown', () => scrollContentBy(0, window.innerHeight / 2)); receiver.on('PageLeft', () => scrollContentBy(-window.innerHeight / 2, 0)); receiver.on('PageRight', () => scrollContentBy(window.innerHeight / 2, 0)); receiver.on('ChangePath', () => onPathButtonPushed()); receiver.on('QuitApp', () => remote.app.quit()); receiver.on('PageTop', () => { const scroller = getScroller(); if (scroller) { scroller.scrollTop = 0; } }); receiver.on('PageBottom', () => { const scroller = getScroller(); if (scroller) { scroller.scrollTop = scroller.scrollHeight; } }); receiver.on('DevTools', function() { this.bw = this.bw || remote.BrowserWindow; this.bw.getFocusedWindow().openDevTools({ detach: true }); }); receiver.on('Reload', () => reloadPreview()); receiver.on('Print', () => remote.getCurrentWindow().webContents.print()); receiver.on('Search', () => onSearchButtonPushed()); receiver.on('Outline', () => onTOCButtonPushed()); searcher.onMount = () => { receiver.enabled = false; }; searcher.onUnmount = () => { receiver.enabled = true; }; toc.onMount = () => { receiver.enabled = false; }; toc.onUnmount = () => { receiver.enabled = true; }; ipc.on('shiba:choose-file', () => onPathButtonPushed()); ipc.on('shiba:lint', () => getMainDrawerPanel().togglePanel()); ipc.on('shiba:outline', () => onTOCButtonPushed()); ipc.on('shiba:search', () => onSearchButtonPushed()); ipc.on('shiba:reload', () => reloadPreview()); const user_css_path: string = path.join(config._config_dir_path, 'user.css'); fs.access(user_css_path, err => { const exists = !err; if (!exists) { return; } const link = document.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'file://' + user_css_path; document.head.appendChild(link); }); })();
the_stack
import { ObservablePoint, Point } from '@pixi/math'; import { expect } from 'chai'; import '@pixi/math-extras'; describe('Point', function () { describe('add', function () { it('should add component-wise', function () { // Point const a = new Point(1, 2); const b = new Point(3, 4); const c = a.add(b); expect(c.x).to.equal(4); expect(c.y).to.equal(6); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const ob = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.add(ob); expect(oc.x).to.equal(4); expect(oc.y).to.equal(6); }); it('should return the same reference given', function () { // Point const a = new Point(1, 2); const b = new Point(3, 4); const c = a.add(b, a); expect(c).to.equal(a); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const ob = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.add(ob, oa); expect(oc).to.equal(oa); }); it('can output into any IPointData given', function () { // Point const a = new Point(1, 2); const b = new Point(3, 4); const c = a.add(b, { x: 0, y: 0 }); expect(c.x).to.equal(4); expect(c.y).to.equal(6); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const ob = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.add(ob, { x: 0, y: 0 }); expect(oc.x).to.equal(4); expect(oc.y).to.equal(6); }); it('can take any IPointData as other input', function () { // Point const a = new Point(1, 2); const c = a.add({ x: 3, y: 4 }); expect(c.x).to.equal(4); expect(c.y).to.equal(6); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const oc = oa.add({ x: 3, y: 4 }); expect(oc.x).to.equal(4); expect(oc.y).to.equal(6); }); }); describe('subtract', function () { it('should subtract component-wise', function () { // Point const a = new Point(1, 2); const b = new Point(3, 4); const c = a.subtract(b); expect(c.x).to.equal(-2); expect(c.y).to.equal(-2); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const ob = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.subtract(ob); expect(oc.x).to.equal(-2); expect(oc.y).to.equal(-2); }); it('should return the same reference given', function () { // Point const a = new Point(1, 2); const b = new Point(3, 4); const c = a.subtract(b, a); expect(c).to.equal(a); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const ob = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.subtract(ob, oa); expect(oc).to.equal(oa); }); it('can output into any IPointData given', function () { // Point const a = new Point(1, 2); const b = new Point(3, 4); const c = a.subtract(b, { x: 0, y: 0 }); expect(c.x).to.equal(-2); expect(c.y).to.equal(-2); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const ob = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.subtract(ob, { x: 0, y: 0 }); expect(oc.x).to.equal(-2); expect(oc.y).to.equal(-2); }); it('can take any IPointData as other input', function () { // Point const a = new Point(1, 2); const c = a.subtract({ x: 3, y: 4 }); expect(c.x).to.equal(-2); expect(c.y).to.equal(-2); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const oc = oa.subtract({ x: 3, y: 4 }); expect(oc.x).to.equal(-2); expect(oc.y).to.equal(-2); }); }); describe('multiply', function () { it('should multiply component-wise', function () { // Point const a = new Point(1, 2); const b = new Point(3, 4); const c = a.multiply(b); expect(c.x).to.equal(3); expect(c.y).to.equal(8); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const ob = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.multiply(ob); expect(oc.x).to.equal(3); expect(oc.y).to.equal(8); }); it('should return the same reference given', function () { // Point const a = new Point(1, 2); const b = new Point(3, 4); const c = a.multiply(b, a); expect(c).to.equal(a); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const ob = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.multiply(ob, oa); expect(oc).to.equal(oa); }); it('can output into any IPointData given', function () { // Point const a = new Point(1, 2); const b = new Point(3, 4); const c = a.multiply(b, { x: 0, y: 0 }); expect(c.x).to.equal(3); expect(c.y).to.equal(8); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const ob = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.multiply(ob, { x: 0, y: 0 }); expect(oc.x).to.equal(3); expect(oc.y).to.equal(8); }); it('can take any IPointData as other input', function () { // Point const a = new Point(1, 2); const c = a.multiply({ x: 3, y: 4 }); expect(c.x).to.equal(3); expect(c.y).to.equal(8); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const oc = oa.multiply({ x: 3, y: 4 }); expect(oc.x).to.equal(3); expect(oc.y).to.equal(8); }); }); describe('multiplyScalar', function () { it('should multiply both components by a scalar', function () { // Point const a = new Point(1, 2); const c = a.multiplyScalar(3); expect(c.x).to.equal(3); expect(c.y).to.equal(6); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const oc = oa.multiplyScalar(3); expect(oc.x).to.equal(3); expect(oc.y).to.equal(6); }); it('should return the same reference given', function () { // Point const a = new Point(1, 2); const c = a.multiplyScalar(3, a); expect(c).to.equal(a); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const oc = oa.multiplyScalar(3, oa); expect(oc).to.equal(oa); }); it('can output into any IPointData given', function () { // Point const a = new Point(1, 2); const c = a.multiplyScalar(3, { x: 0, y: 0 }); expect(c.x).to.equal(3); expect(c.y).to.equal(6); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const oc = oa.multiplyScalar(3, { x: 0, y: 0 }); expect(oc.x).to.equal(3); expect(oc.y).to.equal(6); }); }); describe('dot', function () { it('should multiply component-wise and then add both components', function () { // Point const a = new Point(1, 2); const b = new Point(3, 4); const c = a.dot(b); expect(c).to.equal(11); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const ob = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.dot(ob); expect(oc).to.equal(11); }); }); describe('cross', function () { it('should return the magnitude of the result of a cross product', function () { // Point const a = new Point(1, 2); const b = new Point(3, 4); const c = a.cross(b); expect(c).to.equal(-2); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const ob = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.cross(ob); expect(oc).to.equal(-2); }); }); describe('normalize', function () { it('magnitude should be 1', function () { // Point const a = new Point(3, 4); const c = a.normalize(); const magnitude = Math.sqrt((c.x * c.x) + (c.y * c.y)); expect(magnitude).to.be.closeTo(1, 0.001); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.normalize(); const omagnitude = Math.sqrt((oc.x * oc.x) + (oc.y * oc.y)); expect(omagnitude).to.be.closeTo(1, 0.001); }); it('should return the same reference given', function () { // Point const a = new Point(3, 4); const c = a.normalize(a); expect(c).to.equal(a); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.normalize(oa); expect(oc).to.equal(oa); }); it('can output into any IPointData given', function () { // Point const a = new Point(1, 2); const c = a.normalize({ x: 0, y: 0 }); const magnitude = Math.sqrt((c.x * c.x) + (c.y * c.y)); expect(magnitude).to.be.closeTo(1, 0.001); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const oc = oa.normalize({ x: 0, y: 0 }); const omagnitude = Math.sqrt((oc.x * oc.x) + (oc.y * oc.y)); expect(omagnitude).to.be.closeTo(1, 0.001); }); }); describe('magnitude', function () { it('should return the square root of the sum of the squares of each component', function () { const expectedMagnitude = Math.sqrt((3 * 3) + (4 * 4)); // Point const a = new Point(3, 4); const c = a.magnitude(); expect(c).to.be.closeTo(expectedMagnitude, 0.001); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.magnitude(); expect(oc).to.be.closeTo(expectedMagnitude, 0.001); }); it('should return the sum of the squares of each component', function () { const expectedMagnitudeSquared = (3 * 3) + (4 * 4); // Point const a = new Point(3, 4); const c = a.magnitudeSquared(); expect(c).to.be.closeTo(expectedMagnitudeSquared, 0.001); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.magnitudeSquared(); expect(oc).to.equal(expectedMagnitudeSquared); }); }); describe('project', function () { it('should return the vector projection of a vector onto another nonzero vector', function () { // Point const a = new Point(1, 2); const b = new Point(3, 4); const c = a.project(b); expect(c.x).to.be.closeTo(33 / 25, 0.001); expect(c.y).to.be.closeTo(44 / 25, 0.001); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const ob = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.project(ob); expect(oc.x).to.be.closeTo(33 / 25, 0.001); expect(oc.y).to.be.closeTo(44 / 25, 0.001); }); it('should return the same reference given', function () { // Point const a = new Point(1, 2); const b = new Point(3, 4); const c = a.project(b, a); expect(c).to.equal(a); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const ob = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.project(ob, oa); expect(oc).to.equal(oa); }); it('can output into any IPointData given', function () { // Point const a = new Point(1, 2); const b = new Point(3, 4); const c = a.project(b, { x: 0, y: 0 }); expect(c.x).to.be.closeTo(33 / 25, 0.001); expect(c.y).to.be.closeTo(44 / 25, 0.001); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const ob = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.project(ob, { x: 0, y: 0 }); expect(oc.x).to.be.closeTo(33 / 25, 0.001); expect(oc.y).to.be.closeTo(44 / 25, 0.001); }); it('can take any IPointData as other input', function () { // Point const a = new Point(1, 2); const c = a.project({ x: 3, y: 4 }); expect(c.x).to.be.closeTo(33 / 25, 0.001); expect(c.y).to.be.closeTo(44 / 25, 0.001); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const oc = oa.project({ x: 3, y: 4 }); expect(oc.x).to.be.closeTo(33 / 25, 0.001); expect(oc.y).to.be.closeTo(44 / 25, 0.001); }); }); describe('reflect', function () { it('should return the specular reflect vector', function () { // Point const a = new Point(1, 2); const b = new Point(3, 4); const c = a.reflect(b); expect(c.x).to.equal(-65); expect(c.y).to.equal(-86); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const ob = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.reflect(ob); expect(oc.x).to.equal(-65); expect(oc.y).to.equal(-86); }); it('should return the same reference given', function () { // Point const a = new Point(1, 2); const b = new Point(3, 4); const c = a.reflect(b, a); expect(c).to.equal(a); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const ob = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.reflect(ob, oa); expect(oc).to.equal(oa); }); it('can output into any IPointData given', function () { // Point const a = new Point(1, 2); const b = new Point(3, 4); const c = a.reflect(b, { x: 0, y: 0 }); expect(c.x).to.equal(-65); expect(c.y).to.equal(-86); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const ob = new ObservablePoint(() => { /* empty */ }, {}, 3, 4); const oc = oa.reflect(ob, { x: 0, y: 0 }); expect(oc.x).to.equal(-65); expect(oc.y).to.equal(-86); }); it('can take any IPointData as other input', function () { // Point const a = new Point(1, 2); const c = a.reflect({ x: 3, y: 4 }); expect(c.x).to.equal(-65); expect(c.y).to.equal(-86); // ObservablePoint const oa = new ObservablePoint(() => { /* empty */ }, {}, 1, 2); const oc = oa.reflect({ x: 3, y: 4 }); expect(oc.x).to.equal(-65); expect(oc.y).to.equal(-86); }); }); });
the_stack
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { intlShape } from '../../lib/vulcan-i18n'; // HACK: withRouter should be removed or turned into withLocation, but // FormWrapper passes props around in bulk, and Form has a bunch of prop-name // handling by string gluing, so it's hard to be sure this is safe. // eslint-disable-next-line no-restricted-imports import { withRouter } from 'react-router'; import { gql } from '@apollo/client'; import { graphql, withApollo } from '@apollo/client/react/hoc'; import compose from 'lodash/flowRight'; import { Components, registerComponent, getFragment } from '../../lib/vulcan-lib'; import { capitalize } from '../../lib/vulcan-lib/utils'; import { withCreate } from '../../lib/crud/withCreate'; import { withSingle } from '../../lib/crud/withSingle'; import { withDelete } from '../../lib/crud/withDelete'; import { withUpdate } from '../../lib/crud/withUpdate'; import { getSchema } from '../../lib/utils/getSchema'; import withUser from '../common/withUser'; import { getReadableFields, getCreateableFields, getUpdateableFields } from '../../lib/vulcan-forms/schema_utils'; import withCollectionProps from './withCollectionProps'; import { callbackProps } from './propTypes'; import * as _ from 'underscore'; const intlSuffix = '_intl'; /** * Note: Only use this through WrappedSmartForm */ class FormWrapper extends PureComponent<any> { FormComponent: any constructor(props) { super(props); // instantiate the wrapped component in constructor, not in render // see https://reactjs.org/docs/higher-order-components.html#dont-use-hocs-inside-the-render-method this.FormComponent = this.getComponent(); } // return the current schema based on either the schema or collection prop getSchema() { return this.props.schema ? this.props.schema : getSchema(this.props.collection); } // if a document is being passed, this is an edit form getFormType() { return this.props.documentId || this.props.slug ? 'edit' : 'new'; } // get fragment used to decide what data to load from the server to populate the form, // as well as what data to ask for as return value for the mutation getFragments() { const prefix = `${this.props.collectionName}${capitalize( this.getFormType() )}`; const fragmentName = `${prefix}FormFragment`; const fields = this.props.fields; const readableFields = getReadableFields(this.getSchema()); const createableFields = getCreateableFields(this.getSchema()); const updatetableFields = getUpdateableFields(this.getSchema()); // get all editable/insertable fields (depending on current form type) let queryFields = this.getFormType() === 'new' ? createableFields : updatetableFields; // for the mutations's return value, also get non-editable but viewable fields (such as createdAt, userId, etc.) let mutationFields = this.getFormType() === 'new' ? _.unique(createableFields.concat(readableFields)) : _.unique(createableFields.concat(updatetableFields)); // if "fields" prop is specified, restrict list of fields to it if (typeof fields !== 'undefined' && fields.length > 0) { // add "_intl" suffix to all fields in case some of them are intl fields const fieldsWithIntlSuffix = fields.map(field => `${field}${intlSuffix}`); const allFields = [...fields, ...fieldsWithIntlSuffix]; queryFields = _.intersection(queryFields, allFields); mutationFields = _.intersection(mutationFields, allFields); } // add "addFields" prop contents to list of fields if (this.props.addFields && this.props.addFields.length) { queryFields = queryFields.concat(this.props.addFields); mutationFields = mutationFields.concat(this.props.addFields); } const convertFields = field => { return field.slice(-5) === intlSuffix ? `${field}{ locale value }` : field; }; // generate query fragment based on the fields that can be edited. Note: always add _id. const generatedQueryFragment = gql` fragment ${fragmentName} on ${this.props.typeName} { _id ${queryFields.map(convertFields).join('\n')} } `; // generate mutation fragment based on the fields that can be edited and/or viewed. Note: always add _id. const generatedMutationFragment = gql` fragment ${fragmentName} on ${this.props.typeName} { _id ${mutationFields.map(convertFields).join('\n')} } `; // default to generated fragments let queryFragment = generatedQueryFragment; let mutationFragment = generatedMutationFragment; // if queryFragment or mutationFragment props are specified, accept either fragment object or fragment string if (this.props.queryFragment) { queryFragment = typeof this.props.queryFragment === 'string' ? gql` ${this.props.queryFragment} ` : this.props.queryFragment; } if (this.props.mutationFragment) { mutationFragment = typeof this.props.mutationFragment === 'string' ? gql` ${this.props.mutationFragment} ` : this.props.mutationFragment; } // same with queryFragmentName and mutationFragmentName if (this.props.queryFragmentName) { queryFragment = getFragment(this.props.queryFragmentName); } if (this.props.mutationFragmentName) { mutationFragment = getFragment(this.props.mutationFragmentName); } // if any field specifies extra queries, add them const extraQueries = _.compact( queryFields.map(fieldName => { const field = this.getSchema()[fieldName]; return field.query; }) ); // get query & mutation fragments from props or else default to same as generatedFragment return { queryFragment, mutationFragment, extraQueries }; } getComponent() { let WrappedComponent; const prefix = `${this.props.collectionName}${capitalize( this.getFormType() )}`; const { queryFragment, mutationFragment, extraQueries } = this.getFragments(); // LESSWRONG: ADDED extraVariables option const { extraVariables = {} } = this.props // props to pass on to child component (i.e. <Form />) const childProps = { formType: this.getFormType(), schema: this.getSchema() }; // options for withSingle HoC const queryOptions: any = { queryName: `${prefix}FormQuery`, collection: this.props.collection, fragment: queryFragment, extraQueries, fetchPolicy: 'network-only', // we always want to load a fresh copy of the document pollInterval: 0 // no polling, only load data once }; // options for withCreate, withUpdate, and withDelete HoCs const mutationOptions = { collectionName: this.props.collection.collectionName, fragment: mutationFragment, extraVariables }; // create a stateless loader component, // displays the loading state if needed, and passes on loading and document/data const Loader = props => { const { document, loading } = props; return loading ? ( <Components.Loading /> ) : ( <Components.Form document={document} loading={loading} {...childProps} {...props} /> ); }; Loader.displayName = 'withLoader(Form)'; // if this is an edit from, load the necessary data using the withSingle HoC if (this.getFormType() === 'edit') { WrappedComponent = compose( withSingle(queryOptions), withUpdate(mutationOptions), withDelete(mutationOptions) // @ts-ignore )(Loader); return ( <WrappedComponent selector={{ documentId: this.props.documentId, slug: this.props.slug }} /> ); } else { if (extraQueries && extraQueries.length) { const extraQueriesHoC = graphql( gql` query formNewExtraQuery { ${extraQueries} }`, { alias: 'withExtraQueries', props: returnedProps => { const { /* ownProps, */ data } = returnedProps; const props = { loading: data!.loading, data }; return props; } } ); WrappedComponent = compose( extraQueriesHoC, withCreate(mutationOptions) // @ts-ignore )(Loader); } else { WrappedComponent = compose(withCreate(mutationOptions))(Components.Form); } return <WrappedComponent {...childProps} />; } } render() { const component = this.FormComponent; const componentWithParentProps = React.cloneElement(component, this.props); return componentWithParentProps; } } (FormWrapper as any).propTypes = { // main options collection: PropTypes.object.isRequired, collectionName: PropTypes.string.isRequired, typeName: PropTypes.string.isRequired, documentId: PropTypes.string, // if a document is passed, this will be an edit form schema: PropTypes.object, // usually not needed queryFragment: PropTypes.object, queryFragmentName: PropTypes.string, mutationFragment: PropTypes.object, mutationFragmentName: PropTypes.string, // graphQL newMutation: PropTypes.func, // the new mutation removeMutation: PropTypes.func, // the remove mutation // form prefilledProps: PropTypes.object, layout: PropTypes.string, fields: PropTypes.arrayOf(PropTypes.string), hideFields: PropTypes.arrayOf(PropTypes.string), addFields: PropTypes.arrayOf(PropTypes.string), showRemove: PropTypes.bool, submitLabel: PropTypes.node, cancelLabel: PropTypes.node, revertLabel: PropTypes.node, repeatErrors: PropTypes.bool, warnUnsavedChanges: PropTypes.bool, // callbacks ...callbackProps, currentUser: PropTypes.object, client: PropTypes.object }; (FormWrapper as any).defaultProps = { layout: 'horizontal' }; (FormWrapper as any).contextTypes = { closeCallback: PropTypes.func, intl: intlShape }; const FormWrapperComponent = registerComponent('FormWrapper', FormWrapper, { hocs: [withUser, withApollo, withRouter, withCollectionProps] }); declare global { interface ComponentTypes { FormWrapper: typeof FormWrapperComponent } }
the_stack
import HDKey from 'hdkey'; import { pubToAddress } from 'ethereumjs-util'; import { mocked } from 'ts-jest/utils'; import { GenericWallet } from '../src'; import { safeIntegerValidator, hexSequenceValidator, addressValidator, } from '../src/validators'; import { addressNormalizer, hexSequenceNormalizer } from '../src/normalizers'; import { CHAIN_IDS } from '../src/constants'; jest.mock('hdkey'); jest.mock('../src/validators'); jest.mock('../src/normalizers'); const mockedAddressNormalizer = mocked(addressNormalizer); const mockedHexSequenceNormalizer = mocked(hexSequenceNormalizer); const mockedPubToAddress = mocked(pubToAddress); /* * Common values */ const addressGeneratedFromPublicKey = 'mocked-hex-address'; const rootPublicKey = 'mocked-root-public-key'; const rootChainCode = 'mocked-root-chain-code'; const rootDerivationPath = 'mocked-root-derivation-path'; const mockedChainId = 123123; const addressCount = 10; const addressCountSingle = 1; const mockedArguments = { publicKey: rootPublicKey, chainCode: rootChainCode, rootDerivationPath, addressCount, chainId: mockedChainId, }; describe('`Core` Module', () => { afterEach(() => { mockedAddressNormalizer.mockClear(); mockedHexSequenceNormalizer.mockClear(); mockedPubToAddress.mockClear(); }); describe('`GenericWallet` class', () => { test('Creates a new wallet instance', () => { // @ts-ignore const genericWallet = new GenericWallet(mockedArguments); expect(genericWallet).toBeInstanceOf(GenericWallet); }); test('Derives the address derivation path from the root path', () => { // @ts-ignore new GenericWallet(mockedArguments); expect(HDKey).toHaveBeenCalled(); }); test('Adapts to differnt versions of the derivation path', async () => { const firstDerivationPathIndex = `${rootDerivationPath}/0`; /* * A "trezor"-default derivation path, that ends with a digit. * Eg: m/44'/60'/0'/0 */ // @ts-ignore const derivationPathWithDigitWallet = new GenericWallet(mockedArguments); const derivationPathWithDigit = await derivationPathWithDigitWallet.getDerivationPath(); expect(derivationPathWithDigit).toEqual(firstDerivationPathIndex); /* * A "ledger"-default derivation path, that ends with a slash. * Eg: m/44'/60'/0'/ */ // @ts-ignore const derivationPathWithSpliterWallet = new GenericWallet({ ...mockedArguments, rootDerivationPath: `${rootDerivationPath}/`, }); const derivationPathWithSplitter = await derivationPathWithSpliterWallet.getDerivationPath(); expect(derivationPathWithSplitter).toEqual(firstDerivationPathIndex); }); test('Generates the address(es) from the public key(s)', () => { // @ts-ignore new GenericWallet(mockedArguments); expect(pubToAddress).toHaveBeenCalled(); }); test('The Wallet Object has the required (correct) props', async () => { // @ts-ignore const genericWallet = new GenericWallet(mockedArguments); /* * Address */ expect(genericWallet).toHaveProperty('address'); /* * Public Key * We have to call it directly since Jest's `toHaveProperty` doesn't play well with getters */ await expect(genericWallet.getPublicKey()).resolves.toEqual( expect.any(String), ); /* * Derivation Path * We have to call it directly since Jest's `toHaveProperty` doesn't play well with getters */ await expect(genericWallet.getDerivationPath()).resolves.toEqual( `${rootDerivationPath}/0`, ); /* * Chain Id */ expect(genericWallet).toHaveProperty('chainId'); }); test('The Wallet Object sets the chain Id correctly', () => { const locallyMockedChainId = 222; // @ts-ignore const genericWallet = new GenericWallet({ ...mockedArguments, chainId: locallyMockedChainId, }); /* * Address */ expect(genericWallet).toHaveProperty('chainId', locallyMockedChainId); }); test('The Wallet Object falls back to the default chainId', () => { // @ts-ignore const genericWallet = new GenericWallet({ publicKey: rootPublicKey, chainCode: rootChainCode, rootDerivationPath, addressCount, }); /* * Address */ expect(genericWallet).toHaveProperty('chainId', CHAIN_IDS.HOMESTEAD); }); test('Validates values used to instantiate', async () => { // @ts-ignore new GenericWallet({ ...mockedArguments, addressCount: addressCountSingle, }); /* * Validates the address count */ expect(safeIntegerValidator).toHaveBeenCalled(); expect(safeIntegerValidator).toHaveBeenCalledWith(addressCountSingle); /* * Validates the public key and chain code */ expect(hexSequenceValidator).toHaveBeenCalled(); expect(hexSequenceValidator).toHaveBeenCalledWith(rootPublicKey); expect(hexSequenceValidator).toHaveBeenCalledWith(rootChainCode); /* * Validates the hex address that was generated from the public key */ expect(addressValidator).toHaveBeenCalled(); expect(addressValidator).toHaveBeenCalledWith( /* * 0, since it's the first address, this comes from the mocked HDKey method. * But truth be told, this test is kind of useless... */ `${addressGeneratedFromPublicKey}-0`, ); }); test('Normalizes values used to instantiate', async () => { // @ts-ignore new GenericWallet(mockedArguments); /* * Normalizes all addresses that are derived from the public keys */ expect(addressNormalizer).toHaveBeenCalled(); expect(addressNormalizer).toHaveBeenCalledTimes(addressCount); /* * Normalizes all publicKey that are derived from the root one */ expect(hexSequenceNormalizer).toHaveBeenCalled(); expect(hexSequenceNormalizer).toHaveBeenCalledTimes(addressCount); }); test('Changes the default address', async () => { // @ts-ignore const genericWallet = new GenericWallet(mockedArguments); /* * Should have the `setDefaultAddress` internal method set on the instance */ expect(genericWallet).toHaveProperty('setDefaultAddress'); /* * By default the first (index 0) address and public key * are selected as defaults */ expect(genericWallet).toHaveProperty( 'address', `${addressGeneratedFromPublicKey}-0`, ); /* * Private key is a `hex` string */ const intialPublicKey = await genericWallet.getPublicKey(); expect(Buffer.from(intialPublicKey, 'hex').toString()).toEqual( `${addressGeneratedFromPublicKey}-0`, ); /* * Change the default account */ const newAddressIndex = 2; await expect( genericWallet.setDefaultAddress(newAddressIndex), ).resolves.toBeTruthy(); /* * Now the address should reflec the new index */ expect(genericWallet).toHaveProperty( 'address', `${addressGeneratedFromPublicKey}-${newAddressIndex}`, ); /* * As well as as the private key */ const newPublicKey = await genericWallet.getPublicKey(); expect(Buffer.from(newPublicKey, 'hex').toString()).toEqual( `${addressGeneratedFromPublicKey}-${newAddressIndex}`, ); }); test('Changes the default address with no arguments provided', async () => { // @ts-ignore const genericWallet = new GenericWallet(mockedArguments); /* * Set the initial default account to something later down the array index */ const initialAddressIndex = 4; await expect( genericWallet.setDefaultAddress(initialAddressIndex), ).resolves.toBeTruthy(); expect(genericWallet).toHaveProperty( 'address', `${addressGeneratedFromPublicKey}-${initialAddressIndex}`, ); /* * Change the default account with no arguments provided, so it defaults * To the the initial values */ const defaultAddressIndex = 0; await expect(genericWallet.setDefaultAddress()).resolves.toBeTruthy(); /* * Now the address should reflec the new index */ expect(genericWallet).toHaveProperty( 'address', `${addressGeneratedFromPublicKey}-${defaultAddressIndex}`, ); }); /* * For some reason prettier always suggests a way to fix this that would * violate the 80 max-len rule. Wierd */ test('Cannot change the default address (single address opened)', async () => { // @ts-ignore const genericWallet = new GenericWallet({ ...mockedArguments, addressCount: addressCountSingle, }); await expect(genericWallet.setDefaultAddress(2)).rejects.toThrow(); }); test('Has the `otherAddresses` prop if multiple were instantiated', async () => { // @ts-ignore const genericWallet = new GenericWallet(mockedArguments); expect(genericWallet).toHaveProperty('otherAddresses'); expect(genericWallet.otherAddresses).toHaveLength(addressCount); }); test('Opens the first 10 wallet addresses by default', () => { // @ts-ignore const genericWallet = new GenericWallet({ publicKey: rootPublicKey, chainCode: rootChainCode, rootDerivationPath, chainId: mockedChainId, }); /* * If no value was passed to the addressCount, it defaults to 10 * * This means the otherAddreses prop is available and contains the first * 10 derived addresses */ expect(genericWallet).toHaveProperty('otherAddresses'); expect(genericWallet.otherAddresses).toHaveLength(addressCount); }); test('Falls back to 1 if address count was set to falsy value', () => { // @ts-ignore const genericWallet = new GenericWallet({ ...mockedArguments, addressCount: NaN, }); /* * If a falsy value was passed to the addressCount, it bypasses the default, * but it should be caught by the fallback inside the array map (and falls * back to 1) * * This means the otherAddreses prop will not be available, but we still have * one (the first) addres opened. */ expect(genericWallet).toHaveProperty('otherAddresses', []); expect(genericWallet).toHaveProperty( 'address', `${addressGeneratedFromPublicKey}-0`, ); }); test('`otherAddresses` prop is empty if only one was instantiated', async () => { // @ts-ignore const genericWallet = new GenericWallet({ ...mockedArguments, addressCount: addressCountSingle, }); expect(genericWallet).toHaveProperty('otherAddresses', []); }); }); });
the_stack
declare module com { export module airbnb { export module lottie { export class BuildConfig extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.BuildConfig>; public static DEBUG: boolean; public static APPLICATION_ID: string; public static BUILD_TYPE: string; public static FLAVOR: string; public static VERSION_CODE: number; public static VERSION_NAME: string; public constructor(); } } } } declare module com { export module airbnb { export module lottie { export class Cancellable extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.Cancellable>; /** * Constructs a new instance of the com.airbnb.lottie.Cancellable interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { cancel(): void; }); public constructor(); public cancel(): void; } } } } declare module com { export module airbnb { export module lottie { export class FontAssetDelegate extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.FontAssetDelegate>; public getFontPath(param0: string): string; public fetchFont(param0: string): globalAndroid.graphics.Typeface; public constructor(); } } } } declare module com { export module airbnb { export module lottie { export class ImageAssetDelegate extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.ImageAssetDelegate>; /** * Constructs a new instance of the com.airbnb.lottie.ImageAssetDelegate interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { fetchBitmap(param0: com.airbnb.lottie.LottieImageAsset): globalAndroid.graphics.Bitmap; }); public constructor(); public fetchBitmap(param0: com.airbnb.lottie.LottieImageAsset): globalAndroid.graphics.Bitmap; } } } } declare module com { export module airbnb { export module lottie { export class L extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.L>; public static DBG: boolean; public static TAG: string; public static endSection(param0: string): number; public static setTraceEnabled(param0: boolean): void; public static beginSection(param0: string): void; public constructor(); } } } } declare module com { export module airbnb { export module lottie { export class LottieAnimationView { public static class: java.lang.Class<com.airbnb.lottie.LottieAnimationView>; public onVisibilityChanged(param0: globalAndroid.view.View, param1: number): void; public enableMergePathsForKitKatAndAbove(param0: boolean): void; public getMinFrame(): number; public updateBitmap(param0: string, param1: globalAndroid.graphics.Bitmap): globalAndroid.graphics.Bitmap; public getMaxFrame(): number; public setAnimationFromJson(param0: string, param1: string): void; public removeAllUpdateListeners(): void; public setImageAssetDelegate(param0: com.airbnb.lottie.ImageAssetDelegate): void; public isAnimating(): boolean; public setMinAndMaxFrame(param0: string): void; public hasMatte(): boolean; public onRestoreInstanceState(param0: globalAndroid.os.Parcelable): void; public removeLottieOnCompositionLoadedListener(param0: com.airbnb.lottie.LottieOnCompositionLoadedListener): boolean; public reverseAnimationSpeed(): void; public getPerformanceTracker(): com.airbnb.lottie.PerformanceTracker; public setAnimationFromUrl(param0: string): void; public addLottieOnCompositionLoadedListener(param0: com.airbnb.lottie.LottieOnCompositionLoadedListener): boolean; public setAnimation(param0: java.io.InputStream, param1: string): void; public hasMasks(): boolean; public getRepeatCount(): number; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet); public isMergePathsEnabledForKitKatAndAbove(): boolean; public removeUpdateListener(param0: globalAndroid.animation.ValueAnimator.AnimatorUpdateListener): void; public setFailureListener(param0: com.airbnb.lottie.LottieListener<java.lang.Throwable>): void; public setImageBitmap(param0: globalAndroid.graphics.Bitmap): void; public getComposition(): com.airbnb.lottie.LottieComposition; public setMinAndMaxFrame(param0: number, param1: number): void; public setMinAndMaxFrame(param0: string, param1: string, param2: boolean): void; public setFallbackResource(param0: number): void; public setComposition(param0: com.airbnb.lottie.LottieComposition): void; public setProgress(param0: number): void; public setRepeatMode(param0: number): void; public addAnimatorListener(param0: globalAndroid.animation.Animator.AnimatorListener): void; public pauseAnimation(): void; public getProgress(): number; public setImageResource(param0: number): void; public onDetachedFromWindow(): void; public setRenderMode(param0: com.airbnb.lottie.RenderMode): void; public setMinFrame(param0: string): void; /** @deprecated */ public setAnimationFromJson(param0: string): void; public setTextDelegate(param0: com.airbnb.lottie.TextDelegate): void; public addValueCallback(param0: com.airbnb.lottie.model.KeyPath, param1: any, param2: com.airbnb.lottie.value.SimpleLottieValueCallback<any>): void; public getScale(): number; public getFrame(): number; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.util.AttributeSet, param2: number); public removeAnimatorListener(param0: globalAndroid.animation.Animator.AnimatorListener): void; public getDuration(): number; public setImageDrawable(param0: globalAndroid.graphics.drawable.Drawable): void; public setAnimation(param0: number): void; public setMinFrame(param0: number): void; public setMaxFrame(param0: string): void; public setScaleType(param0: globalAndroid.widget.ImageView.ScaleType): void; public setMaxProgress(param0: number): void; public getImageAssetsFolder(): string; public setImageAssetsFolder(param0: string): void; public setSafeMode(param0: boolean): void; public constructor(param0: globalAndroid.content.Context); public cancelAnimation(): void; public disableExtraScaleModeInFitXY(): void; public setSpeed(param0: number): void; public setFrame(param0: number): void; public setMinAndMaxProgress(param0: number, param1: number): void; /** @deprecated */ public loop(param0: boolean): void; public addAnimatorUpdateListener(param0: globalAndroid.animation.ValueAnimator.AnimatorUpdateListener): void; public resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath): java.util.List<com.airbnb.lottie.model.KeyPath>; public onSaveInstanceState(): globalAndroid.os.Parcelable; public setAnimation(param0: string): void; public setMaxFrame(param0: number): void; public setScale(param0: number): void; public setMinProgress(param0: number): void; public getRepeatMode(): number; public removeAllAnimatorListeners(): void; public setFontAssetDelegate(param0: com.airbnb.lottie.FontAssetDelegate): void; public removeAllLottieOnCompositionLoadedListener(): void; public setCacheComposition(param0: boolean): void; public buildDrawingCache(param0: boolean): void; public invalidateDrawable(param0: globalAndroid.graphics.drawable.Drawable): void; public addValueCallback(param0: com.airbnb.lottie.model.KeyPath, param1: any, param2: com.airbnb.lottie.value.LottieValueCallback<any>): void; public setPerformanceTrackingEnabled(param0: boolean): void; public setApplyingOpacityToLayersEnabled(param0: boolean): void; public getSpeed(): number; public playAnimation(): void; public resumeAnimation(): void; public setRepeatCount(param0: number): void; public onAttachedToWindow(): void; } export module LottieAnimationView { export class SavedState extends globalAndroid.view.View.BaseSavedState { public static class: java.lang.Class<com.airbnb.lottie.LottieAnimationView.SavedState>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.airbnb.lottie.LottieAnimationView.SavedState>; public describeContents(): number; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; } } } } } declare module com { export module airbnb { export module lottie { export class LottieComposition extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.LottieComposition>; public getDurationFrames(): number; public hasDashPattern(): boolean; public getDuration(): number; public incrementMatteOrMaskCount(param0: number): void; public getImages(): java.util.Map<string,com.airbnb.lottie.LottieImageAsset>; public constructor(); public getMarkers(): java.util.List<com.airbnb.lottie.model.Marker>; public getBounds(): globalAndroid.graphics.Rect; public getPrecomps(param0: string): java.util.List<com.airbnb.lottie.model.layer.Layer>; public getWarnings(): java.util.ArrayList<string>; public setHasDashPattern(param0: boolean): void; public getPerformanceTracker(): com.airbnb.lottie.PerformanceTracker; public init(param0: globalAndroid.graphics.Rect, param1: number, param2: number, param3: number, param4: java.util.List<com.airbnb.lottie.model.layer.Layer>, param5: androidx.collection.LongSparseArray<com.airbnb.lottie.model.layer.Layer>, param6: java.util.Map<string,java.util.List<com.airbnb.lottie.model.layer.Layer>>, param7: java.util.Map<string,com.airbnb.lottie.LottieImageAsset>, param8: androidx.collection.SparseArrayCompat<com.airbnb.lottie.model.FontCharacter>, param9: java.util.Map<string,com.airbnb.lottie.model.Font>, param10: java.util.List<com.airbnb.lottie.model.Marker>): void; public getStartFrame(): number; public getMaskAndMatteCount(): number; public getMarker(param0: string): com.airbnb.lottie.model.Marker; public getLayers(): java.util.List<com.airbnb.lottie.model.layer.Layer>; public getFrameRate(): number; public hasImages(): boolean; public toString(): string; public getCharacters(): androidx.collection.SparseArrayCompat<com.airbnb.lottie.model.FontCharacter>; public getEndFrame(): number; public layerModelForId(param0: number): com.airbnb.lottie.model.layer.Layer; public setPerformanceTrackingEnabled(param0: boolean): void; public getFonts(): java.util.Map<string,com.airbnb.lottie.model.Font>; public addWarning(param0: string): void; } export module LottieComposition { export class Factory extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.LottieComposition.Factory>; /** @deprecated */ public static fromInputStreamSync(param0: java.io.InputStream): com.airbnb.lottie.LottieComposition; /** @deprecated */ public static fromJsonSync(param0: globalAndroid.content.res.Resources, param1: org.json.JSONObject): com.airbnb.lottie.LottieComposition; /** @deprecated */ public static fromInputStreamSync(param0: java.io.InputStream, param1: boolean): com.airbnb.lottie.LottieComposition; /** @deprecated */ public static fromFileSync(param0: globalAndroid.content.Context, param1: string): com.airbnb.lottie.LottieComposition; /** @deprecated */ public static fromJsonString(param0: string, param1: com.airbnb.lottie.OnCompositionLoadedListener): com.airbnb.lottie.Cancellable; /** @deprecated */ public static fromJsonSync(param0: string): com.airbnb.lottie.LottieComposition; /** @deprecated */ public static fromAssetFileName(param0: globalAndroid.content.Context, param1: string, param2: com.airbnb.lottie.OnCompositionLoadedListener): com.airbnb.lottie.Cancellable; /** @deprecated */ public static fromRawFile(param0: globalAndroid.content.Context, param1: number, param2: com.airbnb.lottie.OnCompositionLoadedListener): com.airbnb.lottie.Cancellable; /** @deprecated */ public static fromInputStream(param0: java.io.InputStream, param1: com.airbnb.lottie.OnCompositionLoadedListener): com.airbnb.lottie.Cancellable; /** @deprecated */ public static fromJsonReader(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: com.airbnb.lottie.OnCompositionLoadedListener): com.airbnb.lottie.Cancellable; /** @deprecated */ public static fromJsonSync(param0: com.airbnb.lottie.parser.moshi.JsonReader): com.airbnb.lottie.LottieComposition; } export module Factory { export class ListenerAdapter extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.LottieComposition.Factory.ListenerAdapter>; public cancel(): void; public onResult(param0: any): void; public onResult(param0: com.airbnb.lottie.LottieComposition): void; } } } } } } declare module com { export module airbnb { export module lottie { export class LottieCompositionFactory extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.LottieCompositionFactory>; /** @deprecated */ public static fromJsonSync(param0: org.json.JSONObject, param1: string): com.airbnb.lottie.LottieResult<com.airbnb.lottie.LottieComposition>; /** @deprecated */ public static fromJson(param0: org.json.JSONObject, param1: string): com.airbnb.lottie.LottieTask<com.airbnb.lottie.LottieComposition>; public static fromRawResSync(param0: globalAndroid.content.Context, param1: number, param2: string): com.airbnb.lottie.LottieResult<com.airbnb.lottie.LottieComposition>; public static fromJsonStringSync(param0: string, param1: string): com.airbnb.lottie.LottieResult<com.airbnb.lottie.LottieComposition>; public static fromAssetSync(param0: globalAndroid.content.Context, param1: string): com.airbnb.lottie.LottieResult<com.airbnb.lottie.LottieComposition>; public static fromRawRes(param0: globalAndroid.content.Context, param1: number): com.airbnb.lottie.LottieTask<com.airbnb.lottie.LottieComposition>; public static fromJsonReaderSync(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: string): com.airbnb.lottie.LottieResult<com.airbnb.lottie.LottieComposition>; public static fromAsset(param0: globalAndroid.content.Context, param1: string, param2: string): com.airbnb.lottie.LottieTask<com.airbnb.lottie.LottieComposition>; public static fromRawResSync(param0: globalAndroid.content.Context, param1: number): com.airbnb.lottie.LottieResult<com.airbnb.lottie.LottieComposition>; public static fromAsset(param0: globalAndroid.content.Context, param1: string): com.airbnb.lottie.LottieTask<com.airbnb.lottie.LottieComposition>; public static fromJsonInputStreamSync(param0: java.io.InputStream, param1: string): com.airbnb.lottie.LottieResult<com.airbnb.lottie.LottieComposition>; public static fromRawRes(param0: globalAndroid.content.Context, param1: number, param2: string): com.airbnb.lottie.LottieTask<com.airbnb.lottie.LottieComposition>; public static fromJsonReader(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: string): com.airbnb.lottie.LottieTask<com.airbnb.lottie.LottieComposition>; public static fromZipStreamSync(param0: java.util.zip.ZipInputStream, param1: string): com.airbnb.lottie.LottieResult<com.airbnb.lottie.LottieComposition>; public static fromAssetSync(param0: globalAndroid.content.Context, param1: string, param2: string): com.airbnb.lottie.LottieResult<com.airbnb.lottie.LottieComposition>; public static fromJsonString(param0: string, param1: string): com.airbnb.lottie.LottieTask<com.airbnb.lottie.LottieComposition>; public static fromUrlSync(param0: globalAndroid.content.Context, param1: string): com.airbnb.lottie.LottieResult<com.airbnb.lottie.LottieComposition>; public static setMaxCacheSize(param0: number): void; public static fromUrl(param0: globalAndroid.content.Context, param1: string, param2: string): com.airbnb.lottie.LottieTask<com.airbnb.lottie.LottieComposition>; public static fromZipStream(param0: java.util.zip.ZipInputStream, param1: string): com.airbnb.lottie.LottieTask<com.airbnb.lottie.LottieComposition>; public static fromUrl(param0: globalAndroid.content.Context, param1: string): com.airbnb.lottie.LottieTask<com.airbnb.lottie.LottieComposition>; public static fromJsonInputStream(param0: java.io.InputStream, param1: string): com.airbnb.lottie.LottieTask<com.airbnb.lottie.LottieComposition>; } } } } declare module com { export module airbnb { export module lottie { export class LottieDrawable extends globalAndroid.graphics.drawable.Drawable implements globalAndroid.graphics.drawable.Drawable.Callback, globalAndroid.graphics.drawable.Animatable { public static class: java.lang.Class<com.airbnb.lottie.LottieDrawable>; public static RESTART: number; public static REVERSE: number; public static INFINITE: number; public enableMergePathsForKitKatAndAbove(param0: boolean): void; public setColorFilter(param0: globalAndroid.graphics.ColorFilter): void; public getMinFrame(): number; public updateBitmap(param0: string, param1: globalAndroid.graphics.Bitmap): globalAndroid.graphics.Bitmap; public getMaxFrame(): number; public getAlpha(): number; public clearComposition(): void; public removeAllUpdateListeners(): void; public constructor(); public setComposition(param0: com.airbnb.lottie.LottieComposition): boolean; public removeAnimatorUpdateListener(param0: globalAndroid.animation.ValueAnimator.AnimatorUpdateListener): void; public setImageAssetDelegate(param0: com.airbnb.lottie.ImageAssetDelegate): void; public isAnimating(): boolean; public setMinAndMaxFrame(param0: string): void; public hasMatte(): boolean; public isRunning(): boolean; public useTextGlyphs(): boolean; public unscheduleDrawable(param0: globalAndroid.graphics.drawable.Drawable, param1: java.lang.Runnable): void; public getPerformanceTracker(): com.airbnb.lottie.PerformanceTracker; public reverseAnimationSpeed(): void; public getImageAsset(param0: string): globalAndroid.graphics.Bitmap; public hasMasks(): boolean; public getRepeatCount(): number; public isMergePathsEnabledForKitKatAndAbove(): boolean; public getTextDelegate(): com.airbnb.lottie.TextDelegate; public invalidateSelf(): void; public setMinAndMaxFrame(param0: number, param1: number): void; public getComposition(): com.airbnb.lottie.LottieComposition; public setMinAndMaxFrame(param0: string, param1: string, param2: boolean): void; public enableMergePathsForKitKatAndAbove(): boolean; public setProgress(param0: number): void; public setRepeatMode(param0: number): void; public isLooping(): boolean; public getIntrinsicHeight(): number; public addAnimatorListener(param0: globalAndroid.animation.Animator.AnimatorListener): void; public pauseAnimation(): void; public getProgress(): number; public setMinFrame(param0: string): void; public getOpacity(): number; public setTextDelegate(param0: com.airbnb.lottie.TextDelegate): void; public isApplyingOpacityToLayersEnabled(): boolean; public addValueCallback(param0: com.airbnb.lottie.model.KeyPath, param1: any, param2: com.airbnb.lottie.value.SimpleLottieValueCallback<any>): void; public getFrame(): number; public getScale(): number; public removeAnimatorListener(param0: globalAndroid.animation.Animator.AnimatorListener): void; public draw(param0: globalAndroid.graphics.Canvas): void; public setColorFilter(param0: number, param1: globalAndroid.graphics.PorterDuff.Mode): void; public setMinFrame(param0: number): void; public setMaxFrame(param0: string): void; public getImageAssetsFolder(): string; public setMaxProgress(param0: number): void; public getIntrinsicWidth(): number; public getTypeface(param0: string, param1: string): globalAndroid.graphics.Typeface; public setSafeMode(param0: boolean): void; public start(): void; public cancelAnimation(): void; public disableExtraScaleModeInFitXY(): void; public setSpeed(param0: number): void; public setFrame(param0: number): void; public setMinAndMaxProgress(param0: number, param1: number): void; /** @deprecated */ public loop(param0: boolean): void; public addAnimatorUpdateListener(param0: globalAndroid.animation.ValueAnimator.AnimatorUpdateListener): void; public resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath): java.util.List<com.airbnb.lottie.model.KeyPath>; public setMaxFrame(param0: number): void; public setScale(param0: number): void; public setAlpha(param0: number): void; public setMinProgress(param0: number): void; public getRepeatMode(): number; public removeAllAnimatorListeners(): void; public setFontAssetDelegate(param0: com.airbnb.lottie.FontAssetDelegate): void; public setImagesAssetsFolder(param0: string): void; public endAnimation(): void; public invalidateDrawable(param0: globalAndroid.graphics.drawable.Drawable): void; public stop(): void; public addValueCallback(param0: com.airbnb.lottie.model.KeyPath, param1: any, param2: com.airbnb.lottie.value.LottieValueCallback<any>): void; public setPerformanceTrackingEnabled(param0: boolean): void; public setApplyingOpacityToLayersEnabled(param0: boolean): void; public scheduleDrawable(param0: globalAndroid.graphics.drawable.Drawable, param1: java.lang.Runnable, param2: number): void; public getSpeed(): number; public playAnimation(): void; public resumeAnimation(): void; public setRepeatCount(param0: number): void; } export module LottieDrawable { export class ColorFilterData extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.LottieDrawable.ColorFilterData>; public equals(param0: any): boolean; public hashCode(): number; } export class LazyCompositionTask extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.LottieDrawable.LazyCompositionTask>; /** * Constructs a new instance of the com.airbnb.lottie.LottieDrawable$LazyCompositionTask interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { run(param0: com.airbnb.lottie.LottieComposition): void; }); public constructor(); public run(param0: com.airbnb.lottie.LottieComposition): void; } export class RepeatMode extends java.lang.Object implements java.lang.annotation.Annotation { public static class: java.lang.Class<com.airbnb.lottie.LottieDrawable.RepeatMode>; /** * Constructs a new instance of the com.airbnb.lottie.LottieDrawable$RepeatMode interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { equals(param0: any): boolean; hashCode(): number; toString(): string; annotationType(): java.lang.Class<any>; }); public constructor(); public equals(param0: any): boolean; public toString(): string; public annotationType(): java.lang.Class<any>; public hashCode(): number; } } } } } declare module com { export module airbnb { export module lottie { export class LottieImageAsset extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.LottieImageAsset>; public getWidth(): number; public getHeight(): number; public getId(): string; public getFileName(): string; public setBitmap(param0: globalAndroid.graphics.Bitmap): void; public constructor(param0: number, param1: number, param2: string, param3: string, param4: string); public getDirName(): string; public getBitmap(): globalAndroid.graphics.Bitmap; } } } } declare module com { export module airbnb { export module lottie { export class LottieListener<T> extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.LottieListener<any>>; /** * Constructs a new instance of the com.airbnb.lottie.LottieListener<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onResult(param0: T): void; }); public constructor(); public onResult(param0: T): void; } } } } declare module com { export module airbnb { export module lottie { export class LottieLogger extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.LottieLogger>; /** * Constructs a new instance of the com.airbnb.lottie.LottieLogger interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { debug(param0: string): void; debug(param0: string, param1: java.lang.Throwable): void; warning(param0: string): void; warning(param0: string, param1: java.lang.Throwable): void; error(param0: string, param1: java.lang.Throwable): void; }); public constructor(); public error(param0: string, param1: java.lang.Throwable): void; public debug(param0: string): void; public warning(param0: string): void; public warning(param0: string, param1: java.lang.Throwable): void; public debug(param0: string, param1: java.lang.Throwable): void; } } } } declare module com { export module airbnb { export module lottie { export class LottieOnCompositionLoadedListener extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.LottieOnCompositionLoadedListener>; /** * Constructs a new instance of the com.airbnb.lottie.LottieOnCompositionLoadedListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onCompositionLoaded(param0: com.airbnb.lottie.LottieComposition): void; }); public constructor(); public onCompositionLoaded(param0: com.airbnb.lottie.LottieComposition): void; } } } } declare module com { export module airbnb { export module lottie { export class LottieProperty extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.LottieProperty>; /** * Constructs a new instance of the com.airbnb.lottie.LottieProperty interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { <clinit>(): void; }); public constructor(); public static STROKE_COLOR: java.lang.Integer; public static TRANSFORM_SCALE: com.airbnb.lottie.value.ScaleXY; public static POLYSTAR_POINTS: java.lang.Float; public static TRANSFORM_END_OPACITY: java.lang.Float; public static RECTANGLE_SIZE: globalAndroid.graphics.PointF; public static REPEATER_OFFSET: java.lang.Float; public static POLYSTAR_OUTER_ROUNDEDNESS: java.lang.Float; public static COLOR_FILTER: globalAndroid.graphics.ColorFilter; public static POLYSTAR_OUTER_RADIUS: java.lang.Float; public static COLOR: java.lang.Integer; public static POLYSTAR_INNER_ROUNDEDNESS: java.lang.Float; public static TRANSFORM_ROTATION: java.lang.Float; public static POLYSTAR_ROTATION: java.lang.Float; public static GRADIENT_COLOR: native.Array<java.lang.Integer>; public static CORNER_RADIUS: java.lang.Float; public static OPACITY: java.lang.Integer; public static TEXT_SIZE: java.lang.Float; public static TEXT_TRACKING: java.lang.Float; public static TIME_REMAP: java.lang.Float; public static TRANSFORM_SKEW: java.lang.Float; public static TRANSFORM_ANCHOR_POINT: globalAndroid.graphics.PointF; public static TRANSFORM_OPACITY: java.lang.Integer; public static ELLIPSE_SIZE: globalAndroid.graphics.PointF; public static STROKE_WIDTH: java.lang.Float; public static REPEATER_COPIES: java.lang.Float; public static POLYSTAR_INNER_RADIUS: java.lang.Float; public static TRANSFORM_SKEW_ANGLE: java.lang.Float; public static POSITION: globalAndroid.graphics.PointF; public static TRANSFORM_POSITION: globalAndroid.graphics.PointF; public static TRANSFORM_START_OPACITY: java.lang.Float; } } } } declare module com { export module airbnb { export module lottie { export class LottieResult<V> extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.LottieResult<any>>; public constructor(param0: V); public getValue(): V; public getException(): java.lang.Throwable; public hashCode(): number; public equals(param0: any): boolean; public constructor(param0: java.lang.Throwable); } } } } declare module com { export module airbnb { export module lottie { export class LottieTask<T> extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.LottieTask<any>>; public static EXECUTOR: java.util.concurrent.Executor; public constructor(param0: java.util.concurrent.Callable<com.airbnb.lottie.LottieResult<T>>); public addListener(param0: com.airbnb.lottie.LottieListener<T>): com.airbnb.lottie.LottieTask<T>; public removeFailureListener(param0: com.airbnb.lottie.LottieListener<java.lang.Throwable>): com.airbnb.lottie.LottieTask<T>; public removeListener(param0: com.airbnb.lottie.LottieListener<T>): com.airbnb.lottie.LottieTask<T>; public addFailureListener(param0: com.airbnb.lottie.LottieListener<java.lang.Throwable>): com.airbnb.lottie.LottieTask<T>; } export module LottieTask { export class LottieFutureTask extends java.util.concurrent.FutureTask<com.airbnb.lottie.LottieResult<any>> { public static class: java.lang.Class<com.airbnb.lottie.LottieTask.LottieFutureTask>; public done(): void; public run(): void; } } } } } declare module com { export module airbnb { export module lottie { export class OnCompositionLoadedListener extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.OnCompositionLoadedListener>; /** * Constructs a new instance of the com.airbnb.lottie.OnCompositionLoadedListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onCompositionLoaded(param0: com.airbnb.lottie.LottieComposition): void; }); public constructor(); public onCompositionLoaded(param0: com.airbnb.lottie.LottieComposition): void; } } } } declare module com { export module airbnb { export module lottie { export class PerformanceTracker extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.PerformanceTracker>; public getSortedRenderTimes(): java.util.List<androidx.core.util.Pair<string,java.lang.Float>>; public addFrameListener(param0: com.airbnb.lottie.PerformanceTracker.FrameListener): void; public logRenderTimes(): void; public clearRenderTimes(): void; public recordRenderTime(param0: string, param1: number): void; public removeFrameListener(param0: com.airbnb.lottie.PerformanceTracker.FrameListener): void; public constructor(); } export module PerformanceTracker { export class FrameListener extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.PerformanceTracker.FrameListener>; /** * Constructs a new instance of the com.airbnb.lottie.PerformanceTracker$FrameListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onFrameRendered(param0: number): void; }); public constructor(); public onFrameRendered(param0: number): void; } } } } } declare module com { export module airbnb { export module lottie { export class RenderMode { public static class: java.lang.Class<com.airbnb.lottie.RenderMode>; public static AUTOMATIC: com.airbnb.lottie.RenderMode; public static HARDWARE: com.airbnb.lottie.RenderMode; public static SOFTWARE: com.airbnb.lottie.RenderMode; public static valueOf(param0: string): com.airbnb.lottie.RenderMode; public static values(): native.Array<com.airbnb.lottie.RenderMode>; public static valueOf(param0: java.lang.Class<com.airbnb.lottie.RenderMode>, param1: string): java.lang.Enum<com.airbnb.lottie.RenderMode>; } } } } declare module com { export module airbnb { export module lottie { export class SimpleColorFilter extends globalAndroid.graphics.PorterDuffColorFilter { public static class: java.lang.Class<com.airbnb.lottie.SimpleColorFilter>; /** @deprecated */ public constructor(); public constructor(param0: number); public constructor(param0: number, param1: globalAndroid.graphics.PorterDuff.Mode); } } } } declare module com { export module airbnb { export module lottie { export class TextDelegate extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.TextDelegate>; public setText(param0: string, param1: string): void; public invalidateAllText(): void; public setCacheText(param0: boolean): void; public invalidateText(param0: string): void; public getTextInternal(param0: string): string; public constructor(param0: com.airbnb.lottie.LottieAnimationView); public constructor(param0: com.airbnb.lottie.LottieDrawable); } } } } declare module com { export module airbnb { export module lottie { export module animation { export class LPaint extends globalAndroid.graphics.Paint { public static class: java.lang.Class<com.airbnb.lottie.animation.LPaint>; public constructor(param0: globalAndroid.graphics.Paint); public constructor(); public constructor(param0: globalAndroid.graphics.PorterDuff.Mode); public constructor(param0: number, param1: globalAndroid.graphics.PorterDuff.Mode); public constructor(param0: number); public setTextLocales(param0: any): void; } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export abstract class BaseStrokeContent extends java.lang.Object implements com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.AnimationListener, com.airbnb.lottie.animation.content.KeyPathElementContent, com.airbnb.lottie.animation.content.DrawingContent { public static class: java.lang.Class<com.airbnb.lottie.animation.content.BaseStrokeContent>; public layer: com.airbnb.lottie.model.layer.BaseLayer; public onValueChanged(): void; public getBounds(param0: globalAndroid.graphics.RectF, param1: globalAndroid.graphics.Matrix, param2: boolean): void; public resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; public setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; public addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; public getName(): string; public draw(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.Matrix, param2: number): void; } export module BaseStrokeContent { export class PathGroup extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.animation.content.BaseStrokeContent.PathGroup>; } } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export class CompoundTrimPathContent extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.animation.content.CompoundTrimPathContent>; public constructor(); public apply(param0: globalAndroid.graphics.Path): void; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export class Content extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.animation.content.Content>; /** * Constructs a new instance of the com.airbnb.lottie.animation.content.Content interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getName(): string; setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; }); public constructor(); public setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; public getName(): string; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export class ContentGroup extends java.lang.Object implements com.airbnb.lottie.animation.content.DrawingContent, com.airbnb.lottie.animation.content.PathContent, com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.AnimationListener, com.airbnb.lottie.model.KeyPathElement { public static class: java.lang.Class<com.airbnb.lottie.animation.content.ContentGroup>; public onValueChanged(): void; public getPath(): globalAndroid.graphics.Path; public getBounds(param0: globalAndroid.graphics.RectF, param1: globalAndroid.graphics.Matrix, param2: boolean): void; public resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; public setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; public addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; public constructor(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer, param2: com.airbnb.lottie.model.content.ShapeGroup); public getName(): string; public draw(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.Matrix, param2: number): void; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export class DrawingContent extends java.lang.Object implements com.airbnb.lottie.animation.content.Content { public static class: java.lang.Class<com.airbnb.lottie.animation.content.DrawingContent>; /** * Constructs a new instance of the com.airbnb.lottie.animation.content.DrawingContent interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { draw(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.Matrix, param2: number): void; getBounds(param0: globalAndroid.graphics.RectF, param1: globalAndroid.graphics.Matrix, param2: boolean): void; getName(): string; setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; }); public constructor(); public getBounds(param0: globalAndroid.graphics.RectF, param1: globalAndroid.graphics.Matrix, param2: boolean): void; public setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; public getName(): string; public draw(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.Matrix, param2: number): void; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export class EllipseContent extends java.lang.Object implements com.airbnb.lottie.animation.content.PathContent, com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.AnimationListener, com.airbnb.lottie.animation.content.KeyPathElementContent { public static class: java.lang.Class<com.airbnb.lottie.animation.content.EllipseContent>; public onValueChanged(): void; public getPath(): globalAndroid.graphics.Path; public resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; public setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; public addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; public constructor(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer, param2: com.airbnb.lottie.model.content.CircleShape); public getName(): string; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export class FillContent extends java.lang.Object implements com.airbnb.lottie.animation.content.DrawingContent, com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.AnimationListener, com.airbnb.lottie.animation.content.KeyPathElementContent { public static class: java.lang.Class<com.airbnb.lottie.animation.content.FillContent>; public onValueChanged(): void; public getBounds(param0: globalAndroid.graphics.RectF, param1: globalAndroid.graphics.Matrix, param2: boolean): void; public resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; public setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; public addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; public constructor(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer, param2: com.airbnb.lottie.model.content.ShapeFill); public getName(): string; public draw(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.Matrix, param2: number): void; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export class GradientFillContent extends java.lang.Object implements com.airbnb.lottie.animation.content.DrawingContent, com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.AnimationListener, com.airbnb.lottie.animation.content.KeyPathElementContent { public static class: java.lang.Class<com.airbnb.lottie.animation.content.GradientFillContent>; public onValueChanged(): void; public constructor(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer, param2: com.airbnb.lottie.model.content.GradientFill); public getBounds(param0: globalAndroid.graphics.RectF, param1: globalAndroid.graphics.Matrix, param2: boolean): void; public resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; public setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; public addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; public getName(): string; public draw(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.Matrix, param2: number): void; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export class GradientStrokeContent extends com.airbnb.lottie.animation.content.BaseStrokeContent { public static class: java.lang.Class<com.airbnb.lottie.animation.content.GradientStrokeContent>; public onValueChanged(): void; public constructor(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer, param2: com.airbnb.lottie.model.content.GradientStroke); public getBounds(param0: globalAndroid.graphics.RectF, param1: globalAndroid.graphics.Matrix, param2: boolean): void; public addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; public getName(): string; public draw(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.Matrix, param2: number): void; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export class GreedyContent extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.animation.content.GreedyContent>; /** * Constructs a new instance of the com.airbnb.lottie.animation.content.GreedyContent interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { absorbContent(param0: java.util.ListIterator<com.airbnb.lottie.animation.content.Content>): void; }); public constructor(); public absorbContent(param0: java.util.ListIterator<com.airbnb.lottie.animation.content.Content>): void; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export class KeyPathElementContent extends java.lang.Object implements com.airbnb.lottie.model.KeyPathElement, com.airbnb.lottie.animation.content.Content { public static class: java.lang.Class<com.airbnb.lottie.animation.content.KeyPathElementContent>; /** * Constructs a new instance of the com.airbnb.lottie.animation.content.KeyPathElementContent interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; getName(): string; setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; }); public constructor(); public resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; public setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; public addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; public getName(): string; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export class MergePathsContent extends java.lang.Object implements com.airbnb.lottie.animation.content.PathContent, com.airbnb.lottie.animation.content.GreedyContent { public static class: java.lang.Class<com.airbnb.lottie.animation.content.MergePathsContent>; public getPath(): globalAndroid.graphics.Path; public absorbContent(param0: java.util.ListIterator<com.airbnb.lottie.animation.content.Content>): void; public setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; public constructor(param0: com.airbnb.lottie.model.content.MergePaths); public getName(): string; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export class ModifierContent extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.animation.content.ModifierContent>; /** * Constructs a new instance of the com.airbnb.lottie.animation.content.ModifierContent interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export class PathContent extends java.lang.Object implements com.airbnb.lottie.animation.content.Content { public static class: java.lang.Class<com.airbnb.lottie.animation.content.PathContent>; /** * Constructs a new instance of the com.airbnb.lottie.animation.content.PathContent interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getPath(): globalAndroid.graphics.Path; getName(): string; setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; }); public constructor(); public getPath(): globalAndroid.graphics.Path; public setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; public getName(): string; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export class PolystarContent extends java.lang.Object implements com.airbnb.lottie.animation.content.PathContent, com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.AnimationListener, com.airbnb.lottie.animation.content.KeyPathElementContent { public static class: java.lang.Class<com.airbnb.lottie.animation.content.PolystarContent>; public onValueChanged(): void; public getPath(): globalAndroid.graphics.Path; public resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; public setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; public addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; public getName(): string; public constructor(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer, param2: com.airbnb.lottie.model.content.PolystarShape); } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export class RectangleContent extends java.lang.Object implements com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.AnimationListener, com.airbnb.lottie.animation.content.KeyPathElementContent, com.airbnb.lottie.animation.content.PathContent { public static class: java.lang.Class<com.airbnb.lottie.animation.content.RectangleContent>; public onValueChanged(): void; public getPath(): globalAndroid.graphics.Path; public resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; public setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; public addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; public constructor(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer, param2: com.airbnb.lottie.model.content.RectangleShape); public getName(): string; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export class RepeaterContent extends java.lang.Object implements com.airbnb.lottie.animation.content.DrawingContent, com.airbnb.lottie.animation.content.PathContent, com.airbnb.lottie.animation.content.GreedyContent, com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.AnimationListener, com.airbnb.lottie.animation.content.KeyPathElementContent { public static class: java.lang.Class<com.airbnb.lottie.animation.content.RepeaterContent>; public getPath(): globalAndroid.graphics.Path; public onValueChanged(): void; public getBounds(param0: globalAndroid.graphics.RectF, param1: globalAndroid.graphics.Matrix, param2: boolean): void; public resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; public absorbContent(param0: java.util.ListIterator<com.airbnb.lottie.animation.content.Content>): void; public setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; public constructor(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer, param2: com.airbnb.lottie.model.content.Repeater); public addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; public getName(): string; public draw(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.Matrix, param2: number): void; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export class ShapeContent extends java.lang.Object implements com.airbnb.lottie.animation.content.PathContent, com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.AnimationListener { public static class: java.lang.Class<com.airbnb.lottie.animation.content.ShapeContent>; public onValueChanged(): void; public getPath(): globalAndroid.graphics.Path; public constructor(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer, param2: com.airbnb.lottie.model.content.ShapePath); public setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; public getName(): string; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export class StrokeContent extends com.airbnb.lottie.animation.content.BaseStrokeContent { public static class: java.lang.Class<com.airbnb.lottie.animation.content.StrokeContent>; public onValueChanged(): void; public getBounds(param0: globalAndroid.graphics.RectF, param1: globalAndroid.graphics.Matrix, param2: boolean): void; public addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; public constructor(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer, param2: com.airbnb.lottie.model.content.ShapeStroke); public getName(): string; public draw(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.Matrix, param2: number): void; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module content { export class TrimPathContent extends java.lang.Object implements com.airbnb.lottie.animation.content.Content, com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.AnimationListener { public static class: java.lang.Class<com.airbnb.lottie.animation.content.TrimPathContent>; public onValueChanged(): void; public constructor(param0: com.airbnb.lottie.model.layer.BaseLayer, param1: com.airbnb.lottie.model.content.ShapeTrimPath); public isHidden(): boolean; public getOffset(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,java.lang.Float>; public getStart(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,java.lang.Float>; public setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; public getName(): string; public getEnd(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,java.lang.Float>; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module keyframe { export abstract class BaseKeyframeAnimation<K, A> extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,any>>; public valueCallback: com.airbnb.lottie.value.LottieValueCallback<A>; public setProgress(param0: number): void; public getCurrentKeyframe(): com.airbnb.lottie.value.Keyframe<K>; public setIsDiscrete(): void; public addUpdateListener(param0: com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.AnimationListener): void; public notifyListeners(): void; public getValue(): A; public getProgress(): number; public setValueCallback(param0: com.airbnb.lottie.value.LottieValueCallback<A>): void; public getInterpolatedCurrentKeyframeProgress(): number; } export module BaseKeyframeAnimation { export class AnimationListener extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.AnimationListener>; /** * Constructs a new instance of the com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation$AnimationListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onValueChanged(): void; }); public constructor(); public onValueChanged(): void; } export class EmptyKeyframeWrapper<T> extends com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.KeyframesWrapper<any> { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.EmptyKeyframeWrapper<any>>; public getCurrentKeyframe(): com.airbnb.lottie.value.Keyframe<any>; public isCachedValueEnabled(param0: number): boolean; public getStartDelayProgress(): number; public isValueChanged(param0: number): boolean; public isEmpty(): boolean; public getEndProgress(): number; } export class KeyframesWrapper<T> extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.KeyframesWrapper<any>>; /** * Constructs a new instance of the com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation$KeyframesWrapper interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { isEmpty(): boolean; isValueChanged(param0: number): boolean; getCurrentKeyframe(): com.airbnb.lottie.value.Keyframe<T>; getStartDelayProgress(): number; getEndProgress(): number; isCachedValueEnabled(param0: number): boolean; }); public constructor(); public getCurrentKeyframe(): com.airbnb.lottie.value.Keyframe<T>; public isCachedValueEnabled(param0: number): boolean; public getStartDelayProgress(): number; public isValueChanged(param0: number): boolean; public isEmpty(): boolean; public getEndProgress(): number; } export class KeyframesWrapperImpl<T> extends com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.KeyframesWrapper<any> { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.KeyframesWrapperImpl<any>>; public getCurrentKeyframe(): com.airbnb.lottie.value.Keyframe<any>; public isCachedValueEnabled(param0: number): boolean; public getStartDelayProgress(): number; public isValueChanged(param0: number): boolean; public isEmpty(): boolean; public getEndProgress(): number; } export class SingleKeyframeWrapper<T> extends com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.KeyframesWrapper<any> { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.SingleKeyframeWrapper<any>>; public getCurrentKeyframe(): com.airbnb.lottie.value.Keyframe<any>; public isCachedValueEnabled(param0: number): boolean; public getStartDelayProgress(): number; public isValueChanged(param0: number): boolean; public isEmpty(): boolean; public getEndProgress(): number; } } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module keyframe { export class ColorKeyframeAnimation extends com.airbnb.lottie.animation.keyframe.KeyframeAnimation<java.lang.Integer> { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.ColorKeyframeAnimation>; public getIntValue(param0: com.airbnb.lottie.value.Keyframe<java.lang.Integer>, param1: number): number; public constructor(param0: java.util.List<com.airbnb.lottie.value.Keyframe<java.lang.Integer>>); public getIntValue(): number; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module keyframe { export class FloatKeyframeAnimation extends com.airbnb.lottie.animation.keyframe.KeyframeAnimation<java.lang.Float> { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.FloatKeyframeAnimation>; public constructor(param0: java.util.List<com.airbnb.lottie.value.Keyframe<java.lang.Float>>); public getFloatValue(): number; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module keyframe { export class GradientColorKeyframeAnimation extends com.airbnb.lottie.animation.keyframe.KeyframeAnimation<com.airbnb.lottie.model.content.GradientColor> { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.GradientColorKeyframeAnimation>; public constructor(param0: java.util.List<com.airbnb.lottie.value.Keyframe<com.airbnb.lottie.model.content.GradientColor>>); } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module keyframe { export class IntegerKeyframeAnimation extends com.airbnb.lottie.animation.keyframe.KeyframeAnimation<java.lang.Integer> { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.IntegerKeyframeAnimation>; public constructor(param0: java.util.List<com.airbnb.lottie.value.Keyframe<java.lang.Integer>>); public getIntValue(): number; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module keyframe { export abstract class KeyframeAnimation<T> extends com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,any> { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.KeyframeAnimation<any>>; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module keyframe { export class MaskKeyframeAnimation extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.MaskKeyframeAnimation>; public getOpacityAnimations(): java.util.List<com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<java.lang.Integer,java.lang.Integer>>; public getMaskAnimations(): java.util.List<com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<com.airbnb.lottie.model.content.ShapeData,globalAndroid.graphics.Path>>; public constructor(param0: java.util.List<com.airbnb.lottie.model.content.Mask>); public getMasks(): java.util.List<com.airbnb.lottie.model.content.Mask>; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module keyframe { export class PathKeyframe extends com.airbnb.lottie.value.Keyframe<globalAndroid.graphics.PointF> { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.PathKeyframe>; public constructor(param0: com.airbnb.lottie.LottieComposition, param1: any, param2: any, param3: globalAndroid.view.animation.Interpolator, param4: number, param5: java.lang.Float); public constructor(param0: com.airbnb.lottie.LottieComposition, param1: com.airbnb.lottie.value.Keyframe<globalAndroid.graphics.PointF>); public createPath(): void; public constructor(param0: any); } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module keyframe { export class PathKeyframeAnimation extends com.airbnb.lottie.animation.keyframe.KeyframeAnimation<globalAndroid.graphics.PointF> { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.PathKeyframeAnimation>; public constructor(param0: java.util.List<any>); public getValue(): any; public getValue(param0: com.airbnb.lottie.value.Keyframe<globalAndroid.graphics.PointF>, param1: number): globalAndroid.graphics.PointF; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module keyframe { export class PointKeyframeAnimation extends com.airbnb.lottie.animation.keyframe.KeyframeAnimation<globalAndroid.graphics.PointF> { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.PointKeyframeAnimation>; public getValue(): any; public getValue(param0: com.airbnb.lottie.value.Keyframe<globalAndroid.graphics.PointF>, param1: number): globalAndroid.graphics.PointF; public constructor(param0: java.util.List<com.airbnb.lottie.value.Keyframe<globalAndroid.graphics.PointF>>); } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module keyframe { export class ScaleKeyframeAnimation extends com.airbnb.lottie.animation.keyframe.KeyframeAnimation<com.airbnb.lottie.value.ScaleXY> { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.ScaleKeyframeAnimation>; public getValue(): any; public getValue(param0: com.airbnb.lottie.value.Keyframe<com.airbnb.lottie.value.ScaleXY>, param1: number): com.airbnb.lottie.value.ScaleXY; public constructor(param0: java.util.List<com.airbnb.lottie.value.Keyframe<com.airbnb.lottie.value.ScaleXY>>); } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module keyframe { export class ShapeKeyframeAnimation extends com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<com.airbnb.lottie.model.content.ShapeData,globalAndroid.graphics.Path> { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.ShapeKeyframeAnimation>; public getValue(param0: com.airbnb.lottie.value.Keyframe<com.airbnb.lottie.model.content.ShapeData>, param1: number): globalAndroid.graphics.Path; public getValue(): any; public constructor(param0: java.util.List<com.airbnb.lottie.value.Keyframe<com.airbnb.lottie.model.content.ShapeData>>); } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module keyframe { export class SplitDimensionPathKeyframeAnimation extends com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<globalAndroid.graphics.PointF,globalAndroid.graphics.PointF> { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.SplitDimensionPathKeyframeAnimation>; public setProgress(param0: number): void; public getValue(): globalAndroid.graphics.PointF; public getValue(): any; public constructor(param0: com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<java.lang.Float,java.lang.Float>, param1: com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<java.lang.Float,java.lang.Float>); } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module keyframe { export class TextKeyframeAnimation extends com.airbnb.lottie.animation.keyframe.KeyframeAnimation<com.airbnb.lottie.model.DocumentData> { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.TextKeyframeAnimation>; public constructor(param0: java.util.List<com.airbnb.lottie.value.Keyframe<com.airbnb.lottie.model.DocumentData>>); } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module keyframe { export class TransformKeyframeAnimation extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.TransformKeyframeAnimation>; public setProgress(param0: number): void; public getEndOpacity(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,java.lang.Float>; public constructor(param0: com.airbnb.lottie.model.animatable.AnimatableTransform); public applyValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): boolean; public getMatrix(): globalAndroid.graphics.Matrix; public addAnimationsToLayer(param0: com.airbnb.lottie.model.layer.BaseLayer): void; public getOpacity(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,java.lang.Integer>; public getMatrixForRepeater(param0: number): globalAndroid.graphics.Matrix; public addListener(param0: com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.AnimationListener): void; public getStartOpacity(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,java.lang.Float>; } } } } } } declare module com { export module airbnb { export module lottie { export module animation { export module keyframe { export class ValueCallbackKeyframeAnimation<K, A> extends com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,any> { public static class: java.lang.Class<com.airbnb.lottie.animation.keyframe.ValueCallbackKeyframeAnimation<any,any>>; public constructor(param0: com.airbnb.lottie.value.LottieValueCallback<any>, param1: any); public notifyListeners(): void; public getValue(): any; public constructor(param0: com.airbnb.lottie.value.LottieValueCallback<any>); } } } } } } declare module com { export module airbnb { export module lottie { export module manager { export class FontAssetManager extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.manager.FontAssetManager>; public setDelegate(param0: com.airbnb.lottie.FontAssetDelegate): void; public constructor(param0: globalAndroid.graphics.drawable.Drawable.Callback, param1: com.airbnb.lottie.FontAssetDelegate); public setDefaultFontFileExtension(param0: string): void; public getTypeface(param0: string, param1: string): globalAndroid.graphics.Typeface; } } } } } declare module com { export module airbnb { export module lottie { export module manager { export class ImageAssetManager extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.manager.ImageAssetManager>; public constructor(param0: globalAndroid.graphics.drawable.Drawable.Callback, param1: string, param2: com.airbnb.lottie.ImageAssetDelegate, param3: java.util.Map<string,com.airbnb.lottie.LottieImageAsset>); public updateBitmap(param0: string, param1: globalAndroid.graphics.Bitmap): globalAndroid.graphics.Bitmap; public setDelegate(param0: com.airbnb.lottie.ImageAssetDelegate): void; public hasSameContext(param0: globalAndroid.content.Context): boolean; public bitmapForId(param0: string): globalAndroid.graphics.Bitmap; } } } } } declare module com { export module airbnb { export module lottie { export module model { export class CubicCurveData extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.model.CubicCurveData>; public setControlPoint1(param0: number, param1: number): void; public getVertex(): globalAndroid.graphics.PointF; public setControlPoint2(param0: number, param1: number): void; public constructor(param0: globalAndroid.graphics.PointF, param1: globalAndroid.graphics.PointF, param2: globalAndroid.graphics.PointF); public setVertex(param0: number, param1: number): void; public constructor(); public getControlPoint2(): globalAndroid.graphics.PointF; public getControlPoint1(): globalAndroid.graphics.PointF; } } } } } declare module com { export module airbnb { export module lottie { export module model { export class DocumentData extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.model.DocumentData>; public text: string; public fontName: string; public size: number; public justification: com.airbnb.lottie.model.DocumentData.Justification; public tracking: number; public lineHeight: number; public baselineShift: number; public color: number; public strokeColor: number; public strokeWidth: number; public strokeOverFill: boolean; public constructor(param0: string, param1: string, param2: number, param3: com.airbnb.lottie.model.DocumentData.Justification, param4: number, param5: number, param6: number, param7: number, param8: number, param9: number, param10: boolean); public hashCode(): number; } export module DocumentData { export class Justification { public static class: java.lang.Class<com.airbnb.lottie.model.DocumentData.Justification>; public static LEFT_ALIGN: com.airbnb.lottie.model.DocumentData.Justification; public static RIGHT_ALIGN: com.airbnb.lottie.model.DocumentData.Justification; public static CENTER: com.airbnb.lottie.model.DocumentData.Justification; public static valueOf(param0: java.lang.Class<com.airbnb.lottie.model.DocumentData.Justification>, param1: string): java.lang.Enum<com.airbnb.lottie.model.DocumentData.Justification>; public static values(): native.Array<com.airbnb.lottie.model.DocumentData.Justification>; public static valueOf(param0: string): com.airbnb.lottie.model.DocumentData.Justification; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export class Font extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.model.Font>; public getName(): string; public getFamily(): string; public constructor(param0: string, param1: string, param2: string, param3: number); public getStyle(): string; } } } } } declare module com { export module airbnb { export module lottie { export module model { export class FontCharacter extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.model.FontCharacter>; public getShapes(): java.util.List<com.airbnb.lottie.model.content.ShapeGroup>; public static hashFor(param0: string, param1: string, param2: string): number; public getWidth(): number; public constructor(param0: java.util.List<com.airbnb.lottie.model.content.ShapeGroup>, param1: string, param2: number, param3: number, param4: string, param5: string); public hashCode(): number; } } } } } declare module com { export module airbnb { export module lottie { export module model { export class KeyPath extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.model.KeyPath>; public fullyResolvesTo(param0: string, param1: number): boolean; public incrementDepthBy(param0: string, param1: number): number; public matches(param0: string, param1: number): boolean; public propagateToChildren(param0: string, param1: number): boolean; public toString(): string; public resolve(param0: com.airbnb.lottie.model.KeyPathElement): com.airbnb.lottie.model.KeyPath; public getResolvedElement(): com.airbnb.lottie.model.KeyPathElement; public addKey(param0: string): com.airbnb.lottie.model.KeyPath; public constructor(param0: native.Array<string>); public keysToString(): string; } } } } } declare module com { export module airbnb { export module lottie { export module model { export class KeyPathElement extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.model.KeyPathElement>; /** * Constructs a new instance of the com.airbnb.lottie.model.KeyPathElement interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; }); public constructor(); public addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; public resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; } } } } } declare module com { export module airbnb { export module lottie { export module model { export class LottieCompositionCache extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.model.LottieCompositionCache>; public clear(): void; public put(param0: string, param1: com.airbnb.lottie.LottieComposition): void; public resize(param0: number): void; public get(param0: string): com.airbnb.lottie.LottieComposition; public static getInstance(): com.airbnb.lottie.model.LottieCompositionCache; } } } } } declare module com { export module airbnb { export module lottie { export module model { export class Marker extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.model.Marker>; public startFrame: number; public durationFrames: number; public matchesName(param0: string): boolean; public constructor(param0: string, param1: number, param2: number); } } } } } declare module com { export module airbnb { export module lottie { export module model { export class MutablePair<T> extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.model.MutablePair<any>>; public equals(param0: any): boolean; public toString(): string; public constructor(); public set(param0: T, param1: T): void; public hashCode(): number; } } } } } declare module com { export module airbnb { export module lottie { export module model { export module animatable { export class AnimatableColorValue extends com.airbnb.lottie.model.animatable.BaseAnimatableValue<java.lang.Integer,java.lang.Integer> { public static class: java.lang.Class<com.airbnb.lottie.model.animatable.AnimatableColorValue>; public isStatic(): boolean; public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<java.lang.Integer,java.lang.Integer>; public getKeyframes(): java.util.List<com.airbnb.lottie.value.Keyframe<any>>; public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,any>; public constructor(param0: java.util.List<com.airbnb.lottie.value.Keyframe<java.lang.Integer>>); } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module animatable { export class AnimatableFloatValue extends com.airbnb.lottie.model.animatable.BaseAnimatableValue<java.lang.Float,java.lang.Float> { public static class: java.lang.Class<com.airbnb.lottie.model.animatable.AnimatableFloatValue>; public isStatic(): boolean; public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<java.lang.Float,java.lang.Float>; public constructor(param0: java.util.List<com.airbnb.lottie.value.Keyframe<java.lang.Float>>); public getKeyframes(): java.util.List<com.airbnb.lottie.value.Keyframe<any>>; public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,any>; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module animatable { export class AnimatableGradientColorValue extends com.airbnb.lottie.model.animatable.BaseAnimatableValue<com.airbnb.lottie.model.content.GradientColor,com.airbnb.lottie.model.content.GradientColor> { public static class: java.lang.Class<com.airbnb.lottie.model.animatable.AnimatableGradientColorValue>; public isStatic(): boolean; public constructor(param0: java.util.List<com.airbnb.lottie.value.Keyframe<com.airbnb.lottie.model.content.GradientColor>>); public getKeyframes(): java.util.List<com.airbnb.lottie.value.Keyframe<any>>; public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<com.airbnb.lottie.model.content.GradientColor,com.airbnb.lottie.model.content.GradientColor>; public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,any>; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module animatable { export class AnimatableIntegerValue extends com.airbnb.lottie.model.animatable.BaseAnimatableValue<java.lang.Integer,java.lang.Integer> { public static class: java.lang.Class<com.airbnb.lottie.model.animatable.AnimatableIntegerValue>; public isStatic(): boolean; public constructor(); public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<java.lang.Integer,java.lang.Integer>; public getKeyframes(): java.util.List<com.airbnb.lottie.value.Keyframe<any>>; public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,any>; public constructor(param0: java.util.List<com.airbnb.lottie.value.Keyframe<java.lang.Integer>>); } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module animatable { export class AnimatablePathValue extends com.airbnb.lottie.model.animatable.AnimatableValue<globalAndroid.graphics.PointF,globalAndroid.graphics.PointF> { public static class: java.lang.Class<com.airbnb.lottie.model.animatable.AnimatablePathValue>; public isStatic(): boolean; public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<globalAndroid.graphics.PointF,globalAndroid.graphics.PointF>; public constructor(); public getKeyframes(): java.util.List<com.airbnb.lottie.value.Keyframe<globalAndroid.graphics.PointF>>; public getKeyframes(): java.util.List<com.airbnb.lottie.value.Keyframe<any>>; public constructor(param0: java.util.List<com.airbnb.lottie.value.Keyframe<globalAndroid.graphics.PointF>>); public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,any>; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module animatable { export class AnimatablePointValue extends com.airbnb.lottie.model.animatable.BaseAnimatableValue<globalAndroid.graphics.PointF,globalAndroid.graphics.PointF> { public static class: java.lang.Class<com.airbnb.lottie.model.animatable.AnimatablePointValue>; public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<globalAndroid.graphics.PointF,globalAndroid.graphics.PointF>; public isStatic(): boolean; public getKeyframes(): java.util.List<com.airbnb.lottie.value.Keyframe<any>>; public constructor(param0: java.util.List<com.airbnb.lottie.value.Keyframe<globalAndroid.graphics.PointF>>); public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,any>; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module animatable { export class AnimatableScaleValue extends com.airbnb.lottie.model.animatable.BaseAnimatableValue<com.airbnb.lottie.value.ScaleXY,com.airbnb.lottie.value.ScaleXY> { public static class: java.lang.Class<com.airbnb.lottie.model.animatable.AnimatableScaleValue>; public isStatic(): boolean; public constructor(param0: com.airbnb.lottie.value.ScaleXY); public getKeyframes(): java.util.List<com.airbnb.lottie.value.Keyframe<any>>; public constructor(param0: java.util.List<com.airbnb.lottie.value.Keyframe<com.airbnb.lottie.value.ScaleXY>>); public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,any>; public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<com.airbnb.lottie.value.ScaleXY,com.airbnb.lottie.value.ScaleXY>; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module animatable { export class AnimatableShapeValue extends com.airbnb.lottie.model.animatable.BaseAnimatableValue<com.airbnb.lottie.model.content.ShapeData,globalAndroid.graphics.Path> { public static class: java.lang.Class<com.airbnb.lottie.model.animatable.AnimatableShapeValue>; public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<com.airbnb.lottie.model.content.ShapeData,globalAndroid.graphics.Path>; public isStatic(): boolean; public getKeyframes(): java.util.List<com.airbnb.lottie.value.Keyframe<any>>; public constructor(param0: java.util.List<com.airbnb.lottie.value.Keyframe<com.airbnb.lottie.model.content.ShapeData>>); public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,any>; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module animatable { export class AnimatableSplitDimensionPathValue extends com.airbnb.lottie.model.animatable.AnimatableValue<globalAndroid.graphics.PointF,globalAndroid.graphics.PointF> { public static class: java.lang.Class<com.airbnb.lottie.model.animatable.AnimatableSplitDimensionPathValue>; public isStatic(): boolean; public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<globalAndroid.graphics.PointF,globalAndroid.graphics.PointF>; public constructor(param0: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param1: com.airbnb.lottie.model.animatable.AnimatableFloatValue); public getKeyframes(): java.util.List<com.airbnb.lottie.value.Keyframe<globalAndroid.graphics.PointF>>; public getKeyframes(): java.util.List<com.airbnb.lottie.value.Keyframe<any>>; public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,any>; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module animatable { export class AnimatableTextFrame extends com.airbnb.lottie.model.animatable.BaseAnimatableValue<com.airbnb.lottie.model.DocumentData,com.airbnb.lottie.model.DocumentData> { public static class: java.lang.Class<com.airbnb.lottie.model.animatable.AnimatableTextFrame>; public isStatic(): boolean; public getKeyframes(): java.util.List<com.airbnb.lottie.value.Keyframe<any>>; public createAnimation(): com.airbnb.lottie.animation.keyframe.TextKeyframeAnimation; public constructor(param0: java.util.List<com.airbnb.lottie.value.Keyframe<com.airbnb.lottie.model.DocumentData>>); public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,any>; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module animatable { export class AnimatableTextProperties extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.model.animatable.AnimatableTextProperties>; public color: com.airbnb.lottie.model.animatable.AnimatableColorValue; public stroke: com.airbnb.lottie.model.animatable.AnimatableColorValue; public strokeWidth: com.airbnb.lottie.model.animatable.AnimatableFloatValue; public tracking: com.airbnb.lottie.model.animatable.AnimatableFloatValue; public constructor(param0: com.airbnb.lottie.model.animatable.AnimatableColorValue, param1: com.airbnb.lottie.model.animatable.AnimatableColorValue, param2: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param3: com.airbnb.lottie.model.animatable.AnimatableFloatValue); } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module animatable { export class AnimatableTransform extends java.lang.Object implements com.airbnb.lottie.animation.content.ModifierContent, com.airbnb.lottie.model.content.ContentModel { public static class: java.lang.Class<com.airbnb.lottie.model.animatable.AnimatableTransform>; public getStartOpacity(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public constructor(); public constructor(param0: com.airbnb.lottie.model.animatable.AnimatablePathValue, param1: com.airbnb.lottie.model.animatable.AnimatableValue<globalAndroid.graphics.PointF,globalAndroid.graphics.PointF>, param2: com.airbnb.lottie.model.animatable.AnimatableScaleValue, param3: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param4: com.airbnb.lottie.model.animatable.AnimatableIntegerValue, param5: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param6: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param7: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param8: com.airbnb.lottie.model.animatable.AnimatableFloatValue); public getPosition(): com.airbnb.lottie.model.animatable.AnimatableValue<globalAndroid.graphics.PointF,globalAndroid.graphics.PointF>; public getEndOpacity(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public getSkewAngle(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public toContent(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer): com.airbnb.lottie.animation.content.Content; public getRotation(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public getOpacity(): com.airbnb.lottie.model.animatable.AnimatableIntegerValue; public getAnchorPoint(): com.airbnb.lottie.model.animatable.AnimatablePathValue; public getSkew(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public getScale(): com.airbnb.lottie.model.animatable.AnimatableScaleValue; public createAnimation(): com.airbnb.lottie.animation.keyframe.TransformKeyframeAnimation; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module animatable { export class AnimatableValue<K, A> extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.model.animatable.AnimatableValue<any,any>>; /** * Constructs a new instance of the com.airbnb.lottie.model.animatable.AnimatableValue<any,any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getKeyframes(): java.util.List<com.airbnb.lottie.value.Keyframe<K>>; isStatic(): boolean; createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<K,A>; }); public constructor(); public isStatic(): boolean; public getKeyframes(): java.util.List<com.airbnb.lottie.value.Keyframe<K>>; public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<K,A>; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module animatable { export abstract class BaseAnimatableValue<V, O> extends com.airbnb.lottie.model.animatable.AnimatableValue<any,any> { public static class: java.lang.Class<com.airbnb.lottie.model.animatable.BaseAnimatableValue<any,any>>; public isStatic(): boolean; public getKeyframes(): java.util.List<com.airbnb.lottie.value.Keyframe<any>>; public createAnimation(): com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,any>; public toString(): string; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module content { export class CircleShape extends java.lang.Object implements com.airbnb.lottie.model.content.ContentModel { public static class: java.lang.Class<com.airbnb.lottie.model.content.CircleShape>; public toContent(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer): com.airbnb.lottie.animation.content.Content; public getSize(): com.airbnb.lottie.model.animatable.AnimatablePointValue; public isHidden(): boolean; public constructor(param0: string, param1: com.airbnb.lottie.model.animatable.AnimatableValue<globalAndroid.graphics.PointF,globalAndroid.graphics.PointF>, param2: com.airbnb.lottie.model.animatable.AnimatablePointValue, param3: boolean, param4: boolean); public getName(): string; public getPosition(): com.airbnb.lottie.model.animatable.AnimatableValue<globalAndroid.graphics.PointF,globalAndroid.graphics.PointF>; public isReversed(): boolean; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module content { export class ContentModel extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.model.content.ContentModel>; /** * Constructs a new instance of the com.airbnb.lottie.model.content.ContentModel interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { toContent(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer): com.airbnb.lottie.animation.content.Content; }); public constructor(); public toContent(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer): com.airbnb.lottie.animation.content.Content; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module content { export class GradientColor extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.model.content.GradientColor>; public getSize(): number; public constructor(param0: native.Array<number>, param1: native.Array<number>); public getColors(): native.Array<number>; public lerp(param0: com.airbnb.lottie.model.content.GradientColor, param1: com.airbnb.lottie.model.content.GradientColor, param2: number): void; public getPositions(): native.Array<number>; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module content { export class GradientFill extends java.lang.Object implements com.airbnb.lottie.model.content.ContentModel { public static class: java.lang.Class<com.airbnb.lottie.model.content.GradientFill>; public getGradientType(): com.airbnb.lottie.model.content.GradientType; public toContent(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer): com.airbnb.lottie.animation.content.Content; public constructor(param0: string, param1: com.airbnb.lottie.model.content.GradientType, param2: globalAndroid.graphics.Path.FillType, param3: com.airbnb.lottie.model.animatable.AnimatableGradientColorValue, param4: com.airbnb.lottie.model.animatable.AnimatableIntegerValue, param5: com.airbnb.lottie.model.animatable.AnimatablePointValue, param6: com.airbnb.lottie.model.animatable.AnimatablePointValue, param7: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param8: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param9: boolean); public getGradientColor(): com.airbnb.lottie.model.animatable.AnimatableGradientColorValue; public isHidden(): boolean; public getOpacity(): com.airbnb.lottie.model.animatable.AnimatableIntegerValue; public getStartPoint(): com.airbnb.lottie.model.animatable.AnimatablePointValue; public getEndPoint(): com.airbnb.lottie.model.animatable.AnimatablePointValue; public getFillType(): globalAndroid.graphics.Path.FillType; public getName(): string; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module content { export class GradientStroke extends java.lang.Object implements com.airbnb.lottie.model.content.ContentModel { public static class: java.lang.Class<com.airbnb.lottie.model.content.GradientStroke>; public getLineDashPattern(): java.util.List<com.airbnb.lottie.model.animatable.AnimatableFloatValue>; public getGradientType(): com.airbnb.lottie.model.content.GradientType; public getMiterLimit(): number; public getCapType(): com.airbnb.lottie.model.content.ShapeStroke.LineCapType; public getGradientColor(): com.airbnb.lottie.model.animatable.AnimatableGradientColorValue; public getEndPoint(): com.airbnb.lottie.model.animatable.AnimatablePointValue; public getJoinType(): com.airbnb.lottie.model.content.ShapeStroke.LineJoinType; public getName(): string; public toContent(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer): com.airbnb.lottie.animation.content.Content; public getWidth(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public constructor(param0: string, param1: com.airbnb.lottie.model.content.GradientType, param2: com.airbnb.lottie.model.animatable.AnimatableGradientColorValue, param3: com.airbnb.lottie.model.animatable.AnimatableIntegerValue, param4: com.airbnb.lottie.model.animatable.AnimatablePointValue, param5: com.airbnb.lottie.model.animatable.AnimatablePointValue, param6: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param7: com.airbnb.lottie.model.content.ShapeStroke.LineCapType, param8: com.airbnb.lottie.model.content.ShapeStroke.LineJoinType, param9: number, param10: java.util.List<com.airbnb.lottie.model.animatable.AnimatableFloatValue>, param11: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param12: boolean); public isHidden(): boolean; public getOpacity(): com.airbnb.lottie.model.animatable.AnimatableIntegerValue; public getStartPoint(): com.airbnb.lottie.model.animatable.AnimatablePointValue; public getDashOffset(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module content { export class GradientType { public static class: java.lang.Class<com.airbnb.lottie.model.content.GradientType>; public static LINEAR: com.airbnb.lottie.model.content.GradientType; public static RADIAL: com.airbnb.lottie.model.content.GradientType; public static valueOf(param0: string): com.airbnb.lottie.model.content.GradientType; public static valueOf(param0: java.lang.Class<any>, param1: string): java.lang.Enum<any>; public static values(): native.Array<com.airbnb.lottie.model.content.GradientType>; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module content { export class Mask extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.model.content.Mask>; public getOpacity(): com.airbnb.lottie.model.animatable.AnimatableIntegerValue; public constructor(param0: com.airbnb.lottie.model.content.Mask.MaskMode, param1: com.airbnb.lottie.model.animatable.AnimatableShapeValue, param2: com.airbnb.lottie.model.animatable.AnimatableIntegerValue, param3: boolean); public isInverted(): boolean; public getMaskMode(): com.airbnb.lottie.model.content.Mask.MaskMode; public getMaskPath(): com.airbnb.lottie.model.animatable.AnimatableShapeValue; } export module Mask { export class MaskMode { public static class: java.lang.Class<com.airbnb.lottie.model.content.Mask.MaskMode>; public static MASK_MODE_ADD: com.airbnb.lottie.model.content.Mask.MaskMode; public static MASK_MODE_SUBTRACT: com.airbnb.lottie.model.content.Mask.MaskMode; public static MASK_MODE_INTERSECT: com.airbnb.lottie.model.content.Mask.MaskMode; public static MASK_MODE_NONE: com.airbnb.lottie.model.content.Mask.MaskMode; public static valueOf(param0: java.lang.Class<any>, param1: string): java.lang.Enum<any>; public static valueOf(param0: string): com.airbnb.lottie.model.content.Mask.MaskMode; public static values(): native.Array<com.airbnb.lottie.model.content.Mask.MaskMode>; } } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module content { export class MergePaths extends java.lang.Object implements com.airbnb.lottie.model.content.ContentModel { public static class: java.lang.Class<com.airbnb.lottie.model.content.MergePaths>; public toContent(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer): com.airbnb.lottie.animation.content.Content; public constructor(param0: string, param1: com.airbnb.lottie.model.content.MergePaths.MergePathsMode, param2: boolean); public isHidden(): boolean; public getMode(): com.airbnb.lottie.model.content.MergePaths.MergePathsMode; public getName(): string; public toString(): string; } export module MergePaths { export class MergePathsMode { public static class: java.lang.Class<com.airbnb.lottie.model.content.MergePaths.MergePathsMode>; public static MERGE: com.airbnb.lottie.model.content.MergePaths.MergePathsMode; public static ADD: com.airbnb.lottie.model.content.MergePaths.MergePathsMode; public static SUBTRACT: com.airbnb.lottie.model.content.MergePaths.MergePathsMode; public static INTERSECT: com.airbnb.lottie.model.content.MergePaths.MergePathsMode; public static EXCLUDE_INTERSECTIONS: com.airbnb.lottie.model.content.MergePaths.MergePathsMode; public static valueOf(param0: java.lang.Class<any>, param1: string): java.lang.Enum<any>; public static valueOf(param0: string): com.airbnb.lottie.model.content.MergePaths.MergePathsMode; public static values(): native.Array<com.airbnb.lottie.model.content.MergePaths.MergePathsMode>; public static forId(param0: number): com.airbnb.lottie.model.content.MergePaths.MergePathsMode; } } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module content { export class PolystarShape extends java.lang.Object implements com.airbnb.lottie.model.content.ContentModel { public static class: java.lang.Class<com.airbnb.lottie.model.content.PolystarShape>; public toContent(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer): com.airbnb.lottie.animation.content.Content; public getRotation(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public getOuterRoundedness(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public isHidden(): boolean; public getType(): com.airbnb.lottie.model.content.PolystarShape.Type; public getPoints(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public getInnerRadius(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public getInnerRoundedness(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public getName(): string; public getPosition(): com.airbnb.lottie.model.animatable.AnimatableValue<globalAndroid.graphics.PointF,globalAndroid.graphics.PointF>; public getOuterRadius(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public constructor(param0: string, param1: com.airbnb.lottie.model.content.PolystarShape.Type, param2: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param3: com.airbnb.lottie.model.animatable.AnimatableValue<globalAndroid.graphics.PointF,globalAndroid.graphics.PointF>, param4: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param5: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param6: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param7: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param8: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param9: boolean); } export module PolystarShape { export class Type { public static class: java.lang.Class<com.airbnb.lottie.model.content.PolystarShape.Type>; public static STAR: com.airbnb.lottie.model.content.PolystarShape.Type; public static POLYGON: com.airbnb.lottie.model.content.PolystarShape.Type; public static values(): native.Array<com.airbnb.lottie.model.content.PolystarShape.Type>; public static valueOf(param0: java.lang.Class<any>, param1: string): java.lang.Enum<any>; public static valueOf(param0: string): com.airbnb.lottie.model.content.PolystarShape.Type; public static forValue(param0: number): com.airbnb.lottie.model.content.PolystarShape.Type; } } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module content { export class RectangleShape extends java.lang.Object implements com.airbnb.lottie.model.content.ContentModel { public static class: java.lang.Class<com.airbnb.lottie.model.content.RectangleShape>; public toContent(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer): com.airbnb.lottie.animation.content.Content; public constructor(param0: string, param1: com.airbnb.lottie.model.animatable.AnimatableValue<globalAndroid.graphics.PointF,globalAndroid.graphics.PointF>, param2: com.airbnb.lottie.model.animatable.AnimatablePointValue, param3: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param4: boolean); public getSize(): com.airbnb.lottie.model.animatable.AnimatablePointValue; public isHidden(): boolean; public getCornerRadius(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public getName(): string; public getPosition(): com.airbnb.lottie.model.animatable.AnimatableValue<globalAndroid.graphics.PointF,globalAndroid.graphics.PointF>; public toString(): string; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module content { export class Repeater extends java.lang.Object implements com.airbnb.lottie.model.content.ContentModel { public static class: java.lang.Class<com.airbnb.lottie.model.content.Repeater>; public toContent(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer): com.airbnb.lottie.animation.content.Content; public isHidden(): boolean; public getOffset(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public constructor(param0: string, param1: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param2: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param3: com.airbnb.lottie.model.animatable.AnimatableTransform, param4: boolean); public getName(): string; public getCopies(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public getTransform(): com.airbnb.lottie.model.animatable.AnimatableTransform; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module content { export class ShapeData extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.model.content.ShapeData>; public isClosed(): boolean; public getCurves(): java.util.List<com.airbnb.lottie.model.CubicCurveData>; public constructor(); public constructor(param0: globalAndroid.graphics.PointF, param1: boolean, param2: java.util.List<com.airbnb.lottie.model.CubicCurveData>); public getInitialPoint(): globalAndroid.graphics.PointF; public interpolateBetween(param0: com.airbnb.lottie.model.content.ShapeData, param1: com.airbnb.lottie.model.content.ShapeData, param2: number): void; public toString(): string; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module content { export class ShapeFill extends java.lang.Object implements com.airbnb.lottie.model.content.ContentModel { public static class: java.lang.Class<com.airbnb.lottie.model.content.ShapeFill>; public getColor(): com.airbnb.lottie.model.animatable.AnimatableColorValue; public toContent(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer): com.airbnb.lottie.animation.content.Content; public isHidden(): boolean; public getOpacity(): com.airbnb.lottie.model.animatable.AnimatableIntegerValue; public getFillType(): globalAndroid.graphics.Path.FillType; public getName(): string; public constructor(param0: string, param1: boolean, param2: globalAndroid.graphics.Path.FillType, param3: com.airbnb.lottie.model.animatable.AnimatableColorValue, param4: com.airbnb.lottie.model.animatable.AnimatableIntegerValue, param5: boolean); public toString(): string; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module content { export class ShapeGroup extends java.lang.Object implements com.airbnb.lottie.model.content.ContentModel { public static class: java.lang.Class<com.airbnb.lottie.model.content.ShapeGroup>; public toContent(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer): com.airbnb.lottie.animation.content.Content; public isHidden(): boolean; public constructor(param0: string, param1: java.util.List<com.airbnb.lottie.model.content.ContentModel>, param2: boolean); public getItems(): java.util.List<com.airbnb.lottie.model.content.ContentModel>; public getName(): string; public toString(): string; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module content { export class ShapePath extends java.lang.Object implements com.airbnb.lottie.model.content.ContentModel { public static class: java.lang.Class<com.airbnb.lottie.model.content.ShapePath>; public constructor(param0: string, param1: number, param2: com.airbnb.lottie.model.animatable.AnimatableShapeValue, param3: boolean); public toContent(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer): com.airbnb.lottie.animation.content.Content; public isHidden(): boolean; public getShapePath(): com.airbnb.lottie.model.animatable.AnimatableShapeValue; public getName(): string; public toString(): string; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module content { export class ShapeStroke extends java.lang.Object implements com.airbnb.lottie.model.content.ContentModel { public static class: java.lang.Class<com.airbnb.lottie.model.content.ShapeStroke>; public getLineDashPattern(): java.util.List<com.airbnb.lottie.model.animatable.AnimatableFloatValue>; public getColor(): com.airbnb.lottie.model.animatable.AnimatableColorValue; public constructor(param0: string, param1: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param2: java.util.List<com.airbnb.lottie.model.animatable.AnimatableFloatValue>, param3: com.airbnb.lottie.model.animatable.AnimatableColorValue, param4: com.airbnb.lottie.model.animatable.AnimatableIntegerValue, param5: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param6: com.airbnb.lottie.model.content.ShapeStroke.LineCapType, param7: com.airbnb.lottie.model.content.ShapeStroke.LineJoinType, param8: number, param9: boolean); public toContent(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer): com.airbnb.lottie.animation.content.Content; public getMiterLimit(): number; public getWidth(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public getCapType(): com.airbnb.lottie.model.content.ShapeStroke.LineCapType; public isHidden(): boolean; public getOpacity(): com.airbnb.lottie.model.animatable.AnimatableIntegerValue; public getJoinType(): com.airbnb.lottie.model.content.ShapeStroke.LineJoinType; public getDashOffset(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public getName(): string; } export module ShapeStroke { export class LineCapType { public static class: java.lang.Class<com.airbnb.lottie.model.content.ShapeStroke.LineCapType>; public static BUTT: com.airbnb.lottie.model.content.ShapeStroke.LineCapType; public static ROUND: com.airbnb.lottie.model.content.ShapeStroke.LineCapType; public static UNKNOWN: com.airbnb.lottie.model.content.ShapeStroke.LineCapType; public static values(): native.Array<com.airbnb.lottie.model.content.ShapeStroke.LineCapType>; public static valueOf(param0: java.lang.Class<any>, param1: string): java.lang.Enum<any>; public toPaintCap(): globalAndroid.graphics.Paint.Cap; public static valueOf(param0: string): com.airbnb.lottie.model.content.ShapeStroke.LineCapType; } export class LineJoinType { public static class: java.lang.Class<com.airbnb.lottie.model.content.ShapeStroke.LineJoinType>; public static MITER: com.airbnb.lottie.model.content.ShapeStroke.LineJoinType; public static ROUND: com.airbnb.lottie.model.content.ShapeStroke.LineJoinType; public static BEVEL: com.airbnb.lottie.model.content.ShapeStroke.LineJoinType; public static valueOf(param0: java.lang.Class<any>, param1: string): java.lang.Enum<any>; public toPaintJoin(): globalAndroid.graphics.Paint.Join; public static valueOf(param0: string): com.airbnb.lottie.model.content.ShapeStroke.LineJoinType; public static values(): native.Array<com.airbnb.lottie.model.content.ShapeStroke.LineJoinType>; } } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module content { export class ShapeTrimPath extends java.lang.Object implements com.airbnb.lottie.model.content.ContentModel { public static class: java.lang.Class<com.airbnb.lottie.model.content.ShapeTrimPath>; public getType(): com.airbnb.lottie.model.content.ShapeTrimPath.Type; public toContent(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.BaseLayer): com.airbnb.lottie.animation.content.Content; public isHidden(): boolean; public getEnd(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public getOffset(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public constructor(param0: string, param1: com.airbnb.lottie.model.content.ShapeTrimPath.Type, param2: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param3: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param4: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param5: boolean); public getName(): string; public getStart(): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public toString(): string; } export module ShapeTrimPath { export class Type { public static class: java.lang.Class<com.airbnb.lottie.model.content.ShapeTrimPath.Type>; public static SIMULTANEOUSLY: com.airbnb.lottie.model.content.ShapeTrimPath.Type; public static INDIVIDUALLY: com.airbnb.lottie.model.content.ShapeTrimPath.Type; public static valueOf(param0: java.lang.Class<any>, param1: string): java.lang.Enum<any>; public static values(): native.Array<com.airbnb.lottie.model.content.ShapeTrimPath.Type>; public static valueOf(param0: string): com.airbnb.lottie.model.content.ShapeTrimPath.Type; public static forId(param0: number): com.airbnb.lottie.model.content.ShapeTrimPath.Type; } } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module layer { export abstract class BaseLayer extends java.lang.Object implements com.airbnb.lottie.animation.content.DrawingContent, com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.AnimationListener, com.airbnb.lottie.model.KeyPathElement { public static class: java.lang.Class<com.airbnb.lottie.model.layer.BaseLayer>; public onValueChanged(): void; public getBounds(param0: globalAndroid.graphics.RectF, param1: globalAndroid.graphics.Matrix, param2: boolean): void; public resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; public setContents(param0: java.util.List<com.airbnb.lottie.animation.content.Content>, param1: java.util.List<com.airbnb.lottie.animation.content.Content>): void; public addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; public removeAnimation(param0: com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,any>): void; public getName(): string; public addAnimation(param0: com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,any>): void; public draw(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.Matrix, param2: number): void; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module layer { export class CompositionLayer extends com.airbnb.lottie.model.layer.BaseLayer { public static class: java.lang.Class<com.airbnb.lottie.model.layer.CompositionLayer>; public setProgress(param0: number): void; public resolveChildKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; public onValueChanged(): void; public constructor(param0: com.airbnb.lottie.LottieDrawable, param1: com.airbnb.lottie.model.layer.Layer, param2: java.util.List<com.airbnb.lottie.model.layer.Layer>, param3: com.airbnb.lottie.LottieComposition); public getBounds(param0: globalAndroid.graphics.RectF, param1: globalAndroid.graphics.Matrix, param2: boolean): void; public hasMasks(): boolean; public resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; public addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; public hasMatte(): boolean; public draw(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.Matrix, param2: number): void; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module layer { export class ImageLayer extends com.airbnb.lottie.model.layer.BaseLayer { public static class: java.lang.Class<com.airbnb.lottie.model.layer.ImageLayer>; public onValueChanged(): void; public getBounds(param0: globalAndroid.graphics.RectF, param1: globalAndroid.graphics.Matrix, param2: boolean): void; public drawLayer(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.Matrix, param2: number): void; public resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; public addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; public draw(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.Matrix, param2: number): void; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module layer { export class Layer extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.model.layer.Layer>; public getLayerType(): com.airbnb.lottie.model.layer.Layer.LayerType; public toString(param0: string): string; public constructor(param0: java.util.List<com.airbnb.lottie.model.content.ContentModel>, param1: com.airbnb.lottie.LottieComposition, param2: string, param3: number, param4: com.airbnb.lottie.model.layer.Layer.LayerType, param5: number, param6: string, param7: java.util.List<com.airbnb.lottie.model.content.Mask>, param8: com.airbnb.lottie.model.animatable.AnimatableTransform, param9: number, param10: number, param11: number, param12: number, param13: number, param14: number, param15: number, param16: com.airbnb.lottie.model.animatable.AnimatableTextFrame, param17: com.airbnb.lottie.model.animatable.AnimatableTextProperties, param18: java.util.List<com.airbnb.lottie.value.Keyframe<java.lang.Float>>, param19: com.airbnb.lottie.model.layer.Layer.MatteType, param20: com.airbnb.lottie.model.animatable.AnimatableFloatValue, param21: boolean); public isHidden(): boolean; public toString(): string; public getId(): number; } export module Layer { export class LayerType { public static class: java.lang.Class<com.airbnb.lottie.model.layer.Layer.LayerType>; public static PRE_COMP: com.airbnb.lottie.model.layer.Layer.LayerType; public static SOLID: com.airbnb.lottie.model.layer.Layer.LayerType; public static IMAGE: com.airbnb.lottie.model.layer.Layer.LayerType; public static NULL: com.airbnb.lottie.model.layer.Layer.LayerType; public static SHAPE: com.airbnb.lottie.model.layer.Layer.LayerType; public static TEXT: com.airbnb.lottie.model.layer.Layer.LayerType; public static UNKNOWN: com.airbnb.lottie.model.layer.Layer.LayerType; public static valueOf(param0: java.lang.Class<any>, param1: string): java.lang.Enum<any>; public static valueOf(param0: string): com.airbnb.lottie.model.layer.Layer.LayerType; public static values(): native.Array<com.airbnb.lottie.model.layer.Layer.LayerType>; } export class MatteType { public static class: java.lang.Class<com.airbnb.lottie.model.layer.Layer.MatteType>; public static NONE: com.airbnb.lottie.model.layer.Layer.MatteType; public static ADD: com.airbnb.lottie.model.layer.Layer.MatteType; public static INVERT: com.airbnb.lottie.model.layer.Layer.MatteType; public static UNKNOWN: com.airbnb.lottie.model.layer.Layer.MatteType; public static values(): native.Array<com.airbnb.lottie.model.layer.Layer.MatteType>; public static valueOf(param0: string): com.airbnb.lottie.model.layer.Layer.MatteType; public static valueOf(param0: java.lang.Class<any>, param1: string): java.lang.Enum<any>; } } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module layer { export class NullLayer extends com.airbnb.lottie.model.layer.BaseLayer { public static class: java.lang.Class<com.airbnb.lottie.model.layer.NullLayer>; public onValueChanged(): void; public getBounds(param0: globalAndroid.graphics.RectF, param1: globalAndroid.graphics.Matrix, param2: boolean): void; public resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; public addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; public draw(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.Matrix, param2: number): void; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module layer { export class ShapeLayer extends com.airbnb.lottie.model.layer.BaseLayer { public static class: java.lang.Class<com.airbnb.lottie.model.layer.ShapeLayer>; public resolveChildKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; public onValueChanged(): void; public getBounds(param0: globalAndroid.graphics.RectF, param1: globalAndroid.graphics.Matrix, param2: boolean): void; public resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; public addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; public draw(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.Matrix, param2: number): void; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module layer { export class SolidLayer extends com.airbnb.lottie.model.layer.BaseLayer { public static class: java.lang.Class<com.airbnb.lottie.model.layer.SolidLayer>; public onValueChanged(): void; public getBounds(param0: globalAndroid.graphics.RectF, param1: globalAndroid.graphics.Matrix, param2: boolean): void; public drawLayer(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.Matrix, param2: number): void; public resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; public addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; public draw(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.Matrix, param2: number): void; } } } } } } declare module com { export module airbnb { export module lottie { export module model { export module layer { export class TextLayer extends com.airbnb.lottie.model.layer.BaseLayer { public static class: java.lang.Class<com.airbnb.lottie.model.layer.TextLayer>; public onValueChanged(): void; public getBounds(param0: globalAndroid.graphics.RectF, param1: globalAndroid.graphics.Matrix, param2: boolean): void; public resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath): void; public addValueCallback(param0: any, param1: com.airbnb.lottie.value.LottieValueCallback<any>): void; public draw(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.Matrix, param2: number): void; } } } } } } declare module com { export module airbnb { export module lottie { export module network { export class FileExtension { public static class: java.lang.Class<com.airbnb.lottie.network.FileExtension>; public static JSON: com.airbnb.lottie.network.FileExtension; public static ZIP: com.airbnb.lottie.network.FileExtension; public extension: string; public toString(): string; public static values(): native.Array<com.airbnb.lottie.network.FileExtension>; public static forFile(param0: string): com.airbnb.lottie.network.FileExtension; public static valueOf(param0: string): com.airbnb.lottie.network.FileExtension; public tempExtension(): string; public static valueOf(param0: java.lang.Class<any>, param1: string): java.lang.Enum<any>; } } } } } declare module com { export module airbnb { export module lottie { export module network { export class NetworkCache extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.network.NetworkCache>; } } } } } declare module com { export module airbnb { export module lottie { export module network { export class NetworkFetcher extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.network.NetworkFetcher>; public fetchSync(): com.airbnb.lottie.LottieResult<com.airbnb.lottie.LottieComposition>; public static fetchSync(param0: globalAndroid.content.Context, param1: string): com.airbnb.lottie.LottieResult<com.airbnb.lottie.LottieComposition>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class AnimatablePathValueParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.AnimatablePathValueParser>; public static parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: com.airbnb.lottie.LottieComposition): com.airbnb.lottie.model.animatable.AnimatablePathValue; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class AnimatableTextPropertiesParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.AnimatableTextPropertiesParser>; public static parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: com.airbnb.lottie.LottieComposition): com.airbnb.lottie.model.animatable.AnimatableTextProperties; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class AnimatableTransformParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.AnimatableTransformParser>; public static parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: com.airbnb.lottie.LottieComposition): com.airbnb.lottie.model.animatable.AnimatableTransform; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class AnimatableValueParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.AnimatableValueParser>; public static parseFloat(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: com.airbnb.lottie.LottieComposition, param2: boolean): com.airbnb.lottie.model.animatable.AnimatableFloatValue; public static parseFloat(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: com.airbnb.lottie.LottieComposition): com.airbnb.lottie.model.animatable.AnimatableFloatValue; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class CircleShapeParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.CircleShapeParser>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class ColorParser extends com.airbnb.lottie.parser.ValueParser<java.lang.Integer> { public static class: java.lang.Class<com.airbnb.lottie.parser.ColorParser>; public static INSTANCE: com.airbnb.lottie.parser.ColorParser; public parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): any; public parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): java.lang.Integer; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class ContentModelParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.ContentModelParser>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class DocumentDataParser extends com.airbnb.lottie.parser.ValueParser<com.airbnb.lottie.model.DocumentData> { public static class: java.lang.Class<com.airbnb.lottie.parser.DocumentDataParser>; public static INSTANCE: com.airbnb.lottie.parser.DocumentDataParser; public parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): any; public parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): com.airbnb.lottie.model.DocumentData; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class FloatParser extends com.airbnb.lottie.parser.ValueParser<java.lang.Float> { public static class: java.lang.Class<com.airbnb.lottie.parser.FloatParser>; public static INSTANCE: com.airbnb.lottie.parser.FloatParser; public parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): any; public parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): java.lang.Float; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class FontCharacterParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.FontCharacterParser>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class FontParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.FontParser>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class GradientColorParser extends com.airbnb.lottie.parser.ValueParser<com.airbnb.lottie.model.content.GradientColor> { public static class: java.lang.Class<com.airbnb.lottie.parser.GradientColorParser>; public parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): any; public parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): com.airbnb.lottie.model.content.GradientColor; public constructor(param0: number); } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class GradientFillParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.GradientFillParser>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class GradientStrokeParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.GradientStrokeParser>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class IntegerParser extends com.airbnb.lottie.parser.ValueParser<java.lang.Integer> { public static class: java.lang.Class<com.airbnb.lottie.parser.IntegerParser>; public static INSTANCE: com.airbnb.lottie.parser.IntegerParser; public parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): any; public parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): java.lang.Integer; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class JsonUtils extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.JsonUtils>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class KeyframeParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.KeyframeParser>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class KeyframesParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.KeyframesParser>; public static setEndFrames(param0: java.util.List<any>): void; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class LayerParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.LayerParser>; public static parse(param0: com.airbnb.lottie.LottieComposition): com.airbnb.lottie.model.layer.Layer; public static parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: com.airbnb.lottie.LottieComposition): com.airbnb.lottie.model.layer.Layer; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class LottieCompositionMoshiParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.LottieCompositionMoshiParser>; public constructor(); public static parse(param0: com.airbnb.lottie.parser.moshi.JsonReader): com.airbnb.lottie.LottieComposition; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class LottieCompositionParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.LottieCompositionParser>; public constructor(); public static parse(param0: com.airbnb.lottie.parser.moshi.JsonReader): com.airbnb.lottie.LottieComposition; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class MaskParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.MaskParser>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class MergePathsParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.MergePathsParser>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class PathKeyframeParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.PathKeyframeParser>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class PathParser extends com.airbnb.lottie.parser.ValueParser<globalAndroid.graphics.PointF> { public static class: java.lang.Class<com.airbnb.lottie.parser.PathParser>; public static INSTANCE: com.airbnb.lottie.parser.PathParser; public parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): any; public parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): globalAndroid.graphics.PointF; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class PointFParser extends com.airbnb.lottie.parser.ValueParser<globalAndroid.graphics.PointF> { public static class: java.lang.Class<com.airbnb.lottie.parser.PointFParser>; public static INSTANCE: com.airbnb.lottie.parser.PointFParser; public parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): any; public parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): globalAndroid.graphics.PointF; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class PolystarShapeParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.PolystarShapeParser>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class RectangleShapeParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.RectangleShapeParser>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class RepeaterParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.RepeaterParser>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class ScaleXYParser extends com.airbnb.lottie.parser.ValueParser<com.airbnb.lottie.value.ScaleXY> { public static class: java.lang.Class<com.airbnb.lottie.parser.ScaleXYParser>; public static INSTANCE: com.airbnb.lottie.parser.ScaleXYParser; public parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): any; public parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): com.airbnb.lottie.value.ScaleXY; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class ShapeDataParser extends com.airbnb.lottie.parser.ValueParser<com.airbnb.lottie.model.content.ShapeData> { public static class: java.lang.Class<com.airbnb.lottie.parser.ShapeDataParser>; public static INSTANCE: com.airbnb.lottie.parser.ShapeDataParser; public parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): any; public parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): com.airbnb.lottie.model.content.ShapeData; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class ShapeFillParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.ShapeFillParser>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class ShapeGroupParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.ShapeGroupParser>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class ShapePathParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.ShapePathParser>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class ShapeStrokeParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.ShapeStrokeParser>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class ShapeTrimPathParser extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.ShapeTrimPathParser>; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export class ValueParser<V> extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.ValueParser<any>>; /** * Constructs a new instance of the com.airbnb.lottie.parser.ValueParser<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): V; }); public constructor(); public parse(param0: com.airbnb.lottie.parser.moshi.JsonReader, param1: number): V; } } } } } declare module com { export module airbnb { export module lottie { export module parser { export module moshi { export class JsonDataException extends java.lang.RuntimeException { public static class: java.lang.Class<com.airbnb.lottie.parser.moshi.JsonDataException>; } } } } } } declare module com { export module airbnb { export module lottie { export module parser { export module moshi { export class JsonEncodingException extends java.io.IOException { public static class: java.lang.Class<com.airbnb.lottie.parser.moshi.JsonEncodingException>; } } } } } } declare module com { export module airbnb { export module lottie { export module parser { export module moshi { export abstract class JsonReader extends java.lang.Object implements java.io.Closeable { public static class: java.lang.Class<com.airbnb.lottie.parser.moshi.JsonReader>; public selectName(param0: com.airbnb.lottie.parser.moshi.JsonReader.Options): number; public beginObject(): void; public nextBoolean(): boolean; public peek(): com.airbnb.lottie.parser.moshi.JsonReader.Token; public close(): void; public skipName(): void; public static of(param0: any): com.airbnb.lottie.parser.moshi.JsonReader; public endArray(): void; public getPath(): string; public beginArray(): void; public endObject(): void; public nextInt(): number; public nextName(): string; public skipValue(): void; public hasNext(): boolean; public nextDouble(): number; public nextString(): string; } export module JsonReader { export class Options extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.moshi.JsonReader.Options>; public static of(param0: native.Array<string>): com.airbnb.lottie.parser.moshi.JsonReader.Options; } export class Token { public static class: java.lang.Class<com.airbnb.lottie.parser.moshi.JsonReader.Token>; public static BEGIN_ARRAY: com.airbnb.lottie.parser.moshi.JsonReader.Token; public static END_ARRAY: com.airbnb.lottie.parser.moshi.JsonReader.Token; public static BEGIN_OBJECT: com.airbnb.lottie.parser.moshi.JsonReader.Token; public static END_OBJECT: com.airbnb.lottie.parser.moshi.JsonReader.Token; public static NAME: com.airbnb.lottie.parser.moshi.JsonReader.Token; public static STRING: com.airbnb.lottie.parser.moshi.JsonReader.Token; public static NUMBER: com.airbnb.lottie.parser.moshi.JsonReader.Token; public static BOOLEAN: com.airbnb.lottie.parser.moshi.JsonReader.Token; public static NULL: com.airbnb.lottie.parser.moshi.JsonReader.Token; public static END_DOCUMENT: com.airbnb.lottie.parser.moshi.JsonReader.Token; public static valueOf(param0: java.lang.Class<any>, param1: string): java.lang.Enum<any>; public static valueOf(param0: string): com.airbnb.lottie.parser.moshi.JsonReader.Token; public static values(): native.Array<com.airbnb.lottie.parser.moshi.JsonReader.Token>; } } } } } } } declare module com { export module airbnb { export module lottie { export module parser { export module moshi { export class JsonScope extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.moshi.JsonScope>; } } } } } } declare module com { export module airbnb { export module lottie { export module parser { export module moshi { export class JsonUtf8Reader extends com.airbnb.lottie.parser.moshi.JsonReader { public static class: java.lang.Class<com.airbnb.lottie.parser.moshi.JsonUtf8Reader>; public selectName(param0: com.airbnb.lottie.parser.moshi.JsonReader.Options): number; public beginObject(): void; public nextBoolean(): boolean; public peek(): com.airbnb.lottie.parser.moshi.JsonReader.Token; public close(): void; public skipName(): void; public endArray(): void; public beginArray(): void; public endObject(): void; public toString(): string; public nextInt(): number; public nextName(): string; public skipValue(): void; public hasNext(): boolean; public nextDouble(): number; public nextString(): string; } } } } } } declare module com { export module airbnb { export module lottie { export module parser { export module moshi { export class LinkedHashTreeMap<K, V> extends java.util.AbstractMap<any,any> implements java.io.Serializable { public static class: java.lang.Class<com.airbnb.lottie.parser.moshi.LinkedHashTreeMap<any,any>>; public put(param0: any, param1: any): any; public remove(param0: any): any; public entrySet(): java.util.Set<java.util.Map.Entry<any,any>>; public replace(param0: any, param1: any): any; public equals(param0: any): boolean; public hashCode(): number; public getOrDefault(param0: any, param1: any): any; public values(): java.util.Collection<any>; public putAll(param0: java.util.Map<any,any>): void; public isEmpty(): boolean; public remove(param0: any, param1: any): boolean; public size(): number; public putIfAbsent(param0: any, param1: any): any; public merge(param0: any, param1: any, param2: any /* any<any,any,any>*/): any; public forEach(param0: any /* any<any,any>*/): void; public computeIfAbsent(param0: any, param1: any /* any<any,any>*/): any; public get(param0: any): any; public computeIfPresent(param0: any, param1: any /* any<any,any,any>*/): any; public containsValue(param0: any): boolean; public containsKey(param0: any): boolean; public compute(param0: any, param1: any /* any<any,any,any>*/): any; public replaceAll(param0: any /* any<any,any,any>*/): void; public clear(): void; public replace(param0: any, param1: any, param2: any): boolean; public keySet(): java.util.Set<any>; } export module LinkedHashTreeMap { export class AvlBuilder<K, V> extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.moshi.LinkedHashTreeMap.AvlBuilder<any,any>>; } export class AvlIterator<K, V> extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.parser.moshi.LinkedHashTreeMap.AvlIterator<any,any>>; public next(): com.airbnb.lottie.parser.moshi.LinkedHashTreeMap.Node<K,V>; } export class EntrySet extends java.util.AbstractSet<java.util.Map.Entry<any,any>> { public static class: java.lang.Class<com.airbnb.lottie.parser.moshi.LinkedHashTreeMap.EntrySet>; public contains(param0: any): boolean; public size(): number; public iterator(): java.util.Iterator<any>; public containsAll(param0: java.util.Collection<any>): boolean; public hashCode(): number; public spliterator(): java.util.Spliterator<any>; public remove(param0: any): boolean; public clear(): void; public toArray(): native.Array<any>; public removeIf(param0: any /* any*/): boolean; public stream(): java.util.stream.Stream<any>; public addAll(param0: java.util.Collection<any>): boolean; public add(param0: any): boolean; public removeAll(param0: java.util.Collection<any>): boolean; public toArray(param0: native.Array<any>): native.Array<any>; public isEmpty(): boolean; public equals(param0: any): boolean; public iterator(): java.util.Iterator<java.util.Map.Entry<any,any>>; public retainAll(param0: java.util.Collection<any>): boolean; public parallelStream(): java.util.stream.Stream<any>; } export class KeySet extends java.util.AbstractSet<any> { public static class: java.lang.Class<com.airbnb.lottie.parser.moshi.LinkedHashTreeMap.KeySet>; public contains(param0: any): boolean; public size(): number; public iterator(): java.util.Iterator<any>; public containsAll(param0: java.util.Collection<any>): boolean; public hashCode(): number; public spliterator(): java.util.Spliterator<any>; public remove(param0: any): boolean; public clear(): void; public toArray(): native.Array<any>; public removeIf(param0: any /* any*/): boolean; public stream(): java.util.stream.Stream<any>; public addAll(param0: java.util.Collection<any>): boolean; public add(param0: any): boolean; public removeAll(param0: java.util.Collection<any>): boolean; public toArray(param0: native.Array<any>): native.Array<any>; public isEmpty(): boolean; public equals(param0: any): boolean; public retainAll(param0: java.util.Collection<any>): boolean; public parallelStream(): java.util.stream.Stream<any>; } export abstract class LinkedTreeMapIterator<T> extends java.util.Iterator<any> { public static class: java.lang.Class<com.airbnb.lottie.parser.moshi.LinkedHashTreeMap.LinkedTreeMapIterator<any>>; public hasNext(): boolean; public remove(): void; } export class Node<K, V> extends java.util.Map.Entry<any,any> { public static class: java.lang.Class<com.airbnb.lottie.parser.moshi.LinkedHashTreeMap.Node<any,any>>; public getValue(): any; public last(): com.airbnb.lottie.parser.moshi.LinkedHashTreeMap.Node<any,any>; public hashCode(): number; public getKey(): any; public first(): com.airbnb.lottie.parser.moshi.LinkedHashTreeMap.Node<any,any>; public static comparingByValue(param0: java.util.Comparator<any>): java.util.Comparator<any>; public toString(): string; public setValue(param0: any): any; public equals(param0: any): boolean; public static comparingByKey(param0: java.util.Comparator<any>): java.util.Comparator<any>; public static comparingByKey(): java.util.Comparator<any>; public static comparingByValue(): java.util.Comparator<any>; } } } } } } } declare module com { export module airbnb { export module lottie { export module utils { export abstract class BaseLottieAnimator extends globalAndroid.animation.ValueAnimator { public static class: java.lang.Class<com.airbnb.lottie.utils.BaseLottieAnimator>; public setInterpolator(param0: globalAndroid.animation.TimeInterpolator): void; public removeAllListeners(): void; public constructor(); public addListener(param0: globalAndroid.animation.Animator.AnimatorListener): void; public getStartDelay(): number; public removeListener(param0: globalAndroid.animation.Animator.AnimatorListener): void; public setDuration(param0: number): globalAndroid.animation.ValueAnimator; public removeAllUpdateListeners(): void; public addUpdateListener(param0: globalAndroid.animation.ValueAnimator.AnimatorUpdateListener): void; public setDuration(param0: number): globalAndroid.animation.Animator; public setStartDelay(param0: number): void; public removeUpdateListener(param0: globalAndroid.animation.ValueAnimator.AnimatorUpdateListener): void; } } } } } declare module com { export module airbnb { export module lottie { export module utils { export class GammaEvaluator extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.utils.GammaEvaluator>; public constructor(); public static evaluate(param0: number, param1: number, param2: number): number; } } } } } declare module com { export module airbnb { export module lottie { export module utils { export class LogcatLogger extends java.lang.Object implements com.airbnb.lottie.LottieLogger { public static class: java.lang.Class<com.airbnb.lottie.utils.LogcatLogger>; public debug(param0: string, param1: java.lang.Throwable): void; public warning(param0: string, param1: java.lang.Throwable): void; public constructor(); public warning(param0: string): void; public error(param0: string, param1: java.lang.Throwable): void; public debug(param0: string): void; } } } } } declare module com { export module airbnb { export module lottie { export module utils { export class Logger extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.utils.Logger>; public static warning(param0: string): void; public static setInstance(param0: com.airbnb.lottie.LottieLogger): void; public static debug(param0: string): void; public constructor(); public static debug(param0: string, param1: java.lang.Throwable): void; public static warning(param0: string, param1: java.lang.Throwable): void; public static error(param0: string, param1: java.lang.Throwable): void; } } } } } declare module com { export module airbnb { export module lottie { export module utils { export class LottieValueAnimator extends com.airbnb.lottie.utils.BaseLottieAnimator implements globalAndroid.view.Choreographer.FrameCallback { public static class: java.lang.Class<com.airbnb.lottie.utils.LottieValueAnimator>; public running: boolean; public setFrame(param0: number): void; public doFrame(param0: number): void; public playAnimation(): void; public setSpeed(param0: number): void; public endAnimation(): void; public getDuration(): number; public setMinAndMaxFrames(param0: number, param1: number): void; public removeFrameCallback(param0: boolean): void; public constructor(); public setMinFrame(param0: number): void; public setMaxFrame(param0: number): void; public getMinFrame(): number; public getAnimatedValue(param0: string): any; public setComposition(param0: com.airbnb.lottie.LottieComposition): void; public postFrameCallback(): void; public resumeAnimation(): void; public removeFrameCallback(): void; public getAnimatedFraction(): number; public cancel(): void; public pauseAnimation(): void; public getAnimatedValueAbsolute(): number; public getSpeed(): number; public getFrame(): number; public isRunning(): boolean; public getAnimatedValue(): any; public clearComposition(): void; public getMaxFrame(): number; public setRepeatMode(param0: number): void; public reverseAnimationSpeed(): void; } } } } } declare module com { export module airbnb { export module lottie { export module utils { export class MeanCalculator extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.utils.MeanCalculator>; public constructor(); public add(param0: number): void; public getMean(): number; } } } } } declare module com { export module airbnb { export module lottie { export module utils { export class MiscUtils extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.utils.MiscUtils>; public static addPoints(param0: globalAndroid.graphics.PointF, param1: globalAndroid.graphics.PointF): globalAndroid.graphics.PointF; public static resolveKeyPath(param0: com.airbnb.lottie.model.KeyPath, param1: number, param2: java.util.List<com.airbnb.lottie.model.KeyPath>, param3: com.airbnb.lottie.model.KeyPath, param4: com.airbnb.lottie.animation.content.KeyPathElementContent): void; public static clamp(param0: number, param1: number, param2: number): number; public constructor(); public static getPathFromData(param0: com.airbnb.lottie.model.content.ShapeData, param1: globalAndroid.graphics.Path): void; public static lerp(param0: number, param1: number, param2: number): number; public static contains(param0: number, param1: number, param2: number): boolean; } } } } } declare module com { export module airbnb { export module lottie { export module utils { export class Utils extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.utils.Utils>; public static SECOND_IN_NANOS: number; public static applyTrimPathIfNeeded(param0: globalAndroid.graphics.Path, param1: number, param2: number, param3: number): void; public static isAtLeastVersion(param0: number, param1: number, param2: number, param3: number, param4: number, param5: number): boolean; public static resizeBitmapIfNeeded(param0: globalAndroid.graphics.Bitmap, param1: number, param2: number): globalAndroid.graphics.Bitmap; public static getAnimationScale(param0: globalAndroid.content.Context): number; public static closeQuietly(param0: java.io.Closeable): void; public static getScale(param0: globalAndroid.graphics.Matrix): number; public static createPath(param0: globalAndroid.graphics.PointF, param1: globalAndroid.graphics.PointF, param2: globalAndroid.graphics.PointF, param3: globalAndroid.graphics.PointF): globalAndroid.graphics.Path; public static applyTrimPathIfNeeded(param0: globalAndroid.graphics.Path, param1: com.airbnb.lottie.animation.content.TrimPathContent): void; public static dpScale(): number; public static saveLayerCompat(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.RectF, param2: globalAndroid.graphics.Paint, param3: number): void; public static hashFor(param0: number, param1: number, param2: number, param3: number): number; public static renderPath(param0: globalAndroid.graphics.Path): globalAndroid.graphics.Bitmap; public static saveLayerCompat(param0: globalAndroid.graphics.Canvas, param1: globalAndroid.graphics.RectF, param2: globalAndroid.graphics.Paint): void; public static hasZeroScaleAxis(param0: globalAndroid.graphics.Matrix): boolean; public static isNetworkException(param0: java.lang.Throwable): boolean; } } } } } declare module com { export module airbnb { export module lottie { export module value { export class Keyframe<T> extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.value.Keyframe<any>>; public startValue: T; public endValue: T; public interpolator: globalAndroid.view.animation.Interpolator; public startFrame: number; public endFrame: java.lang.Float; public pathCp1: globalAndroid.graphics.PointF; public pathCp2: globalAndroid.graphics.PointF; public toString(): string; public isStatic(): boolean; public constructor(param0: com.airbnb.lottie.LottieComposition, param1: T, param2: T, param3: globalAndroid.view.animation.Interpolator, param4: number, param5: java.lang.Float); public containsProgress(param0: number): boolean; public getStartValueInt(): number; public getEndValueInt(): number; public getEndValueFloat(): number; public constructor(param0: T); public getStartProgress(): number; public getEndProgress(): number; public getStartValueFloat(): number; } } } } } declare module com { export module airbnb { export module lottie { export module value { export class LottieFrameInfo<T> extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.value.LottieFrameInfo<any>>; public getStartFrame(): number; public getEndFrame(): number; public getOverallProgress(): number; public constructor(); public getEndValue(): T; public getLinearKeyframeProgress(): number; public set(param0: number, param1: number, param2: T, param3: T, param4: number, param5: number, param6: number): com.airbnb.lottie.value.LottieFrameInfo<T>; public getInterpolatedKeyframeProgress(): number; public getStartValue(): T; } } } } } declare module com { export module airbnb { export module lottie { export module value { export class LottieInterpolatedFloatValue extends com.airbnb.lottie.value.LottieInterpolatedValue<java.lang.Float> { public static class: java.lang.Class<com.airbnb.lottie.value.LottieInterpolatedFloatValue>; public constructor(); public constructor(param0: any); public constructor(param0: java.lang.Float, param1: java.lang.Float); public constructor(param0: java.lang.Float, param1: java.lang.Float, param2: globalAndroid.view.animation.Interpolator); } } } } } declare module com { export module airbnb { export module lottie { export module value { export class LottieInterpolatedIntegerValue extends com.airbnb.lottie.value.LottieInterpolatedValue<java.lang.Integer> { public static class: java.lang.Class<com.airbnb.lottie.value.LottieInterpolatedIntegerValue>; public constructor(param0: java.lang.Integer, param1: java.lang.Integer); public constructor(); public constructor(param0: java.lang.Integer, param1: java.lang.Integer, param2: globalAndroid.view.animation.Interpolator); public constructor(param0: any); } } } } } declare module com { export module airbnb { export module lottie { export module value { export class LottieInterpolatedPointValue extends com.airbnb.lottie.value.LottieInterpolatedValue<globalAndroid.graphics.PointF> { public static class: java.lang.Class<com.airbnb.lottie.value.LottieInterpolatedPointValue>; public constructor(param0: globalAndroid.graphics.PointF, param1: globalAndroid.graphics.PointF); public constructor(); public constructor(param0: any); public constructor(param0: globalAndroid.graphics.PointF, param1: globalAndroid.graphics.PointF, param2: globalAndroid.view.animation.Interpolator); } } } } } declare module com { export module airbnb { export module lottie { export module value { export abstract class LottieInterpolatedValue<T> extends com.airbnb.lottie.value.LottieValueCallback<any> { public static class: java.lang.Class<com.airbnb.lottie.value.LottieInterpolatedValue<any>>; public getValue(param0: com.airbnb.lottie.value.LottieFrameInfo<any>): any; } } } } } declare module com { export module airbnb { export module lottie { export module value { export class LottieRelativeFloatValueCallback extends com.airbnb.lottie.value.LottieValueCallback<java.lang.Float> { public static class: java.lang.Class<com.airbnb.lottie.value.LottieRelativeFloatValueCallback>; public getOffset(param0: com.airbnb.lottie.value.LottieFrameInfo<java.lang.Float>): java.lang.Float; public constructor(); public getValue(param0: com.airbnb.lottie.value.LottieFrameInfo<any>): any; public constructor(param0: java.lang.Float); public constructor(param0: any); public getValue(param0: com.airbnb.lottie.value.LottieFrameInfo<java.lang.Float>): java.lang.Float; } } } } } declare module com { export module airbnb { export module lottie { export module value { export class LottieRelativeIntegerValueCallback extends com.airbnb.lottie.value.LottieValueCallback<java.lang.Integer> { public static class: java.lang.Class<com.airbnb.lottie.value.LottieRelativeIntegerValueCallback>; public getValue(param0: com.airbnb.lottie.value.LottieFrameInfo<java.lang.Integer>): java.lang.Integer; public constructor(); public getValue(param0: com.airbnb.lottie.value.LottieFrameInfo<any>): any; public getOffset(param0: com.airbnb.lottie.value.LottieFrameInfo<java.lang.Integer>): java.lang.Integer; public constructor(param0: any); } } } } } declare module com { export module airbnb { export module lottie { export module value { export class LottieRelativePointValueCallback extends com.airbnb.lottie.value.LottieValueCallback<globalAndroid.graphics.PointF> { public static class: java.lang.Class<com.airbnb.lottie.value.LottieRelativePointValueCallback>; public getOffset(param0: com.airbnb.lottie.value.LottieFrameInfo<globalAndroid.graphics.PointF>): globalAndroid.graphics.PointF; public constructor(); public getValue(param0: com.airbnb.lottie.value.LottieFrameInfo<any>): any; public constructor(param0: any); public constructor(param0: globalAndroid.graphics.PointF); public getValue(param0: com.airbnb.lottie.value.LottieFrameInfo<globalAndroid.graphics.PointF>): globalAndroid.graphics.PointF; } } } } } declare module com { export module airbnb { export module lottie { export module value { export class LottieValueCallback<T> extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.value.LottieValueCallback<any>>; public value: T; public setValue(param0: T): void; public getValueInternal(param0: number, param1: number, param2: T, param3: T, param4: number, param5: number, param6: number): T; public constructor(); public constructor(param0: T); public getValue(param0: com.airbnb.lottie.value.LottieFrameInfo<T>): T; public setAnimation(param0: com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation<any,any>): void; } } } } } declare module com { export module airbnb { export module lottie { export module value { export class ScaleXY extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.value.ScaleXY>; public equals(param0: any): boolean; public getScaleX(): number; public equals(param0: number, param1: number): boolean; public getScaleY(): number; public toString(): string; public constructor(); public set(param0: number, param1: number): void; public constructor(param0: number, param1: number); } } } } } declare module com { export module airbnb { export module lottie { export module value { export class SimpleLottieValueCallback<T> extends java.lang.Object { public static class: java.lang.Class<com.airbnb.lottie.value.SimpleLottieValueCallback<any>>; /** * Constructs a new instance of the com.airbnb.lottie.value.SimpleLottieValueCallback<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getValue(param0: com.airbnb.lottie.value.LottieFrameInfo<T>): T; }); public constructor(); public getValue(param0: com.airbnb.lottie.value.LottieFrameInfo<T>): T; } } } } } //Generics information: //com.airbnb.lottie.LottieListener:1 //com.airbnb.lottie.LottieResult:1 //com.airbnb.lottie.LottieTask:1 //com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation:2 //com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.EmptyKeyframeWrapper:1 //com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.KeyframesWrapper:1 //com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.KeyframesWrapperImpl:1 //com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation.SingleKeyframeWrapper:1 //com.airbnb.lottie.animation.keyframe.KeyframeAnimation:1 //com.airbnb.lottie.animation.keyframe.ValueCallbackKeyframeAnimation:2 //com.airbnb.lottie.model.MutablePair:1 //com.airbnb.lottie.model.animatable.AnimatableValue:2 //com.airbnb.lottie.model.animatable.BaseAnimatableValue:2 //com.airbnb.lottie.parser.ValueParser:1 //com.airbnb.lottie.parser.moshi.LinkedHashTreeMap:2 //com.airbnb.lottie.parser.moshi.LinkedHashTreeMap.AvlBuilder:2 //com.airbnb.lottie.parser.moshi.LinkedHashTreeMap.AvlIterator:2 //com.airbnb.lottie.parser.moshi.LinkedHashTreeMap.LinkedTreeMapIterator:1 //com.airbnb.lottie.parser.moshi.LinkedHashTreeMap.Node:2 //com.airbnb.lottie.value.Keyframe:1 //com.airbnb.lottie.value.LottieFrameInfo:1 //com.airbnb.lottie.value.LottieInterpolatedValue:1 //com.airbnb.lottie.value.LottieValueCallback:1 //com.airbnb.lottie.value.SimpleLottieValueCallback:1
the_stack
import { EventEmitter, Inject, Injectable, InjectionToken, Optional, SkipSelf } from '@angular/core'; import { Observable, BehaviorSubject } from 'rxjs'; import { RTFiltersService } from '../../filters/filters.service'; import { destroyAll } from '../../utilities'; import { RTStateService } from './state.service'; import { RTSortingsService } from './sortings.service'; import { OperationStatus } from '../../core/operation-status'; import { ListResponse } from '../../core/list-response'; import { AsyncSubscriber } from './async-subscriber'; import { NullObjectPager } from './null-object-pager'; import { Pager } from '../../core/pager'; import { FilterConfig } from '../../core/filter-config'; import { map } from 'rxjs/operators'; export const RTFilterTarget = new InjectionToken<any>('RTFilterTarget'); export class OperationStatusStream { public status$: Observable<OperationStatus>; } @Injectable() export class RTList { /** * Global settings of list.. * * These settings are static and their values are copied to the properties of the same name for each instance of {@link RTList} type. * * So, changing of this settings will affect all instances of {@link RTList} type that will be created after such changes. * If you want to change settings of concrete object you can use it the same name properties. */ public static settings = { /** * @see {@link RTList.keepRecordsOnLoad} */ keepRecordsOnLoad: false }; public loadStarted: EventEmitter<void> = new EventEmitter<void>(); public loadSucceed: EventEmitter<ListResponse<any> | any[]> = new EventEmitter<ListResponse<any> | any[]>(); public loadFailed: EventEmitter<any> = new EventEmitter<any>(); private filterTargets: object[] = []; constructor( private asyncSubscriber: AsyncSubscriber, @Optional() stateServices: RTStateService, // | RTStateService[], @SkipSelf() @Optional() @Inject(RTFilterTarget) filterTargets: any, private sortingsService: RTSortingsService, private filtersService: RTFiltersService ) { if (stateServices != null) { if (Array.isArray(stateServices)) { this.stateServices.push(...stateServices); } else { this.stateServices.push(stateServices); } } this.pager = new NullObjectPager(); if (filterTargets != null) { if (Array.isArray(filterTargets)) { this.filterTargets.push(...filterTargets); } else { this.filterTargets.push(filterTargets); } } } /** * Specifies that list must destroy previously loaded records immediately or keep them until data request is completed. */ public keepRecordsOnLoad: boolean = RTList.settings.keepRecordsOnLoad; /** * Can be used with `Observable` data sourceto specify that list must keep previously loaded records or destroy them when new value published */ public appendStreamedData: boolean | null = null; /** * Method for getting data. This parameter is required and its configuration is necessary. * * This method get one parameter with the settings of the request implementing {@link ListRequest} contract for the simple lists and {@link PagedListRequest} one for the paged lists. * The return value of this method should be any subscribable object which can be handled by {@link AsyncSubscriber}. * For the simple lists the response should contain array with the records. As for the paged ones, it should implement {@link ListResponse} contract. */ public fetchMethod: (requestParams: any) => any; /** * Array of elements transferred in the {@link ListResponse.items} property. */ public get items(): any[] { return (this.items$ as BehaviorSubject<any[]>).getValue(); } /** * Array of registered {@link RTStateService} instances. */ public stateServices: RTStateService[] = new Array<RTStateService>(); /** * Async implementation of @see RTList.status */ public status$: Observable<OperationStatus> = new BehaviorSubject(OperationStatus.Initial); /** * Async implementation of @see RTList.destroyed */ public destroyed$: Observable<boolean> = new BehaviorSubject(false); /** * Async implementation of @see RTList.inited */ public inited$: Observable<boolean> = new BehaviorSubject(false); /** * Async implementation of @see RTList.items */ public items$: Observable<any[]> = new BehaviorSubject([]); /** * Async implementation of @see RTList.busy */ public busy$: Observable<boolean> = this.status$.pipe(map(status => status === OperationStatus.Progress)); /** * Async implementation of @see RTList.ready */ public ready$: Observable<boolean> = this.status$.pipe(map(status => status !== OperationStatus.Progress)); private pagerInternal: Pager; /** * Configured {@link Pager} service. */ public get pager(): Pager { return this.pagerInternal; } public set pager(value: Pager) { this.filtersService.removeFilterTarget(this.pagerInternal); this.pagerInternal = value; this.filtersService.registerFilterTarget(this.pagerInternal); } /** * True if the service was already destroyed via {@link destroy} call. */ public get destroyed(): boolean { return (this.destroyed$ as BehaviorSubject<boolean>).getValue(); } /** * True if the service was already initialized via {@link init} call. */ public get inited(): boolean { return (this.inited$ as BehaviorSubject<boolean>).getValue(); } /** * Current execution status of the list. */ public get status(): OperationStatus { return (this.status$ as BehaviorSubject<OperationStatus>).getValue(); } /** * returns `true`, if there is a data request executed at the moment (i.e. {@link state} is equal to {@link ProgressState.Progress}) */ public get busy(): boolean { return this.status === OperationStatus.Progress; } /** * returns `true`, if there is no data request executed at the moment (i.e. {@link state} is NOT equal to {@link ProgressState.Progress}) */ public get ready(): boolean { return this.status !== OperationStatus.Progress; } /** * Performs initialization logic of the service. This method must be called before first use of the service. */ public init(): void { if (this.inited) { return; } this.filtersService.registerFilterTarget(...this.filterTargets); this.filtersService.registerFilterTarget(this.pager, this.sortingsService); const restoredState = {}; Object.assign(restoredState, ...this.stateServices.map((service: RTStateService) => service.getState() || {})); this.filtersService.applyParams(restoredState); (this.inited$ as BehaviorSubject<boolean>).next(true); } /** * Performs destroy logic of the list itself and all of the inner services. */ public destroy(): void { this.asyncSubscriber.destroy(); this.filtersService.destroy(); this.sortingsService.destroy(); this.clearData(); (this.destroyed$ as BehaviorSubject<boolean>).next(true); } /** * Registers passed object(s) as state service to manage the list state. */ public registerStateService(...services: RTStateService[]): void { services.forEach((service: RTStateService) => { this.stateServices.push(service); }); } /** * Removes passed object(s) from state services collection of the list. */ public removeStateService(...services: RTStateService[]): void { services.forEach((service: RTStateService) => { const index = this.stateServices.findIndex((s: RTStateService) => s === service); if (index !== -1) { this.stateServices.splice(index, 1); } }); } /** * Registers passed object(s) as filter targets in underlying {@link FiltersService} to include their configured properties as parameters to the data request. * @see {@link FiltersService.registerFilterTarget} */ public registerFilterTarget(...targets: object[]): void { this.filtersService.registerFilterTarget(...targets); } /** * @see {@link FiltersService.removeFilterTarget} */ public removeFilterTarget(...targets: object[]): void { this.filtersService.removeFilterTarget(...targets); } /** * @see {@link FiltersService.getRequestState} */ public getRequestState(filterFn?: (config: FilterConfig, proposedValue: any, targetObject: object) => boolean): any { return this.filtersService.getRequestState(filterFn); } /** * Resets the list parameters (sortings, paging, filters) to their default values. */ public resetSettings(): void { this.asyncSubscriber.detach(); this.filtersService.resetValues(); this.pager.reset(); this.clearData(); (this.status$ as BehaviorSubject<OperationStatus>).next(OperationStatus.Initial); } /** * Cancels the request executed at the moment. */ public cancelRequests(): void { if (this.busy || this.appendStreamedData !== null) { this.asyncSubscriber.detach(); (this.status$ as BehaviorSubject<OperationStatus>).next(OperationStatus.Cancelled); this.clearData(); } } /** * Clears {@link items} array. Calls {@link destroyAll} method for {@link items} array to perform optional destroy logic of the elements. * {@see destroyAll} */ public clearData(): void { destroyAll(this.items); (this.items$ as BehaviorSubject<any[]>).next([]); } /** * Performs data loading by calling specified {@link fetchMethod} delegate. * @return result of {@link fetchMethod} execution. */ public loadData(): Observable<any> | Promise<any> | EventEmitter<any> { if (this.busy) { return null; } this.loadStarted.emit(); const subscribable = this.beginRequest(); this.tryCleanItemsOnLoad(false); this.asyncSubscriber.attach(subscribable, this.loadDataSuccessCallback, this.loadDataFailCallback); this.stateServices.forEach((service: RTStateService) => { service.persistState(this.filtersService); }); return subscribable; } /** * Resets paging parameters and performs data loading by calling {@link loadData} if list not in {@link OperationStatus.Progress} state. * @return result of {@link fetchMethod} if it was called. `null` otherwise. */ public reloadData(): Observable<any> | Promise<any> | EventEmitter<any> { if (this.busy) { return null; } this.loadStarted.emit(); this.pager.reset(); const subscribable = this.beginRequest(); this.tryCleanItemsOnReload(false); this.asyncSubscriber.attach(subscribable, this.reloadDataSuccessCallback, this.reloadDataFailCallback); this.stateServices.forEach((service: RTStateService) => { service.persistState(this.filtersService); }); return subscribable; } /** * Callback which is executed if {@link fetchMethod} execution finished successfully. */ public loadSuccessCallback(response: ListResponse<any> | any[]): ListResponse<any> | any[] { const items = Array.isArray(response) ? response : response.items; (this.items$ as BehaviorSubject<any[]>).next(this.items.concat(items)); this.pager.processResponse(response); // In case when filter changed from last request and there's no data now // Don't do this for flat responses since we don't know real count items if (!Array.isArray(response) && this.pager.totalCount === 0) { this.clearData(); this.pager.reset(); } (this.status$ as BehaviorSubject<OperationStatus>).next( this.pager.totalCount === 0 && this.items.length === 0 ? OperationStatus.NoData : OperationStatus.Done ); this.loadSucceed.emit(response); return response; } /** * Callback which is executed if {@link fetchMethod} execution finished with error. */ public loadFailCallback(): void { this.tryCleanItemsOnLoad(true); (this.status$ as BehaviorSubject<OperationStatus>).next(OperationStatus.Fail); this.loadFailed.emit(); } private loadDataSuccessCallback = (response: ListResponse<any> | any[]): ListResponse<any> | any[] => { if (this.tryInterceptStatusResponse(response)) { return response; } this.tryCleanItemsOnLoad(true); return this.loadSuccessCallback(response); }; private reloadDataSuccessCallback = (response: ListResponse<any> | any[]): ListResponse<any> | any[] => { if (this.tryInterceptStatusResponse(response)) { return response; } this.tryCleanItemsOnReload(true); return this.loadSuccessCallback(response); }; private loadDataFailCallback = (): void => { this.tryCleanItemsOnLoad(true); this.loadFailCallback(); }; private tryInterceptStatusResponse(response: any): boolean { if (this.responseHasStatus(response)) { switch (response.status) { case OperationStatus.Fail: this.reloadDataFailCallback(); return true; case OperationStatus.Cancelled: this.cancelRequests(); return true; case OperationStatus.Progress: return true; } } return false; } private reloadDataFailCallback = (): void => { this.tryCleanItemsOnReload(true); this.loadFailCallback(); }; private tryCleanItemsOnLoad(requestCompleted: boolean): void { if (this.keepRecordsOnLoad === requestCompleted && this.pager.appendedOnLoad === false) { this.clearData(); } if (requestCompleted && this.appendStreamedData === false) { this.clearData(); } } private tryCleanItemsOnReload(requestCompleted: boolean): void { if (this.keepRecordsOnLoad === requestCompleted) { this.clearData(); } if (requestCompleted && this.appendStreamedData === false) { this.clearData(); } } private beginRequest(): any { (this.status$ as BehaviorSubject<OperationStatus>).next(OperationStatus.Progress); const requestState = this.filtersService.getRequestState(); return this.fetchMethod(requestState); } private responseHasStatus(response: ListResponse<any> | any[]): boolean { return (response as ListResponse<any>).status !== null && typeof (response as ListResponse<any>).status !== 'undefined'; } } export let LIST_PROVIDERS: any[] = [AsyncSubscriber, RTList, RTFiltersService, RTSortingsService, { provide: OperationStatusStream, useExisting: RTList }];
the_stack
import { Connectors } from './vulcan-lib/connectors'; import { createMutator, updateMutator } from './vulcan-lib/mutators'; import Votes from '../lib/collections/votes/collection'; import { userCanDo } from '../lib/vulcan-users/permissions'; import { recalculateScore } from '../lib/scoring'; import { voteTypes } from '../lib/voting/voteTypes'; import { voteCallbacks, VoteDocTuple, getVotePower } from '../lib/voting/vote'; import { getVotingSystemForDocument, VotingSystem } from '../lib/voting/votingSystems'; import { algoliaExportById } from './search/utils'; import { createAnonymousContext } from './vulcan-lib/query'; import moment from 'moment'; import { randomId } from '../lib/random'; import * as _ from 'underscore'; import sumBy from 'lodash/sumBy' import uniq from 'lodash/uniq'; import keyBy from 'lodash/keyBy'; // Test if a user has voted on the server const getExistingVote = async ({ document, user }: { document: DbVoteableType, user: DbUser, }) => { const vote = await Connectors.get(Votes, { documentId: document._id, userId: user._id, cancelled: false, }, {}, true); return vote; } // Add a vote of a specific type on the server const addVoteServer = async ({ document, collection, voteType, extendedVote, user, voteId, context }: { document: DbVoteableType, collection: CollectionBase<DbVoteableType>, voteType: string, extendedVote: any, user: DbUser, voteId: string, context: ResolverContext, }): Promise<VoteDocTuple> => { // create vote and insert it const partialVote = createVote({ document, collectionName: collection.options.collectionName, voteType, extendedVote, user, voteId }); const {data: vote} = await createMutator({ collection: Votes, document: partialVote, validate: false, }); let newDocument = { ...document, ...(await recalculateDocumentScores(document, context)), } // update document score & set item as active await collection.rawUpdateOne( {_id: document._id}, { $set: { inactive: false, baseScore: newDocument.baseScore, score: newDocument.score, extendedScore: newDocument.extendedScore, }, }, {} ); void algoliaExportById(collection as any, newDocument._id); return {newDocument, vote}; } // Create new vote object export const createVote = ({ document, collectionName, voteType, extendedVote, user, voteId }: { document: VoteableType, collectionName: CollectionNameString, voteType: string, extendedVote: any, user: DbUser|UsersCurrent, voteId?: string, }): Partial<DbVote> => { if (!document.userId) throw new Error("Voted-on document does not have an author userId?"); return { // when creating a vote from the server, voteId can sometimes be undefined ...(voteId ? {_id:voteId} : undefined), documentId: document._id, collectionName, userId: user._id, voteType: voteType, extendedVoteType: extendedVote, power: getVotePower({user, voteType, document}), votedAt: new Date(), authorId: document.userId, cancelled: false, documentIsAf: !!(document.af), } }; // Clear all votes for a given document and user (server) export const clearVotesServer = async ({ document, user, collection, excludeLatest, context }: { document: DbVoteableType, user: DbUser, collection: CollectionBase<DbVoteableType>, // If true, clears all votes except the latest (ie, only clears duplicate // votes). If false, clears all votes (including the latest). excludeLatest?: boolean, context: ResolverContext, }) => { let newDocument = _.clone(document); const votes = await Connectors.find(Votes, { documentId: document._id, userId: user._id, cancelled: false, }); if (votes.length) { const latestVoteId = _.max(votes, v=>v.votedAt)?._id; for (let vote of votes) { if (excludeLatest && vote._id === latestVoteId) { continue; } // Cancel the existing votes await updateMutator({ collection: Votes, documentId: vote._id, set: { cancelled: true }, unset: {}, validate: false, }); //eslint-disable-next-line no-unused-vars const {_id, ...otherVoteFields} = vote; // Create an un-vote for each of the existing votes const unvote = { ...otherVoteFields, cancelled: true, isUnvote: true, power: -vote.power, votedAt: new Date(), }; await createMutator({ collection: Votes, document: unvote, validate: false, }); await voteCallbacks.cancelSync.runCallbacks({ iterator: {newDocument, vote}, properties: [collection, user] }); await voteCallbacks.cancelAsync.runCallbacksAsync( [{newDocument, vote}, collection, user] ); } const newScores = await recalculateDocumentScores(document, context); await collection.rawUpdateOne( {_id: document._id}, { $set: {...newScores }, }, {} ); newDocument = { ...newDocument, ...newScores, }; void algoliaExportById(collection as any, newDocument._id); } return newDocument; } // Server-side database operation export const performVoteServer = async ({ documentId, document, voteType, extendedVote, collection, voteId = randomId(), user, toggleIfAlreadyVoted = true, context }: { documentId?: string, document?: DbVoteableType|null, voteType: string, extendedVote?: any, collection: CollectionBase<DbVoteableType>, voteId?: string, user: DbUser, toggleIfAlreadyVoted?: boolean, context?: ResolverContext, }) => { if (!context) context = await createAnonymousContext(); const collectionName = collection.options.collectionName; document = document || await Connectors.get(collection, documentId); if (!document) throw new Error("Error casting vote: Document not found."); const collectionVoteType = `${collectionName.toLowerCase()}.${voteType}` if (!user) throw new Error("Error casting vote: Not logged in."); if (!extendedVote && voteType && voteType !== "neutral" && !userCanDo(user, collectionVoteType)) { throw new Error(`Error casting vote: User can't cast votes of type ${collectionVoteType}.`); } if (!voteTypes[voteType]) throw new Error(`Invalid vote type in performVoteServer: ${voteType}`); if (collectionName==="Revisions" && (document as DbRevision).collectionName!=='Tags') throw new Error("Revisions are only voteable if they're revisions of tags"); const existingVote = await getExistingVote({document, user}); if (existingVote && existingVote.voteType === voteType && !extendedVote) { if (toggleIfAlreadyVoted) { document = await clearVotesServer({document, user, collection, context}) } } else { await checkRateLimit({ document, collection, voteType, user }); let voteDocTuple: VoteDocTuple = await addVoteServer({document, user, collection, voteType, extendedVote, voteId, context}); voteDocTuple = await voteCallbacks.castVoteSync.runCallbacks({ iterator: voteDocTuple, properties: [collection, user] }); document = voteDocTuple.newDocument; document = await clearVotesServer({ document, user, collection, excludeLatest: true, context }) void voteCallbacks.castVoteAsync.runCallbacksAsync( [voteDocTuple, collection, user] ); } (document as any).__typename = collection.options.typeName; return document; } const getVotingRateLimits = async (user: DbUser|null) => { if (user?.isAdmin) { // Very lax rate limiting for admins return { perDay: 100000, perHour: 50000, perUserPerDay: 50000 } } return { perDay: 200, perHour: 100, perUserPerDay: 100, }; } // Check whether a given vote would exceed voting rate limits, and if so, throw // an error. Otherwise do nothing. const checkRateLimit = async ({ document, collection, voteType, user }: { document: DbVoteableType, collection: CollectionBase<DbVoteableType>, voteType: string, user: DbUser }): Promise<void> => { // No rate limit on self-votes if(document.userId === user._id) return; const rateLimits = await getVotingRateLimits(user); // Retrieve all non-cancelled votes cast by this user in the past 24 hours const oneDayAgo = moment().subtract(1, 'days').toDate(); const votesInLastDay = await Votes.find({ userId: user._id, authorId: {$ne: user._id}, // Self-votes don't count votedAt: {$gt: oneDayAgo}, cancelled:false }).fetch(); if (votesInLastDay.length >= rateLimits.perDay) { throw new Error("Voting rate limit exceeded: too many votes in one day"); } const oneHourAgo = moment().subtract(1, 'hours').toDate(); const votesInLastHour = _.filter(votesInLastDay, vote=>vote.votedAt >= oneHourAgo); if (votesInLastHour.length >= rateLimits.perHour) { throw new Error("Voting rate limit exceeded: too many votes in one hour"); } const votesOnThisAuthor = _.filter(votesInLastDay, vote=>vote.authorId===document.userId); if (votesOnThisAuthor.length >= rateLimits.perUserPerDay) { throw new Error("Voting rate limit exceeded: too many votes today on content by this author"); } } function voteHasAnyEffect(votingSystem: VotingSystem, vote: DbVote, af: boolean) { if (votingSystem.name !== "default") { // If using a non-default voting system, include neutral votes in the vote // count, because they may have an effect that's not captured in their power. return true; } if (af) { return !!vote.afPower; } else { return !!vote.power; } } export const recalculateDocumentScores = async (document: VoteableType, context: ResolverContext) => { const votes = await Votes.find( { documentId: document._id, cancelled: false } ).fetch() || []; const userIdsThatVoted = uniq(votes.map(v=>v.userId)); const usersThatVoted = await context.loaders.Users.loadMany(userIdsThatVoted); const usersThatVotedById = keyBy(usersThatVoted, u=>u._id); const afVotes = _.filter(votes, v=>userCanDo(usersThatVotedById[v.userId], "votes.alignment")); const votingSystem = await getVotingSystemForDocument(document, context); const nonblankVoteCount = votes.filter(v => (!!v.voteType && v.voteType !== "neutral") || votingSystem.isNonblankExtendedVote(v)).length; const baseScore = sumBy(votes, v=>v.power) const afBaseScore = sumBy(afVotes, v=>v.afPower) const voteCount = _.filter(votes, v=>voteHasAnyEffect(votingSystem, v, false)).length; const afVoteCount = _.filter(afVotes, v=>voteHasAnyEffect(votingSystem, v, true)).length; return { baseScore, afBaseScore, voteCount: voteCount, afVoteCount: afVoteCount, extendedScore: await votingSystem.computeExtendedScore(votes, context), afExtendedScore: await votingSystem.computeExtendedScore(afVotes, context), score: recalculateScore({...document, baseScore}) }; }
the_stack
import should from "should"; import Adapt, { Group, handle, Sequence, SFCBuildProps, SFCDeclProps, useAsync, useBuildHelpers, useDeployedWhen, useMethod, useMethodFrom, waiting } from "@adpt/core"; import { k8sutils, minikubeMocha, mochaTmpdir, TODO_platform } from "@adpt/testutils"; import { waitForNoThrow } from "@adpt/utils"; import fs from "fs-extra"; import path from "path"; import { OmitT, WithPartialT } from "type-ops"; import { createActionPlugin } from "../../src/action"; import { isExecaError } from "../../src/common"; import Container from "../../src/Container"; import { DockerContainer, DockerContainerProps, LocalDockerImage, LocalDockerRegistry } from "../../src/docker"; import { dockerRun, execDocker } from "../../src/docker/cli"; import { deleteAllContainers, deleteAllImages, deployIDFilter } from "../docker/common"; import { mkInstance } from "../run_minikube"; import { MockDeploy } from "../testlib"; import { forceK8sObserverSchemaLoad } from "./testlib"; import { ClusterInfo, Kubeconfig, ServiceDeployment } from "../../src/k8s"; const { deleteAll, getAll } = k8sutils; async function killHupDockerd(fixture: minikubeMocha.MinikubeFixture) { const info = await fixture.info; const contId = info.container.id; await execDocker(["exec", contId, "killall", "-HUP", "dockerd"], { dockerHost: process.env.DOCKER_HOST }); } async function revertDaemonJson(fixture: minikubeMocha.MinikubeFixture, oldDaemonJSON: string | null | undefined) { if (oldDaemonJSON === undefined) return; await installDaemonJSON(fixture, oldDaemonJSON); } async function installDaemonJSON(fixture: minikubeMocha.MinikubeFixture, daemonJSON: string | null) { const info = await fixture.info; const contId = info.container.id; let oldDaemonJSON: string | null = null; try { const result = await execDocker(["exec", contId, "cat", `/etc/docker/daemon.json`], { dockerHost: process.env.DOCKER_HOST }); oldDaemonJSON = result.stdout; } catch (e) { if (isExecaError(e) && e.stderr && e.stderr.startsWith("cat: can't open '/etc/docker/daemon.json'")) { oldDaemonJSON = null; } else { throw e; } } if (daemonJSON === null) { await execDocker(["exec", contId, "rm", "/etc/docker/daemon.json"], { dockerHost: process.env.DOCKER_HOST }); await killHupDockerd(fixture); } else { await fs.writeFile("daemon.json", daemonJSON); await execDocker(["cp", "daemon.json", `${contId}:/etc/docker/daemon.json`], { dockerHost: process.env.DOCKER_HOST }); await killHupDockerd(fixture); await fs.remove("daemon.json"); } return oldDaemonJSON; } const pending = Symbol("value-pending"); type Pending = typeof pending; describe("k8s ServiceDeployment tests", function () { this.timeout(60 * 1000); let clusterInfo: ClusterInfo; let client: k8sutils.KubeClient; let pluginDir: string; let mockDeploy: MockDeploy; let oldDaemonJSON: string | null | undefined; mochaTmpdir.all(`adapt-cloud-k8s-ServiceDeployment`); before(async function () { this.timeout(mkInstance.setupTimeoutMs); this.slow(20 * 1000); clusterInfo = { kubeconfig: await mkInstance.kubeconfig as Kubeconfig }; client = await mkInstance.client; pluginDir = path.join(process.cwd(), "plugins"); forceK8sObserverSchemaLoad(); }); beforeEach(async () => { await fs.remove(pluginDir); mockDeploy = new MockDeploy({ pluginCreates: [createActionPlugin], tmpDir: pluginDir, uniqueDeployID: true }); await mockDeploy.init(); }); afterEach(async function () { this.timeout(40 * 1000); if (client) { const filter = deployIDFilter(mockDeploy.deployID); await Promise.all([ deleteAll("deployments", { client, deployID: mockDeploy.deployID, apiPrefix: "apis/apps/v1" }), deleteAllContainers(filter), ]); await deleteAllImages(filter); } await revertDaemonJson(mkInstance, oldDaemonJSON); }); it("should push container to private registry and run in k8s", async function () { // TODO: Failures due to container networking TODO_platform(this, "win32"); const timeout = 300 * 1000; this.timeout(timeout); const dockerNetwork = (await mkInstance.info).network; const dockerNetworkId = dockerNetwork && dockerNetwork.id; interface LocalDindContainerProps extends OmitT<WithPartialT<DockerContainerProps, "dockerHost">, "image"> { daemonConfig: object | Pending; } function LocalDindContainer(propsIn: SFCDeclProps<LocalDindContainerProps>) { const { handle: hand, ...props } = propsIn as SFCBuildProps<LocalDindContainerProps>; const dindImg = handle(); const dind = handle(); const helpers = useBuildHelpers(); const ipAddr = useMethod<string | undefined>(dind, undefined, "dockerIP", props.networks && props.networks[0]); useMethodFrom(dind, "dockerIP"); const dockerHost = props.dockerHost; useDeployedWhen(async () => { let reason: string; if (props.daemonConfig && props.daemonConfig === pending) reason = `Waiting for daemonConfig`; else if (ipAddr) { try { await dockerRun({ autoRemove: true, background: false, image: "busybox:1", dockerHost, command: ["wget", "--spider", `http://${ipAddr}:2375/info`], }); return true; } catch (err) { reason = err.message; } } else { reason = "No IP address for container"; } return waiting(`Waiting for DIND to become ready (${reason})`); }); if (props.daemonConfig && props.daemonConfig === pending) return null; const img = <LocalDockerImage handle={dindImg} dockerfile={` FROM docker:dind COPY --from=files /daemon.json /etc/docker/daemon.json `} files={[{ path: "/daemon.json", contents: JSON.stringify(props.daemonConfig) }]} options={{ imageName: "adapt-test-service-deployment-dind", uniqueTag: true }} />; const contProps = { ...props, handle: dind, image: dindImg, environment: { DOCKER_TLS_CERTDIR: "" }, privileged: true, restartPolicy: { name: "Always" } as const, }; const cont = <DockerContainer {...contProps} />; hand.replaceTarget(cont, helpers); return <Group> {img} {cont} </Group>; } let configInstalled = false; function TestBench() { const reg = handle(); const testImg = handle(); const dind = handle(); const registryInternal = useMethod<string | undefined>(reg, undefined, "registry", dockerNetworkId); //const dindPorts = useMethod<number[] | undefined>(reg, undefined, "exposedPorts"); const unusedRegistryPort = 23421; const daemonConfig = registryInternal === undefined ? pending : { "insecure-registries": [registryInternal] }; useAsync(async () => { if (!configInstalled && registryInternal !== undefined) { const oldConfig = await installDaemonJSON(mkInstance, JSON.stringify(daemonConfig)); configInstalled = true; await fs.writeFile("oldDaemonJSON.json", JSON.stringify(oldConfig)); } }, undefined); const networks = ["bridge"]; if (dockerNetworkId) networks.push(dockerNetworkId); const dindIP = useMethod(dind, "dockerIP"); return <Sequence> <LocalDockerRegistry handle={reg} port={unusedRegistryPort} networks={networks} /> <LocalDindContainer handle={dind} daemonConfig={daemonConfig} networks={networks} /> <LocalDockerImage handle={testImg} dockerfile={` FROM alpine:3.8 CMD ["sleep", "3600"] `} options={{ dockerHost: `${dindIP}:2375`, imageName: "adapt-test-service-deployment-testimg", uniqueTag: true }} /> <ServiceDeployment podProps={{ terminationGracePeriodSeconds: 0 }} config={{ //FIXME(manishv) This is technically wrong, //but I know earlier state loop turns will ensure registryInternal !== pending //by the time we get here and need to deploy this component registryPrefix: registryInternal, ...clusterInfo }}> <Container name="foo" image={testImg} /> </ServiceDeployment> </Sequence >; } const orig = <TestBench />; const { dom } = await mockDeploy.deploy(orig, { timeoutInMs: this.timeout() ? timeout : undefined, }); oldDaemonJSON = JSON.parse((await fs.readFile("oldDaemonJSON.json")).toString()); should(dom).not.Null(); await waitForNoThrow(10, 1, async () => { const pods = await getAll("pods", { client, deployID: mockDeploy.deployID }); should(pods).length(1); const pod = pods[0]; should(pod).have.keys("status"); const status = pod.status; should(status).have.keys("containerStatuses"); const containerStatuses = status.containerStatuses; should(containerStatuses).length(1); should(containerStatuses[0]).have.key("state"); should(containerStatuses[0].state).have.key("running"); }); }); });
the_stack
import { h, Fragment } from 'https://unpkg.com/preact@10.5.12?module'; import { useState, useEffect } from 'https://unpkg.com/preact@10.5.12/hooks/dist/hooks.module.js?module'; // import components import FieldView from '../fieldView/FieldView.tsx'; import * as helpers from './helpers.tsx'; // import type definitions import { ActiveCollectionProps } from './interface.ts'; /******************************************************************************************* */ /** * @description This component renders all details for the active collection. * Gives option to add new entry, delete entry & edit values of entry. * * @param activeCollection - currently selected collection from sidebar (string) * * @param refreshCollections - a function which refreshes the active collections * by making a new request to api. Forces any newly added or edited entries to display * * @param resultsView - a boolean which determines whether all of the entries in a collection * should be displayed or just an individual entry * * @param handleResultsView -a function for setting the resultsView depending on wether it is * invoked with true or false */ const ActiveCollection = ({ activeCollection, refreshCollections, resultsView, handleResultsView }: ActiveCollectionProps) => { // holds the current page the user is on, defaults to 1 const [activePage, setActivePage] = useState('1'); // holds the selected number of results to display per page - options are 10, 20, 50 const [activeResultsPerPage, setActiveResultsPerPage] = useState('10'); // holds array of arrays, where each nested array holds two elements, // the first element being the field name, and the second // element being the data type tied to the field const [headers, setHeaders] = useState([[]]); // holds an array containing all the entries in the selected collection const [entries, setEntries] = useState([]); // an object containing the data for the selected entry const [activeEntry, setActiveEntry] = useState({}); // a boolean representing whether or not this is a new entry being created or // an active entry being edited/updated const [newEntry, setNewEntry] = useState(false); // a boolean which determines the state of the confirm delete popup // open (true) or closed (false) - defaults to false const [deletePopup, setDeletePopup] = useState(false); // holds state of api request for updating or adding new entry const [saveFail, setSaveFail] = useState(false); // holds state of api request for updating or adding new entry const [saveSuccess, setSaveSuccess] = useState(false); // holds state of api request for updating or adding new entry const [loading, setLoading] = useState(false); /******************************************************************************************* */ // invoked when updates to resultsView are recognized // a request is made to get all entries in the selected collection // and headers and entries arrays are updated with the response data // // activePage is reset to '1' - the default and handleResultsView // is invoked with true, updating resultsView and // telling the application to display all collection results useEffect(() => { fetch(`/api/tables/${activeCollection}`) .then((data) => data.json()) .then((res) => { // console.log('res.data.columns: ', res.data.rows) const headers = res.data.columns.map( (header: any) => [header.column_name, header.data_type] ); const entries = res.data.rows; setActivePage('1'); setHeaders(headers); setEntries(entries); }) .catch((error) => console.log('error', error)); }, [resultsView]); // invoked when updates to activeCollection are recognized // a request is made to get all entries in the selected collection // and headers and entries arrays are updated with the response data // // activePage is reset to '1' - the default and handleResultsView // is invoked with true, updating resultsView and // telling the application to display all collection results useEffect(() => { if (activeCollection === undefined) return; fetch(`/api/tables/${activeCollection}`) .then((data) => data.json()) .then((res) => { // console.log('res.data.columns: ', res.data.rows) const headers = res.data.columns.map( (header: any) => [header.column_name, header.data_type] ); const entries = res.data.rows; setActivePage('1'); handleResultsView(true); setHeaders(headers); setEntries(entries); }) .catch((error) => console.log('error', error)); }, [activeCollection]); // updates state variables on click of add new entry button const createEntry = (e: any) => { const entry: any = {}; headers.forEach((header: Array<string>) => { // this creates a property on entry object, // with key being the header (field name), and // value being an array containing three elements [input value, data type, error message] // input and error message start as empty strings because they will be updated and held in state // when user changes the input fields in field view entry[header[0]] = ['', header[1], '']; }); setActiveEntry(entry); // tells application that a new entry is being created here setNewEntry(true); // tells application that the individual field view should be displayed handleResultsView(false); }; // function which updates state variables when an entry is selected // to be edited const updateEntry = (e: any) => { const data: any = {}; const length = e.target.parentNode.children.length; let count = 0; while (count < length) { const value = e.target.parentNode.children[count].textContent; // this creates a property on data object, // with key being the header (field name), and // value being an array containing three elements [input value, data type, error message] // error message starts as empty strings because it will be updated and held in state when // an error is recognized in the input field. data[headers[count][0]] = [value, headers[count][1], '']; count += 1; } setActiveEntry(data); setNewEntry(false); handleResultsView(false); }; // handles click to a different page const handlePageClick = (event: any) => { const text = event.target.innerText; switch (text) { // handle back arrow clicks case '«': if (activePage === '1') break; const leftNum = String(Number(activePage) - 1); setActivePage(leftNum); break; // handle forward arrow clicks case '»': const pageCount = Math.ceil( entries.length / Number(activeResultsPerPage) ); if (Number(activePage) === pageCount) break; const rightNum = String(Number(activePage) + 1); setActivePage(rightNum); break; default: setActivePage(text); break; } }; // function which handles click to set the amount of results shown per page const handleResultsPerPageClick = (event: any) => { const text = event.target.innerText; setActivePage('1'); setActiveResultsPerPage(text); }; // function which renders the confirm delete popup which displays when a user // clicks the delete button, and allows user to confirm or cancel the request // to delete the active collection const ConfirmDelete = () => { // declare variable which will hold the correct loading svg to render based on loading state let loader; // if loading is true set loader to loading spinner if (loading) { loader = <div className='saveFieldBtnLoader deletePopupBtnLoader'></div>; // if saveFail is true, set loader to failed svg x } else if (saveFail) { loader = ( <div> <svg className='saveFieldFailSVG deletePopupBtnLoader' xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" > <path d="M24 20.188l-8.315-8.209 8.2-8.282-3.697-3.697-8.212 8.318-8.31-8.203-3.666 3.666 8.321 8.24-8.206 8.313 3.666 3.666 8.237-8.318 8.285 8.203z"/> </svg> </div> ); // if saveSuccess is true, set loader to success svg checkmark } else if (saveSuccess) { loader = ( <svg className='saveFieldSuccessSVG deletePopupBtnLoader' xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" > <path d="M0 11c2.761.575 6.312 1.688 9 3.438 3.157-4.23 8.828-8.187 15-11.438-5.861 5.775-10.711 12.328-14 18.917-2.651-3.766-5.547-7.271-10-10.917z"/> </svg> ); }; return ( <div className='confirmDeletePopup'> <p className='confirmDeleteText'> Are you sure you want to delete <br></br><span className='confirmDeleteHighlight'>{activeCollection} </span> from <span className='confirmDeleteHighlight'> collections</span> ? </p> <div className='confirmDeleteBtnContainer'> {loader} {(!loading && !saveSuccess && !saveFail) && <p className='confirmDeleteCancel' onClick={() => setDeletePopup(false)}>cancel</p> } <button className='confirmDeleteBtn' onClick={(e: any) => handleDelete(e)}>Delete Table</button>) </div> </div> ); }; // function which handles the click of the delete button as well as the confirm // button in the confirm delete popup const handleDelete = (event: any) => { if (!deletePopup) setDeletePopup(true); // if the button in the confirm delete popup is clicked, // the event target will have a className of 'confirmDelete' // and this if statement will pass, making the request to actually // delete the collection if (event.target.className === 'confirmDeleteBtn') { setLoading(true); fetch(`/api/tables/${activeCollection}`, { method: 'DELETE' }) .then((res) => res.json()) .then((res) => { if (res.success) { const copy = activeCollection; setLoading(false); setSaveSuccess(true); setDeletePopup(false); refreshCollections(); } }) .then(() => setSaveSuccess(false)) .catch((err) => { console.log(err); setSaveFail(true); }); } }; // maps each field name to the fields array const fields = headers.map((field: any, index: number) => ( <helpers.Field activeCollection={activeCollection} fieldName={field[0]} /> )); // sets entriesCount based on length of entries const entriesCount = entries.length; let entriesPerPage; // creates object with each page as a key, and each value an array of entries // size of array and amount of pages is based on selected results per page const pagesCache: any = {}; if (entries.length) { const resultsPerPage: number = Number(activeResultsPerPage); let count: number = 0; let page: number = 1; entries.forEach((entry: any) => { if (count === resultsPerPage) { page += 1; count = 0; } if (!pagesCache[page]) pagesCache[page.toString()] = []; pagesCache[page.toString()].push(Object.values(entry)); count += 1; }); let keyCount = 0; // maps each entry based on selected page and selected page entriesPerPage = pagesCache[activePage].map( (entry: Array<string>, index: number) => { keyCount += 1; return ( <helpers.Entry values={entry} index={index} fieldNames={headers} handleClick={updateEntry} /> ); } ); } else entriesPerPage = []; // maps page numbers based on results per page and amount of entries const pagination = Object.keys(pagesCache).map((page) => { let paginationClass; page.toString() === activePage ? (paginationClass = 'collectionCurrentPage') : (paginationClass = 'collectionStalePage'); return ( <a className={paginationClass} onClick={(e: any) => handlePageClick(e)} href="#" > {page} </a> ); }); // if results view is truthy, render view which displays all entries // in selected collection if (resultsView) { return ( <div className="activeCollectionContainer"> <div className="activeCollectionHeader"> <div className="deleteContainer"> <div className="activeCollectionDetails"> <p className="activeCollectionName">{activeCollection}</p> <p className="activeCollectionCount"> {entries.length} entries found </p> </div> <div className="deleteEntrySVG" onClick={handleDelete}> <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="#bd5555" > <path d="M3 6v18h18v-18h-18zm5 14c0 .552-.448 1-1 1s-1-.448-1-1v-10c0-.552.448-1 1-1s1 .448 1 1v10zm5 0c0 .552-.448 1-1 1s-1-.448-1-1v-10c0-.552.448-1 1-1s1 .448 1 1v10zm5 0c0 .552-.448 1-1 1s-1-.448-1-1v-10c0-.552.448-1 1-1s1 .448 1 1v10zm4-18v2h-20v-2h5.711c.9 0 1.631-1.099 1.631-2h5.315c0 .901.73 2 1.631 2h5.712z" /> </svg> </div> </div> <button className="addEntryBtn" id="addNewEntryBtn" onClick={createEntry} > Add New {activeCollection} </button> </div> <div className="activeTableContainer"> {deletePopup && <ConfirmDelete /> } <table className="activeCollectionTable"> <thead> <tr> {fields} </tr> </thead> <tbody>{entriesPerPage}</tbody> </table> </div> {/* if pagination.length (pagination is an array holding hte amount of pages in a collection) * is truthy, display the pagination options on the bottom of view * if falsy, display an empty div */} {pagination.length ? ( <div className="paginationContainer"> <div className="pagination"> <a className="collectionsPaginationLeft" onClick={(e: any) => handlePageClick(e)} href="#" > &laquo; </a> {pagination} <a className="collectionsPaginationRight" onClick={(e: any) => handlePageClick(e)} href="#" > &raquo; </a> </div> <div className="resultsPerPage"> <p onClick={(e: any) => handleResultsPerPageClick(e)} className={ activeResultsPerPage === '10' ? 'activeResultsPerPage' : 'staleResultsPerPage' } > 10 </p> <p className="resultsSlash">/</p> <p onClick={(e: any) => handleResultsPerPageClick(e)} className={ activeResultsPerPage === '20' ? 'activeResultsPerPage' : 'staleResultsPerPage' } > 20 </p> <p className="resultsSlash">/</p> <p onClick={(e: any) => handleResultsPerPageClick(e)} className={ activeResultsPerPage === '50' ? 'activeResultsPerPage' : 'staleResultsPerPage' } > 50 </p> </div> </div> ) : ( <div></div> )} </div> ); // if resultsView is falsy, render the Field View, // which displays the view when an individual field is // selected, or this is a new entry beinf created } else { return ( <FieldView activeEntry={activeEntry} activeItem={activeCollection} newEntry={newEntry} collectionEntries={entries} handleResultsView={handleResultsView} /> ); } }; export default ActiveCollection;
the_stack
import AVLTree from '../../../src/data-structures/trees/avl-tree' import AVLTreeNode from '../../../src/data-structures/trees/avl-tree/avl-tree-node' describe('AVL Tree', () => { let tree: AVLTree<number> beforeEach(() => { tree = new AVLTree() }) describe('Inspection', () => { it('size()', () => { expect(tree.size()).toBe(0) }) it('isEmpty()', () => { expect(tree.isEmpty()).toBe(true) tree.insert(8) expect(tree.isEmpty()).toBe(false) }) it('height()', () => { // Tree should look like: // 10 // 5 15 // 2 12 21 // No tree expect(tree.height()).toBe(0) // Layer One tree.insert(10) expect(tree.height()).toBe(1) // Layer Two tree.insert(5) expect(tree.height()).toBe(2) tree.insert(15) expect(tree.height()).toBe(2) // Layer Three tree.insert(2) expect(tree.height()).toBe(3) tree.insert(7) expect(tree.height()).toBe(3) tree.insert(12) expect(tree.height()).toBe(3) tree.insert(21) expect(tree.height()).toBe(3) // Layer 4 tree.insert(1) expect(tree.height()).toBe(4) }) }) describe('Searching', () => { const treeB = new AVLTree<number>() const a = new AVLTreeNode(5, null) const b = new AVLTreeNode(4, a) const c = new AVLTreeNode(3, b) const d = new AVLTreeNode(2, c) const e = new AVLTreeNode(1, d) const f = new AVLTreeNode(6, a) const g = new AVLTreeNode(7, f) const h = new AVLTreeNode(8, g) a.left = b b.left = c c.left = d d.left = e a.right = f f.right = g g.right = h treeB.root = a it('find()', () => { expect(treeB.find(5)).toBe(a) expect(treeB.find(4)).toBe(b) expect(treeB.find(3)).toBe(c) expect(treeB.find(2)).toBe(d) expect(treeB.find(1)).toBe(e) expect(treeB.find(6)).toBe(f) expect(treeB.find(7)).toBe(g) expect(treeB.find(8)).toBe(h) }) it('findMin()', () => { expect(treeB.findMin()).toBe(e) }) it('findMax()', () => { expect(treeB.findMax()).toBe(h) }) it('findSucessor()', () => { expect(treeB.findSucessor(a)).toBe(f) expect(treeB.findSucessor(e)).toBe(d) expect(treeB.findSucessor(f)).toBe(g) const treeC = new AVLTree<number>() const m = new AVLTreeNode(5, null) const n = new AVLTreeNode(3, m) const o = new AVLTreeNode(2, n) const p = new AVLTreeNode(1, o) const q = new AVLTreeNode(4, n) m.left = n n.left = o o.left = p n.right = q treeC.root = m expect(treeC.findSucessor(q)).toBe(m) }) it('findPredecessor()', () => { expect(treeB.findPredecessor(a)).toBe(b) expect(treeB.findPredecessor(e)).toBe(null) expect(treeB.findPredecessor(f)).toBe(a) }) }) describe('Insertion/Deletion', () => { describe('rotations after insertion', () => { describe('left heavy', () => { it('left left simple case', () => { // 5 3 // 3 -> 1 5 // 1 tree.insert(5) expect(tree.height()).toBe(1) tree.insert(3) expect(tree.height()).toBe(2) tree.insert(1) expect(tree.height()).toBe(2) const three = tree.find(3) const one = tree.find(1) const five = tree.find(5) if (!three || !one || !five) throw new Error() expect(three.balanceFactor).toBe(0) expect(three.height).toBe(2) expect(one.balanceFactor).toBe(0) expect(one.height).toBe(1) expect(five.balanceFactor).toBe(0) expect(five.height).toBe(1) }) it('left left advanced case', () => { // Before: // 10 // 5 15 // 4 8 12 21 // 2 // 1 // After: // 10 // 5 15 // 2 8 12 21 // 1 4 // Layer One tree.insert(10) expect(tree.height()).toBe(1) // Layer Two tree.insert(5) tree.insert(15) expect(tree.height()).toBe(2) // Layer Three tree.insert(4) tree.insert(8) tree.insert(12) tree.insert(21) expect(tree.height()).toBe(3) // Layer 4 tree.insert(2) expect(tree.height()).toBe(4) tree.insert(1) expect(tree.height()).toBe(4) const two = tree.find(2) const one = tree.find(1) const four = tree.find(4) if (!two || !one || !four) throw new Error() expect(two.balanceFactor).toBe(0) expect(two.height).toBe(2) expect(one.balanceFactor).toBe(0) expect(one.height).toBe(1) expect(four.balanceFactor).toBe(0) expect(four.height).toBe(1) }) it('left right case', () => { // 5 5 4 // 3 -> 4 -> 3 5 // 4 3 tree.insert(5) expect(tree.height()).toBe(1) tree.insert(3) expect(tree.height()).toBe(2) tree.insert(4) expect(tree.height()).toBe(2) const four = tree.find(4) const three = tree.find(3) const five = tree.find(5) if (!three || !four || !five) throw new Error() expect(four.balanceFactor).toBe(0) expect(four.height).toBe(2) expect(three.balanceFactor).toBe(0) expect(three.height).toBe(1) expect(five.balanceFactor).toBe(0) expect(five.height).toBe(1) }) describe('right heavy', () => { it('right right case', () => { // 5 7 // 7 -> 5 8 // 8 tree.insert(5) expect(tree.height()).toBe(1) tree.insert(7) expect(tree.height()).toBe(2) tree.insert(8) expect(tree.height()).toBe(2) const seven = tree.find(7) const five = tree.find(8) const eight = tree.find(5) if (!seven || !five || !eight) throw new Error() expect(seven.balanceFactor).toBe(0) expect(seven.height).toBe(2) expect(five.balanceFactor).toBe(0) expect(five.height).toBe(1) expect(eight.balanceFactor).toBe(0) expect(eight.height).toBe(1) }) it('right left case', () => { // 5 5 6 // 7 -> 6 -> 5 7 // 6 7 tree.insert(5) expect(tree.height()).toBe(1) tree.insert(7) expect(tree.height()).toBe(2) tree.insert(6) expect(tree.height()).toBe(2) const six = tree.find(6) const five = tree.find(5) const seven = tree.find(7) if (!six || !five || !seven) throw new Error() expect(six.balanceFactor).toBe(0) expect(six.height).toBe(2) expect(five.balanceFactor).toBe(0) expect(five.height).toBe(1) expect(seven.balanceFactor).toBe(0) expect(seven.height).toBe(1) }) }) }) }) it('insert()', () => { tree.insert(5) expect(tree.size()).toBe(1) tree.insert(3) expect(tree.size()).toBe(2) tree.insert(2) expect(tree.size()).toBe(3) tree.insert(6) expect(tree.size()).toBe(4) tree.insert(9) expect(tree.size()).toBe(5) tree.insert(4) expect(tree.size()).toBe(6) }) describe('removal', () => { beforeEach(() => { // Before: // 10 // 5 15 // 4 8 12 21 // 2 // 1 // After: // 10 // 5 15 // 2 8 12 21 // 1 4 // Layer One tree.insert(10) // Layer Two tree.insert(5) tree.insert(15) // Layer Three tree.insert(4) tree.insert(8) tree.insert(12) tree.insert(21) // Layer 4 tree.insert(2) tree.insert(1) }) it('removes node with no children', () => { const four = tree.find(4) const two = tree.find(2) if (!four || !two) throw new Error() expect(two.balanceFactor).toBe(0) tree.remove(four) expect(tree.find(4)).toBe(null) expect(two.right).toBe(null) expect(two.balanceFactor).toBe(1) }) it('removes node with 1 left child', () => { const four = tree.find(4) const two = tree.find(2) if (!four || !two) throw new Error() expect(two.balanceFactor).toBe(0) tree.remove(four) expect(tree.find(4)).toBe(null) expect(two.right).toBe(null) expect(two.balanceFactor).toBe(1) // new part tree.remove(two) expect(tree.find(2)).toBe(null) const one = tree.find(1) if (!one) throw new Error() expect(one.balanceFactor).toBe(0) }) it('removes node with two children', () => { // Before: // 10 // 5 15 // 4 8 12 21 // 2 // 1 // After: // 10 // 5 15 // 2 8 12 21 // 1 4 6 // Layer One tree.insert(10) // Layer Two tree.insert(5) tree.insert(15) // Layer Three tree.insert(4) tree.insert(8) tree.insert(12) tree.insert(21) // Layer 4 tree.insert(2) tree.insert(1) tree.insert(6) const five = tree.find(5) if (!five) throw new Error() // 10 // XX 15 // 2 8 12 21 // 1 4 6 // 10 // 6 15 // 2 8 12 21 // 1 4 tree.remove(five) expect(tree.find(5)).toBe(null) const six = tree.find(6) if (!six || !six.right) throw new Error() expect(six.right.value).toBe(8) }) }) }) describe('Traversals', () => { const treeB = new AVLTree<number>() const a = new AVLTreeNode(5, null) const b = new AVLTreeNode(4, a) const c = new AVLTreeNode(3, b) const d = new AVLTreeNode(2, c) const e = new AVLTreeNode(1, d) const f = new AVLTreeNode(6, a) const g = new AVLTreeNode(7, f) const h = new AVLTreeNode(8, g) a.left = b b.left = c c.left = d d.left = e a.right = f f.right = g g.right = h treeB.root = a it('inorder()', () => { const inorderNumbers = [1, 2, 3, 4, 5, 6, 7, 8] let i = 0 for (const n of treeB.inorderTraversal()) { expect(n).toBe(inorderNumbers[i]) i += 1 } }) it('preorder()', () => { // Tree should look like: // 10 // 5 15 // 2 7 12 21 // // Layer One tree.insert(10) // Layer Two tree.insert(5) tree.insert(15) // Layer Three tree.insert(2) tree.insert(7) tree.insert(12) tree.insert(21) const preorderNumbers = [10, 5, 2, 7, 15, 12, 21] let i = 0 for (const n of tree.preorderTraversal()) { expect(n).toBe(preorderNumbers[i]) i += 1 } }) it('postorder()', () => { // Tree should look like: // 10 // 5 15 // 2 7 12 21 // Layer One tree.insert(10) // Layer Two tree.insert(5) tree.insert(15) // Layer Three tree.insert(2) tree.insert(7) tree.insert(12) tree.insert(21) const postorderNumbers = [2, 7, 5, 12, 21, 15, 10] let i = 0 for (const n of tree.postorderTraversal()) { expect(n).toBe(postorderNumbers[i]) i += 1 } }) }) })
the_stack
* Notes: * If a Tag's name starts with a capital letter then it can have tags within it. * If a Tag's name starts with a lower case letter then it can only have a primitive type within it. */ // TAGS // High Level Descriptions /** * ### Not Currently Supported * Distance of the camera from the earth's surface, in meters. * Interpreted according to the Camera's <altitudeMode> or <gx:altitudeMode>. */ export const ALTITUDE_TAG = 'altitude'; /** * How linestring or polygons work. * Any altitude value should be accompanied by an <altitudeMode> element, which tells Google Earth how to read the altitude value. Altitudes can be measured: * * from the surface of the Earth (relativeToGround), above sea level (absolute), * or from the bottom of major bodies of water (relativeToSeaFloor). * It can also be ignored (clampToGround and clampToSeaFloor) * * https://developers.google.com/kml/documentation/altitudemode */ export const ALTITUDE_MODE_TAG = 'altitudeMode'; /** * Specifies how the description balloon for placemarks is drawn. The <bgColor>, if specified, is used as the background color of the balloon. See <Feature> for a diagram illustrating how the default description balloon appears in Google Earth. */ export const BALLOON_STYLE_TAG = 'BalloonStyle'; /** * ### Not Supported * * Defines the virtual camera that views the scene. This element defines the position of the camera relative to the Earth's surface as well as the viewing direction of the camera. The camera position is defined by <longitude>, <latitude>, <altitude>, and either <altitudeMode> or <gx:altitudeMode>. The viewing direction of the camera is defined by <heading>, <tilt>, and <roll>. <Camera> can be a child element of any Feature or of <NetworkLinkControl>. A parent element cannot contain both a <Camera> and a <LookAt> at the same time. * * <Camera> provides full six-degrees-of-freedom control over the view, so you can position the Camera in space and then rotate it around the X, Y, and Z axes. Most importantly, you can tilt the camera view so that you're looking above the horizon into the sky. * * <Camera> can also contain a TimePrimitive (<gx:TimeSpan> or <gx:TimeStamp>). Time values in Camera affect historical imagery, sunlight, and the display of time-stamped features. For more information, read Time with AbstractViews in the Time and Animation chapter of the Developer's Guide. * * #### Defining a View * Within a Feature or <NetworkLinkControl>, use either a <Camera> or a <LookAt> object (but not both in the same object). The <Camera> object defines the viewpoint in terms of the viewer's position and orientation. The <Camera> object allows you to specify a view that is not on the Earth's surface. The <LookAt> object defines the viewpoint in terms of what is being viewed. The <LookAt> object is more limited in scope than <Camera> and generally requires that the view direction intersect the Earth's surface. * * The following diagram shows the X, Y, and Z axes, which are attached to the virtual camera. * * The X axis points toward the right of the camera and is called the right vector. * * The Y axis defines the "up" direction relative to the screen and is called the up vector. * * The Z axis points from the center of the screen toward the eye point. The camera looks down the −Z axis, which is called the view vector. */ export const CAMERA_TAG = 'Camera'; /** * Color and opacity (alpha) values are expressed in hexadecimal notation. * The range of values for any one color is 0 to 255 (00 to ff). * For alpha, 00 is fully transparent and ff is fully opaque. * The order of expression is aabbggrr, where aa=alpha (00 to ff); * bb=blue (00 to ff); gg=green (00 to ff); rr=red (00 to ff). * For example, if you want to apply a blue color with 50 percent opacity to an overlay, * you would specify the following: * <color>7fff0000</color>, where alpha=0x7f, blue=0xff, green=0x00, and red=0x00. */ export const COLOR_TAG = 'color'; /** * ### A Document is a container for features and styles. * * This element is required if your KML file uses shared styles. It is recommended that you use shared styles, which require the following steps: * Define all Styles in a Document. Assign a unique ID to each Style. * Within a given Feature or StyleMap, reference the Style's ID using a <styleUrl> element. * Note that shared styles are not inherited by the Features in the Document. * Each Feature must explicitly reference the styles it uses in a <styleUrl> element. * For a Style that applies to a Document (such as ListStyle), the Document itself must explicitly reference the <styleUrl>. * * https://developers.google.com/kml/documentation/kmlreference#document */ export const DOCUMENT_TAG = 'Document'; /** * ### A Folder is used to arrange other Features hierarchically * (Folders, Placemarks, NetworkLinks, or Overlays). * A Feature is visible only if it and all its ancestors are visible. */ export const FOLDER_TAG = 'Folder'; /** * This element draws an image overlay draped onto the terrain. * * The <href> child of <Icon> specifies the image to be used as the overlay. * This file can be either on a local file system or on a web server. * If this element is omitted or contains no <href>, a rectangle is drawn using the color and LatLonBox bounds defined by the ground overlay. * * https://developers.google.com/kml/documentation/kmlreference#geometry */ export const GROUND_OVERLAY_TAG = 'GroundOverlay'; export const ICON_STYLE_TAG = 'IconStyle'; /** * ### Defines an image associated with an Icon style or overlay. * * The required <href> child element defines the location of the image to be used as the overlay or as the icon for the placemark. * This location can either be on a local file system or a remote web server. * * https://developers.google.com/kml/documentation/kmlreference#icon */ export const ICON_TAG = 'Icon'; /** * The root element of a KML file. This element is required. * It follows the xml declaration at the beginning of the file. * The hint attribute is used as a signal to Google Earth to display the file as celestial data. * * The <kml> element may also include the namespace for any external XML schemas that are referenced within the file. * * A basic <kml> element contains 0 or 1 Feature and 0 or 1 NetworkLinkControl: */ export const KML_TAG = 'kml'; /** * Specifies how the <name> of a Feature is drawn in the 3D viewer. A custom color, color mode, and scale for the label (name) can be specified. */ export const LABEL_STYLE_TAG = 'LabelStyle'; /** * ### Defines a connected set of line segments. * Use <LineStyle> to specify the color, color mode, and width of the line. * When a LineString is extruded, the line is extended to the ground, forming a polygon that looks somewhat like a wall or fence. * For extruded LineStrings, the line itself uses the current LineStyle, and the extrusion uses the current PolyStyle. See the KML Tutorial for examples of LineStrings (or paths). * * https://developers.google.com/kml/documentation/kmlreference#linestring */ export const LINE_STRING_TAG = 'LineString'; /** * ### Specifies the drawing style (color, color mode, and line width) for all line geometry. * * Line geometry includes the outlines of outlined polygons and the extruded "tether" of Placemark icons (if extrusion is enabled). * * https://developers.google.com/kml/documentation/kmlreference#linestyle */ export const LINE_STYLE_TAG = 'LineStyle'; /** * <Link> specifies the location of any of the following: KML files fetched by network links Image files used in any Overlay (the <Icon> element specifies the image in an Overlay; <Icon> has the same fields as <Link>) Model files used in the <Model> element The file is conditionally loaded and refreshed, depending on the refresh parameters supplied here. Two different sets of refresh parameters can be specified: one set is based on time (<refreshMode> and <refreshInterval>) and one is based on the current "camera" view (<viewRefreshMode> and <viewRefreshTime>). In addition, Link specifies whether to scale the bounding box parameters that are sent to the server (<viewBoundScale> and provides a set of optional viewing parameters that can be sent to the server (<viewFormat>) as well as a set of optional parameters containing version and language information. When a file is fetched, the URL that is sent to the server is composed of three pieces of information: the href (Hypertext Reference) that specifies the file to load. an arbitrary format string that is created from (a) parameters that you specify in the <viewFormat> element or (b) bounding box parameters (this is the default and is used if no <viewFormat> element is included in the file). a second format string that is specified in the <httpQuery> element. If the file specified in <href> is a local file, the <viewFormat> and <httpQuery> elements are not used. The <Link> element replaces the <Url> element of <NetworkLink> contained in earlier KML releases and adds functionality for the <Region> element (introduced in KML 2.1). In Google Earth releases 3.0 and earlier, the <Link> element is ignored. */ export const LINK_TAG = 'Link'; /** * Specifies how a Feature is displayed in the list view. The list view is a hierarchy of containers and children; in Google Earth, this is the Places panel. */ export const LIST_STYLE_TAG = 'ListStyle'; /** * Not Supported * Defines a virtual camera that is associated with any element derived from Feature. The LookAt element positions the "camera" in relation to the object that is being viewed. In Google Earth, the view "flies to" this LookAt viewpoint when the user double-clicks an item in the Places panel or double-clicks an icon in the 3D viewer. */ export const LOOK_AT_TAG = 'LookAt'; /** * A 3D object described in a COLLADA file (referenced in the <Link> tag). COLLADA files have a .dae file extension. Models are created in their own coordinate space and then located, positioned, and scaled in Google Earth. See the "Topics in KML" page on Models for more detail. Google Earth supports the COLLADA common profile, with the following exceptions: Google Earth supports only triangles and lines as primitive types. The maximum number of triangles allowed is 21845. Google Earth does not support animation or skinning. Google Earth does not support external geometry references. */ export const MODEL_TAG = 'Model'; /** * ### A container for zero or more geometry primitives associated with the same feature. * * https://developers.google.com/kml/documentation/kmlreference#multigeometry */ export const MULTI_GEOMETRY_TAG = 'MultiGeometry'; /** * A href (url) to a separate KML file that is added as part of the current KML. * Used to provide dynamic data into the KML. */ export const NETWORK_LINK_TAG = 'NetworkLink'; /** * Controls the behavior of files fetched by a <NetworkLink>. */ export const NETWORK_LINK_CONTROL_TAG = 'NetworkLinkControl'; /** * The <PhotoOverlay> element allows you to geographically locate a photograph on the Earth and to specify viewing parameters for this PhotoOverlay. The PhotoOverlay can be a simple 2D rectangle, a partial or full cylinder, or a sphere (for spherical panoramas). The overlay is placed at the specified location and oriented toward the viewpoint. * * Because <PhotoOverlay> is derived from <Feature>, it can contain one of the two elements derived from <AbstractView>—either <Camera> or <LookAt>. The Camera (or LookAt) specifies a viewpoint and a viewing direction (also referred to as a view vector). The PhotoOverlay is positioned in relation to the viewpoint. Specifically, the plane of a 2D rectangular image is orthogonal (at right angles to) the view vector. The normal of this plane—that is, its front, which is the part with the photo—is oriented toward the viewpoint. * * The URL for the PhotoOverlay image is specified in the <Icon> tag, which is inherited from <Overlay>. The <Icon> tag must contain an <href> element that specifies the image file to use for the PhotoOverlay. In the case of a very large image, the <href> is a special URL that indexes into a pyramid of images of varying resolutions (see ImagePyramid). */ export const PHOTO_OVERLAY_TAG = 'PhotoOverlay'; /** * ### A Placemark is a Feature with an associated Geometry. * In Google Earth, a Placemark appears as a list item in the Places panel. * A Placemark with a Point has an icon associated with it that marks a point on the Earth in the 3D viewer. * (In the Google Earth 3D viewer, a Point Placemark is the only object you can click or roll over. * Other Geometry objects do not have an icon in the 3D viewer. * To give the user something to click in the 3D viewer, you would need to create a MultiGeometry object that contains both a Point and the other Geometry object.) * * https://developers.google.com/kml/documentation/kmlreference#placemark */ export const PLACEMARK_TAG = 'Placemark'; /** * A geographic location defined by longitude, latitude, and (optional) altitude. When a Point is contained by a Placemark, the point itself determines the position of the Placemark's name and icon. When a Point is extruded, it is connected to the ground with a line. This "tether" uses the current LineStyle. */ export const POINT_TAG = 'Point'; /** * A Polygon is defined by an outer boundary and 0 or more inner boundaries. The boundaries, in turn, are defined by LinearRings. When a Polygon is extruded, its boundaries are connected to the ground to form additional polygons, which gives the appearance of a building or a box. Extruded Polygons use <PolyStyle> for their color, color mode, and fill. The <coordinates> for polygons must be specified in counterclockwise order. Polygons follow the "right-hand rule," which states that if you place the fingers of your right hand in the direction in which the coordinates are specified, your thumb points in the general direction of the geometric normal for the polygon. (In 3D graphics, the geometric normal is used for lighting and points away from the front face of the polygon.) Since Google Earth fills only the front face of polygons, you will achieve the desired effect only when the coordinates are specified in the proper order. Otherwise, the polygon will be gray. */ export const POLYGON_TAG = 'Polygon'; /** * ### Specifies the drawing style for all polygons * * including polygon extrusions (which look like the walls of buildings) and line extrusions (which look like solid fences). * * https://developers.google.com/kml/documentation/kmlreference#polystyle */ export const POLY_STYLE_TAG = 'PolyStyle'; /** * A region contains a bounding box (<LatLonAltBox>) that describes an area of interest defined by geographic coordinates and altitudes. In addition, a Region contains an LOD (level of detail) extent (<Lod>) that defines a validity range of the associated Region in terms of projected screen size. A Region is said to be "active" when the bounding box is within the user's view and the LOD requirements are met. Objects associated with a Region are drawn only when the Region is active. When the <viewRefreshMode> is onRegion, the Link or Icon is loaded only when the Region is active. See the "Topics in KML" page on Regions for more details. In a Container or NetworkLink hierarchy, this calculation uses the Region that is the closest ancestor in the hierarchy. */ export const REGION_TAG = 'Region'; /** * Specifies a custom KML schema that is used to add custom data to KML Features. The "id" attribute is required and must be unique within the KML file. <Schema> is always a child of <Document>. */ export const SCHEMA_TAG = 'Schema'; /** * This element draws an image overlay fixed to the screen. Sample uses for ScreenOverlays are compasses, logos, and heads-up displays. ScreenOverlay sizing is determined by the <size> element. Positioning of the overlay is handled by mapping a point in the image specified by <overlayXY> to a point on the screen specified by <screenXY>. Then the image is rotated by <rotation> degrees about a point relative to the screen specified by <rotationXY>. * * The <href> child of <Icon> specifies the image to be used as the overlay. This file can be either on a local file system or on a web server. If this element is omitted or contains no <href>, a rectangle is drawn using the color and size defined by the screen overlay. */ export const SCREEN_OVERLAY_TAG = 'ScreenOverlay'; /** * ### A Style defines an addressable style group * * that can be referenced by StyleMaps and Features. * Styles affect how Geometry is presented in the 3D viewer and how Features appear in the Places panel of the List view. * Shared styles are collected in a <Document> and must have an id defined for them so that they can be referenced by the individual Features that use them. * * Use an id to refer to the style from a <styleUrl>. * * https://developers.google.com/kml/documentation/kmlreference#style */ export const STYLE_TAG = 'Style'; /** * ### A <StyleMap> maps between two different Styles. * * Typically a <StyleMap> element is used to provide separate normal and highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. * * https://developers.google.com/kml/documentation/kmlreference#stylemap */ export const STYLE_MAP_TAG = 'StyleMap'; /** * ### URL of a <Style> or <StyleMap> defined in a Document. * * If the style is in the same file, use a # reference. * * If the style is defined in an external file, use a full URL along with # referencing * * https://developers.google.com/kml/documentation/kmlreference#styleurl */ export const STYLE_URL_TAG = 'styleUrl'; /** * Represents an extent in time bounded by begin and end dateTimes. * * If <begin> or <end> is missing, then that end of the period is unbounded (see Example below). * * The dateTime is defined according to XML Schema time (see XML Schema Part 2: Datatypes Second Edition). The value can be expressed as yyyy-mm-ddThh:mm:ss.ssszzzzzz, where T is the separator between the date and the time, and the time zone is either Z (for UTC) or zzzzzz, which represents ±hh:mm in relation to UTC. Additionally, the value can be expressed as a date only. See <TimeStamp> for examples. */ export const TIME_SPAN_TAG = 'TimeSpan'; /** * Represents a single moment in time. This is a simple element and contains no children. Its value is a dateTime, specified in XML time (see XML Schema Part 2: Datatypes Second Edition). The precision of the TimeStamp is dictated by the dateTime value in the <when> element. */ export const TIME_STAMP_TAG = 'TimeStamp'; /** * Note: This element was deprecated in KML Release 2.1 and is replaced by <Link>, which provides the additional functionality of Regions. The <Url> tag will still work in Google Earth, but use of the newer <Link> tag is encouraged. * * Use this element to set the location of the link to the KML file, to define the refresh options for the server and viewer changes, and to populate a variable to return useful client information to the server. */ export const URL_TAG = 'Url'; // Usage Level Descriptions export const ADDRESS_DETAILS_TAG = 'AddressDetails'; export const ADDRESS_TAG = 'address'; export const ATOM_AUTHOR_TAG = 'atom:author'; export const ATOM_LINK_TAG = 'atom:link'; export const BEGIN_TAG = 'begin'; export const BG_COLOR_TAG = 'bgColor'; export const BOTTOM_FOV_TAG = 'bottomFov'; export const CHANGE_TAG = 'Change'; export const COLOR_MODE_TAG = 'colorMode'; export const COLOR_STYLE_TAG = 'ColorStyle'; export const COOKIE_TAG = 'cookie'; export const COORDINATES_TAG = 'coordinates'; export const CREATE_TAG = 'Create'; export const DATA_TAG = 'Data'; export const DELETE_TAG = 'Delete' export const DESCRIPTION_TAG = 'description'; export const DISPLAY_MODE_TAG = 'displayMode'; export const DISPLAY_NAME_TAG = 'displayName'; export const DRAW_ORDER_TAG = 'drawOrder'; export const EAST_TAG = 'east'; export const END_TAG = 'end'; export const EXPIRES_TAG = 'expires'; export const EXTENDED_DATA_TAG = 'ExtendedData'; export const EXTRUDE_TAG = 'extrude'; export const FLY_TO_VIEW_TAG = 'flyToView'; export const GEOM_COLOR_TAG = 'geomColor'; export const GRID_ORIGIN_TAG = 'gridOrigin'; export const HEADING_TAG = 'heading'; export const HOTSPOT_TAG = 'hotSpot'; export const HREF_TAG = 'href'; export const HTTP_QUERY_TAG = 'httpQuery'; export const IMAGE_PYRAMID_TAG = 'ImagePyramid'; export const INNER_BOUNDARY_TAG = 'innerBoundaryIs'; export const ITEM_ICON_HREF = 'href'; export const ITEM_ICON_TAG = 'itemIcon'; export const KEY_TAG = 'key'; export const LAT_LON_ALT_BOX_TAG = 'LatLonAltBox'; export const LAT_LON_BOX_TAG = 'LatLonBox'; export const LATITUDE_TAG = 'latitude'; export const LEFT_FOV_TAG = 'leftFov'; export const LEVEL_OF_DETAIL_TAG = 'Lod'; export const LINEAR_RING_TAG = 'LinearRing' export const LINK_DESCRIPTION_TAG = 'linkDescription'; export const LINK_NAME_TAG = 'linkName'; export const LINK_SNIPPET_TAG = 'linkSnippet'; export const LIST_ITEM_TYPE_TAG = 'listItemType'; export const LONGITUDE_TAG = 'longitude'; export const MAX_ALTITUDE_TAG = 'maxAltitude'; export const MAX_FADE_EXTENT = 'maxFadeExtent'; export const MAX_HEIGHT_TAG = 'maxHeight'; export const MAX_LOD_PIXELS_TAG = 'maxLodPixels'; export const MAX_SESSION_LENGTH_TAG = 'maxSessionLength'; export const MAX_WIDTH_TAG = 'maxWidth'; export const MESSAGE_TAG = 'message'; export const META_DATA_TAG = 'Metadata'; export const MIN_ALTITUDE_TAG = 'minAltitude'; export const MIN_FADE_EXTENT = 'minFadeExtent'; export const MIN_LOD_PIXELS_TAG = 'minLodPixels'; export const MIN_REFRESH_PERIOD_TAG = 'minRefreshPeriod'; export const NAME_TAG = 'name'; export const NEAR_TAG = 'near'; export const NORTH_TAG = 'north'; export const OPEN_TAG = 'open'; export const OPTION_TAG = 'option'; export const ORIENTATION_TAG = 'Orientation'; export const OUTER_BOUNDARY_TAG = 'outerBoundaryIs'; export const PAIR_TAG = 'Pair'; export const PHONE_NUMBER_TAG = 'phoneNumber'; export const REFRESH_INTERVAL_TAG = 'viewRefreshMode'; export const REFRESH_MODE_TAG = 'refreshMode'; export const REFRESH_VISIBILITY_TAG = 'refreshVisibility'; export const RIGHT_FOV_TAG = 'rightFov'; export const ROLL_TAG = 'roll'; export const ROTATION_TAG = 'rotation'; export const SCALE_TAG = 'scale'; export const SCHEMA_DATA_TAG = 'SchemaData'; export const SHAPE_TAG = 'shape'; export const SIMPLE_DATA_TAG = 'SimpleData'; export const SIMPLE_FIELD_TAG = 'SimpleField'; export const SNIPPET_TAG = 'Snippet'; export const SOUTH_TAG = 'south'; export const STATE_TAG = 'state'; export const TARGET_HREF_TAG = 'targetHref'; export const TESSELLATE_TAG = 'tessellate'; export const TEXT_COLOR_TAG = 'textColor'; export const TEXT_TAG = 'text'; export const TILE_SIZE_TAG = 'tileSize'; export const TILT_TAG = 'tilt'; export const TOP_FOV_TAG = 'topFov'; export const UPDATE_TAG = 'Update'; export const VALUE_TAG = 'value'; export const VIEW_BOUND_SCALE_TAG = 'viewBoundScale'; export const VIEW_FORMAT_TAG = 'viewFormat'; export const VIEW_REFRESH_TIME_TAG = 'viewRefreshTime'; export const VIEW_VOLUME_TAG = 'ViewVolume'; export const VISIBILITY_TAG = 'visibility'; export const WEST_TAG = 'west'; export const WHEN_TAG = 'when'; export const WIDTH_TAG = 'width'; export const XAL_ADDRESS_DETAILS_TAG = 'xal:AddressDetails'; // Redefined export const LIST_STYLE_BG_COLOR = BG_COLOR_TAG; export const LOD_TAG = LEVEL_OF_DETAIL_TAG; // Google Extended Descriptions /** * How linestring or polygons work. * Any altitude value should be accompanied by an <altitudeMode> element, which tells Google Earth how to read the altitude value. Altitudes can be measured: * * from the surface of the Earth (relativeToGround), above sea level (absolute), * or from the bottom of major bodies of water (relativeToSeaFloor). * It can also be ignored (clampToGround and clampToSeaFloor) * * https://developers.google.com/kml/documentation/altitudemode */ export const GX_ALTITUDE_MODE_TAG = 'gx:altitudeMode'; export const GX_ALTITUDE_OFFSET_TAG = 'gx:altitudeOffset'; export const GX_ANGLES_TAG = 'gx:angles'; export const GX_ANIMATED_UPDATE_TAG = 'gx:AnimatedUpdate'; export const GX_BALLOON_VISIBILITY_TAG = 'gx:balloonVisibility'; export const GX_COORD_TAG = 'gx:coord'; export const GX_DELAY_START_TAG = 'gx:delayedStart'; export const GX_DURATION_TAG = 'gx:duration'; export const GX_FLY_TO_TAG = 'gx:FlyTo'; export const GX_FLY_TO_MODE_TAG = 'gx:FlyToMode'; export const GX_H_TAG = 'gx:h'; export const GX_HORIZ_FOV_TAG = 'gx:horizFov'; export const GX_HORIZONTAL_FOV_TAG = GX_HORIZ_FOV_TAG; export const GX_LABEL_VISIBILITY_TAG = 'gx:labelVisibility'; export const GX_LAT_LON_QUAD_TAG = 'gx:LatLonQuad'; export const GX_MULTI_TRACK_TAG = 'gx:MultiTrack'; export const GX_OUTER_COLOR_TAG = 'gx:outerColor'; export const GX_OUTER_WIDTH_TAG = 'gx:outerWidth'; export const GX_PHYSICAL_WIDTH_TAG = 'gx:physicalWidth'; export const GX_PLAYLIST_TAG = 'gx:Playlist'; export const GX_SOUND_CUE = 'gx:SoundCue'; export const GX_TIME_SPAN_TAG = 'gx:TimeSpan'; export const GX_TIME_STAMP_TAG = 'gx:TimeStamp'; export const GX_TOUR_TAG = 'gx:Tour'; export const GX_TRACK_TAG = 'gx:Track'; export const GX_VIEWER_OPTIONS_TAG = 'gx:ViewerOptions'; export const GX_W_TAG = 'gx:w'; export const GX_WAIT_TAG = 'gx:wait'; export const GX_X_TAG = 'gx:x'; export const GX_Y_TAG = 'gx:y'; // Descriptors export const MAX_LINES_DESCRIPTOR = 'maxLines'; export const X_COMPONENT_DESCRIPTOR = 'x'; export const X_UNITS_DESCRIPTOR = 'xunits'; export const Y_COMPONENT_DESCRIPTOR = 'y'; export const Y_UNITS_DESCRIPTOR = 'yunits'; // Selectors XML Stream export const XML_STREAM_CHILDREN_SELECTOR = '$children'; export const XML_STREAM_NAME_SELECTOR = '$name'; export const XML_STREAM_TEXT_SELECTOR = '$text'; // Type collections // Enums export enum SIMPLE_FIELD_TYPES { string = 'string', int = 'int', uint = 'uint', short = 'short', ushort = 'ushort', float = 'float', double = 'double', bool = 'bool', } export enum SHAPE_TYPES { rectangle = 'rectangle', cylinder = 'cylinder', sphere = 'sphere', } export enum ALTITUDE_MODES { absolute = 'absolute', clampToGround = 'clampToGround', clampToSeaFloor = 'clampToSeaFloor', relativeToGround = 'relativeToGround', relativeToSeaFloor = 'relativeToSeaFloor', } export enum DISPLAY_MODES { default = 'default', hide = 'hide', } export enum OPTIONS_NAME { streetview = 'streetview', historicalimagery = 'historicalimagery', sunlight = 'sunlight', groundnavigation = 'groundnavigation', } export enum COLOR_MODES { normal = 'normal', random = 'random', } /** * This is an abstract element and cannot be used directly in a KML file. The following diagram shows how some of a Feature's elements appear in Google Earth. */ export const FEATURE_TAGS = { Document: DOCUMENT_TAG, Folder: FOLDER_TAG, NetworkLink: NETWORK_LINK_TAG, Placemark: PLACEMARK_TAG, GroundOverlay: GROUND_OVERLAY_TAG, PhotoOverlay: PHOTO_OVERLAY_TAG, ScreenOverlay: SCREEN_OVERLAY_TAG, }; /** * This is an abstract element and cannot be used directly in a KML file. This element is extended by the <Camera> and <LookAt> elements. */ export const ABSTRACT_VIEW_TAGS = { Camera: CAMERA_TAG, LookAt: LOOK_AT_TAG, }; export const TIME_PRIMITIVE_TAGS = { TimeStamp: TIME_STAMP_TAG, TimeSpan: TIME_SPAN_TAG, }; export const ABSTRACT_VIEW_CHILDREN_TAGS = { TimePrimitive: TIME_PRIMITIVE_TAGS, 'gx:ViewerOptions': GX_VIEWER_OPTIONS_TAG, }; /** * This is an abstract element and cannot be used directly in a KML file. It is the base type for the <Style> and <StyleMap> elements. The StyleMap element selects a style based on the current mode of the Placemark. An element derived from StyleSelector is uniquely identified by its id and its url. */ export const STYLE_SELECTOR_TAGS = { Style: STYLE_TAG, StyleMap: STYLE_MAP_TAG, }; export const REGION_CHILDREN_TAGS = { LatLonAltBox: LAT_LON_BOX_TAG, Lod: LEVEL_OF_DETAIL_TAG, }; export const LAT_LON_ALT_BOX_CHILDREN_TAGS = { /** * Possible values for <altitudeMode> are clampToGround, relativeToGround, and absolute. Possible values for <gx:altitudeMode> are clampToSeaFloor and relativeToSeaFloor. Also see <LatLonBox>. */ altitudeMode: ALTITUDE_MODE_TAG, /** * Possible values for <altitudeMode> are clampToGround, relativeToGround, and absolute. Possible values for <gx:altitudeMode> are clampToSeaFloor and relativeToSeaFloor. Also see <LatLonBox>. */ 'gx:altitudeMode': GX_ALTITUDE_MODE_TAG, /** * Specified in meters (and is affected by the altitude mode specification). */ minAltitude: MIN_ALTITUDE_TAG, /** * Specified in meters (and is affected by the altitude mode specification). */ maxAltitude: MAX_ALTITUDE_TAG, /** * (required) Specifies the latitude of the north edge of the bounding box, in decimal degrees from 0 to ±90. */ north: NORTH_TAG, /** * (required) Specifies the latitude of the south edge of the bounding box, in decimal degrees from 0 to ±90. */ south: SOUTH_TAG, /** * (required) Specifies the longitude of the east edge of the bounding box, in decimal degrees from 0 to ±180. */ east: EAST_TAG, /** * (required) Specifies the longitude of the west edge of the bounding box, in decimal degrees from 0 to ±180. */ west: WEST_TAG, }; /** * Lod is an abbreviation for Level of Detail. <Lod> describes the size of the projected region on the screen that is required in order for the region to be considered "active." Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). See diagram below for a visual representation of these parameters. */ export const LOD_CHILDREN_TAGS = { /** * (required) Defines a square in screen space, with sides of the specified value in pixels. For example, 128 defines a square of 128 x 128 pixels. The region's bounding box must be larger than this square (and smaller than the maxLodPixels square) in order for the Region to be active. */ minLodPixels: MIN_LOD_PIXELS_TAG, /** * Measurement in screen pixels that represents the maximum limit of the visibility range for a given Region. A value of −1, the default, indicates "active to infinite size." */ maxLodPixels: MAX_LOD_PIXELS_TAG, /** * Distance over which the geometry fades, from fully opaque to fully transparent. This ramp value, expressed in screen pixels, is applied at the minimum end of the LOD (visibility) limits. */ minFadeExtent: MIN_FADE_EXTENT, /** * Distance over which the geometry fades, from fully transparent to fully opaque. This ramp value, expressed in screen pixels, is applied at the maximum end of the LOD (visibility) limits. */ maxFadeExtent: MAX_FADE_EXTENT, }; export const FEATURE_CHILDREN_TAGS = { /** * User-defined text displayed in the 3D viewer as the label for the object (for example, for a Placemark, Folder, or NetworkLink). */ name: NAME_TAG, /** * Boolean value. Specifies whether the feature is drawn in the 3D viewer when it is initially loaded. In order for a feature to be visible, the <visibility> tag of all its ancestors must also be set to 1. In the Google Earth List View, each Feature has a checkbox that allows the user to control visibility of the Feature. */ visibility: VISIBILITY_TAG, /** * Boolean value. Specifies whether a Document or Folder appears closed or open when first loaded into the Places panel. 0=collapsed (the default), 1=expanded. See also <ListStyle>. This element applies only to Document, Folder, and NetworkLink. */ open: OPEN_TAG, /** * KML 2.2 supports new elements for including data about the author and related website in your KML file. This information is displayed in geo search results, both in Earth browsers such as Google Earth, and in other applications such as Google Maps. The ascription elements used in KML are as follows: atom:author element - parent element for atom:name atom:name element - the name of the author atom:link element - contains the href attribute href attribute - URL of the web page containing the KML/KMZ file These elements are defined in the Atom Syndication Format. The complete specification is found at http://atompub.org. (see the sample that follows). The <atom:author> element is the parent element for <atom:name>, which specifies the author of the KML feature. */ 'atom:author': ATOM_AUTHOR_TAG, /** * Specifies the URL of the website containing this KML or KMZ file. Be sure to include the namespace for this element in any KML file that uses it: xmlns:atom="http://www.w3.org/2005/Atom" (see the sample that follows). */ 'atom:link': ATOM_LINK_TAG, /** * A string value representing an unstructured address written as a standard street, city, state address, and/or as a postal code. You can use the <address> tag to specify the location of a point instead of using latitude and longitude coordinates. (However, if a <Point> is provided, it takes precedence over the <address>.) To find out which locales are supported for this tag in Google Earth, go to the Google Maps Help. */ address: ADDRESS_TAG, /** * A structured address, formatted as xAL, or eXtensible Address Language, an international standard for address formatting. <xal:AddressDetails> is used by KML for geocoding in Google Maps only. For details, see the Google Maps API documentation. Currently, Google Earth does not use this element; use <address> instead. Be sure to include the namespace for this element in any KML file that uses it: xmlns:xal="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0" */ 'xal:AddressDetails': XAL_ADDRESS_DETAILS_TAG, /** * A string value representing a telephone number. This element is used by Google Maps Mobile only. The industry standard for Java-enabled cellular phones is RFC2806. * For more information, see http://www.ietf.org/rfc /rfc2806.txt. */ phoneNumber: PHONE_NUMBER_TAG, /** * A short description of the feature. In Google Earth, this description is displayed in the Places panel under the name of the feature. If a Snippet is not supplied, the first two lines of the <description> are used. In Google Earth, if a Placemark contains both a description and a Snippet, the <Snippet> appears beneath the Placemark in the Places panel, and the <description> appears in the Placemark's description balloon. This tag does not support HTML markup. <Snippet> has a maxLines attribute, an integer that specifies the maximum number of lines to display. */ Snippet: SNIPPET_TAG, /** * User-supplied content that appears in the description balloon. The supported content for the <description> element changed from Google Earth 4.3 to 5.0. Specific information for each version is listed out below, followed by information common to both. Google Earth 5.0 Google Earth 5.0 (and later) supports plain text content, as well as full HTML and JavaScript, within description balloons. Contents of the description tag are rendered by the WebKit open source web browser engine, and are displayed as they would be in any WebKit-based browser. General restrictions Links to local files are generally not allowed. This prevents malicious code from damaging your system or accessing your data. Should you wish to allow access to your local filesystem, select Preferences > Allow access to local files and personal data. Links to image files on the local filesystem are always allowed, if contained within an <img> tag. Content that has been compressed into a KMZ file can be accessed, even if on the local filesystem. Cookies are enabled, but for the purposes of the same-origin policy, local content does not share a domain with any other content (including other local content). HTML HTML is mostly rendered as it would be in any WebKit browser. Targets are ignored when included in HTML written directly into the KML; all such links are opened as if the target is set to _blank. Any specified targets are ignored. HTML that is contained in an iFrame, however, or dynamically generated with JavaScript or DHTML, will use target="_self" as the default. Other targets can be specified and are supported. The contents of KMZ files, local anchor links, and ;flyto methods cannot be targeted from HTML contained within an iFrame. If the user specifies width="100%" for the width of an iFrame, then the iFrame's width will be dependent on all the other content in the balloon—it should essentially be ignored while calculating layout size. This rule applies to any other block element inside the balloon as well. JavaScript Most JavaScript is supported. Dialog boxes can not be created - functions such as alert() and prompt() will not be displayed. They will, however, be written to the system console, as will other errors and exceptions. CSS CSS is allowed. As with CSS in a regular web browser, CSS can be used to style text, page elements, and to control the size and appearance of the description balloon. Google Earth 4.3 The <description> element supports plain text as well as a subset of HTML formatting elements, including tables (see KML example below). It does not support other web-based technology, such as dynamic page markup (PHP, JSP, ASP), scripting languages (VBScript, Javascript), nor application languages (Java, Python). In Google Earth release 4.2, video is supported. (See Example below.) Common information If your description contains no HTML markup, Google Earth attempts to format it, replacing newlines with <br> and wrapping URLs with anchor tags. A valid URL string for the World Wide Web is automatically converted to a hyperlink to that URL (e.g., http://www.google.com). Consequently, you do not need to surround a URL with the <a href="http://.."></a> tags in order to achieve a simple link. When using HTML to create a hyperlink around a specific word, or when including images in the HTML, you must use HTML entity references or the CDATA element to escape angle brackets, apostrophes, and other special characters. The CDATA element tells the XML parser to ignore special characters used within the brackets. This element takes the form of: <![CDATA[ special characters here ]]> If you prefer not to use the CDATA element, you can use entity references to replace all the special characters. <description> <![CDATA[ This is an image <img src="icon.jpg"> ]]> </description> Other Behavior Specified Through Use of the <a> Element KML supports the use of two attributes within the <a> element: href and type. The anchor element <a> contains an href attribute that specifies a URL. If the href is a KML file and has a .kml or .kmz file extension, Google Earth loads that file directly when the user clicks it. If the URL ends with an extension not known to Google Earth (for example, .html), the URL is sent to the browser. The href can be a fragment URL (that is, a URL with a # sign followed by a KML identifier). When the user clicks a link that includes a fragment URL, by default the browser flies to the Feature whose ID matches the fragment. If the Feature has a LookAt or Camera element, the Feature is viewed from the specified viewpoint. The behavior can be further specified by appending one of the following three strings to the fragment URL: ;flyto (default) - fly to the Feature ;balloon - open the Feature's balloon but do not fly to the Feature ;balloonFlyto - open the Feature's balloon and fly to the Feature For example, the following code indicates to open the file CraftsFairs.kml, fly to the Placemark whose ID is "Albuquerque," and open its balloon: <description> <![CDATA[ <a href="http://myServer.com/CraftsFairs.kml#Albuquerque;balloonFlyto"> One of the Best Art Shows in the West</a> ]]> </description> The type attribute is used within the <a> element when the href does not end in .kml or .kmz, but the reference needs to be interpreted in the context of KML. Specify the following: type="application/vnd.google-earth.kml+xml" For example, the following URL uses the type attribute to notify Google Earth that it should attempt to load the file, even though the file extension is .php: <a href="myserver.com/cgi-bin/generate-kml.php#placemark123" type="application/vnd.google-earth.kml+xml"> */ description: DESCRIPTION_TAG, /** * Defines a viewpoint associated with any element derived from Feature. See <Camera> and <LookAt>. */ AbstractView: ABSTRACT_VIEW_TAGS, /** * Associates this Feature with a period of time (<TimeSpan>) or a point in time (<TimeStamp>). */ TimePrimitive: TIME_PRIMITIVE_TAGS, /** * URL of a <Style> or <StyleMap> defined in a Document. If the style is in the same file, use a # reference. If the style is defined in an external file, use a full URL along with # referencing. */ styleUrl: STYLE_URL_TAG, /** * One or more Styles and StyleMaps can be defined to customize the appearance of any element derived from Feature or of the Geometry in a Placemark. (See <BalloonStyle>, <ListStyle>, <StyleSelector>, and the styles derived from <ColorStyle>.) A style defined within a Feature is called an "inline style" and applies only to the Feature that contains it. A style defined as the child of a <Document> is called a "shared style." A shared style must have an id defined for it. This id is referenced by one or more Features within the <Document>. In cases where a style element is defined both in a shared style and in an inline style for a Feature—that is, a Folder, GroundOverlay, NetworkLink, Placemark, or ScreenOverlay—the value for the Feature's inline style takes precedence over the value for the shared style. */ StyleSelector: STYLE_SELECTOR_TAGS, /** * Features and geometry associated with a Region are drawn only when the Region is active. See <Region>. */ Region: REGION_TAG, /** * Deprecated us ExtendedData */ Metadata: META_DATA_TAG, /** * Allows you to add custom data to a KML file. This data can be (1) data that references an external XML schema, (2) untyped data/value pairs, or (3) typed data. A given KML Feature can contain a combination of these types of custom data. */ ExtendedData: EXTENDED_DATA_TAG, }; /** * A Document is a container for features and styles. This element is required if your KML file uses shared styles. It is recommended that you use shared styles, which require the following steps: Define all Styles in a Document. Assign a unique ID to each Style. Within a given Feature or StyleMap, reference the Style's ID using a <styleUrl> element. Note that shared styles are not inherited by the Features in the Document. Each Feature must explicitly reference the styles it uses in a <styleUrl> element. For a Style that applies to a Document (such as ListStyle), the Document itself must explicitly reference the <styleUrl>. For example: */ export const DOCUMENT_CHILDREN_TAGS = { inheritedFeatureElements: FEATURE_CHILDREN_TAGS, /** * 0 or more elements derived from <Schema> */ schemaElements: SCHEMA_TAG, /** * 0 or more elements derived from <Feature> */ featureElements: FEATURE_TAGS, }; /** * A Folder is used to arrange other Features hierarchically (Folders, Placemarks, NetworkLinks, or Overlays). A Feature is visible only if it and all its ancestors are visible. */ export const FOLDER_CHILDREN_TAGS = { inheritedFeatureElements: FEATURE_CHILDREN_TAGS, /** * 0 or more Feature elements */ featureElements: FEATURE_TAGS, }; /** * References a KML file or KMZ archive on a local or remote network. * Use the <Link> element to specify the location of the KML file. * Within that element, you can define the refresh options for updating the file, based on time and camera change. * NetworkLinks can be used in combination with Regions to handle very large datasets efficiently. */ export const NETWORK_LINK_CHILDREN_TAGS = { inheritedFeatureElements: FEATURE_CHILDREN_TAGS, /** * Boolean value. A value of 0 leaves the visibility of features within the control of the Google Earth user. * Set the value to 1 to reset the visibility of features each time the NetworkLink is refreshed. * For example, suppose a Placemark within the linked KML file has <visibility> set to 1 and the NetworkLink has <refreshVisibility> set to 1. * When the file is first loaded into Google Earth, the user can clear the check box next to the item to turn off display in the 3D viewer. * However, when the NetworkLink is refreshed, the Placemark will be made visible again, since its original visibility state was TRUE. */ refreshVisibility: REFRESH_VISIBILITY_TAG, /** * Boolean value. * A value of 1 causes Google Earth to fly to the view of the LookAt or Camera in the NetworkLinkControl (if it exists). * If the NetworkLinkControl does not contain an AbstractView element, Google Earth flies to the LookAt or Camera element in the Feature child within the <kml> element in the refreshed file. * If the <kml> element does not have a LookAt or Camera specified, the view is unchanged. * For example, Google Earth would fly to the <LookAt> view of the parent Document, not the <LookAt> of the Placemarks contained within the Document. */ flyToView: FLY_TO_VIEW_TAG, /** * Required */ Link: LINK_TAG, Url: URL_TAG, }; export const OVERLAY_TAGS = { GroundOverlay: GROUND_OVERLAY_TAG, ScreenOverlay: SCREEN_OVERLAY_TAG, PhotoOverlay: PHOTO_OVERLAY_TAG, }; /** * This is an abstract element and cannot be used directly in a KML file. * <Overlay> is the base type for image overlays drawn on the planet surface or on the screen. * <Icon> specifies the image to use and can be configured to reload images based on a timer or by camera changes. * This element also includes specifications for stacking order of multiple overlays and for adding color and transparency values to the base image. */ export const OVERLAY_TAGS_CHILDREN_TAGS = { inheritedFeatureElements: FEATURE_CHILDREN_TAGS, /** * Color values are expressed in hexadecimal notation, including opacity (alpha) values. * * The order of expression is alpha, blue, green, red (aabbggrr). * The range of values for any one color is 0 to 255 (00 to ff). For opacity, 00 is fully transparent and ff is fully opaque. * For example, if you want to apply a blue color with 50 percent opacity to an overlay, you would specify the following: <color>7fff0000</color> * * Note: The <geomColor> element has been deprecated. Use <color> instead. */ color: COLOR_TAG, /** * Note: The <geomColor> element has been deprecated. Use <color> instead. */ geomColor: GEOM_COLOR_TAG, /** * This element defines the stacking order for the images in overlapping overlays. * Overlays with higher <drawOrder> values are drawn on top of overlays with lower <drawOrder> values */ drawOrder: DRAW_ORDER_TAG, /** * Defines the image associated with the Overlay. * * The <href> element defines the location of the image to be used as the Overlay. * This location can be either on a local file system or on a web server. * If this element is omitted or contains no <href>, a rectangle is drawn using the color and size defined by the ground or screen overlay. */ Icon: ICON_TAG, }; export const GROUND_OVERLAY_CHILDREN_TAGS = { inheritedOverlayElement: OVERLAY_TAGS_CHILDREN_TAGS, /** * Specifies the distance above the earth's surface, in meters, and is interpreted according to the altitude mode. */ altitude: ALTITUDE_TAG, /** * ### Specifies how the <altitude>is interpreted. Possible values are * * clampToGround - (default) Indicates to ignore the altitude specification and drape the overlay over the terrain. * * absolute - Sets the altitude of the overlay relative to sea level, regardless of the actual elevation of the terrain beneath the element. For example, if you set the altitude of an overlay to 10 meters with an absolute altitude mode, the overlay will appear to be at ground level if the terrain beneath is also 10 meters above sea level. If the terrain is 3 meters above sea level, the overlay will appear elevated above the terrain by 7 meters. */ altitudeMode: ALTITUDE_MODE_TAG, /** * A KML extension in the Google extension namespace, allowing altitudes relative to the sea floor. Values are: * * relativeToSeaFloor - Interprets the <altitude> as a value in meters above the sea floor. If the point is above land rather than sea, the <altitude> will be interpreted as being above the ground. * * clampToSeaFloor - The <altitude> specification is ignored, and the overlay will be draped over the sea floor. If the point is on land rather than at sea, the overlay will be positioned on the ground. */ 'gx:altitudeMode': GX_ALTITUDE_MODE_TAG, LatLonBox: LAT_LON_BOX_TAG, 'gx:LatLonQuad': GX_LAT_LON_QUAD_TAG, }; /** * Placemarks Tags can have one of these tags. * Geometry tag is an abstract element and cannot be used directly in a KML file. * It provides a placeholder object for all derived Geometry objects. * * https://developers.google.com/kml/documentation/kmlreference#geometry */ export const GEOMETRY_TAGS = { POINT: POINT_TAG, LINESTRING: LINE_STRING_TAG, POLYGON: POLYGON_TAG, MULTIGEOMETRY: 'MultiGeometry', MODEL: 'Model', }; /** * The <PhotoOverlay> element allows you to geographically locate a photograph on the Earth and to specify viewing parameters for this PhotoOverlay. * The PhotoOverlay can be a simple 2D rectangle, a partial or full cylinder, or a sphere (for spherical panoramas). * The overlay is placed at the specified location and oriented toward the viewpoint. * * Because <PhotoOverlay> is derived from <Feature>, it can contain one of the two elements derived from <AbstractView>—either <Camera> or <LookAt>. * The Camera (or LookAt) specifies a viewpoint and a viewing direction (also referred to as a view vector). * The PhotoOverlay is positioned in relation to the viewpoint. * Specifically, the plane of a 2D rectangular image is orthogonal (at right angles to) the view vector. * The normal of this plane—that is, its front, which is the part with the photo—is oriented toward the viewpoint. * * The URL for the PhotoOverlay image is specified in the <Icon> tag, which is inherited from <Overlay>. * The <Icon> tag must contain an <href> element that specifies the image file to use for the PhotoOverlay. * In the case of a very large image, the <href> is a special URL that indexes into a pyramid of images of varying resolutions (see ImagePyramid). */ export const PHOTO_OVERLAY_CHILDREN_TAGS = { inheritedOverlayElement: OVERLAY_TAGS_CHILDREN_TAGS, /** * Adjusts how the photo is placed inside the field of view. * This element is useful if your photo has been rotated and deviates slightly from a desired horizontal view. */ rotation: ROTATION_TAG, /** * Defines how much of the current scene is visible. * Specifying the field of view is analogous to specifying the lens opening in a physical camera. * A small field of view, like a telephoto lens, focuses on a small part of the scene. * A large field of view, like a wide-angle lens, focuses on a large part of the scene. * * The field of view for a PhotoOverlay is defined by four planes, each of which is specified by an angle relative to the view vector. * These four planes define the top, bottom, left, and right sides of the field of view, which has the shape of a truncated pyramid. */ ViewVolume: VIEW_VOLUME_TAG, /** * For very large images, you'll need to construct an image pyramid, which is a hierarchical set of images, each of which is an increasingly lower resolution version of the original image. * Each image in the pyramid is subdivided into tiles, so that only the portions in view need to be loaded. * Google Earth calculates the current viewpoint and loads the tiles that are appropriate to the user's distance from the image. * As the viewpoint moves closer to the PhotoOverlay, Google Earth loads higher resolution tiles. * Since all the pixels in the original image can't be viewed on the screen at once, this preprocessing allows Google Earth to achieve maximum performance because it loads only the portions of the image that are in view, and only the pixel details that can be discerned by the user at the current viewpoint. * * When you specify an image pyramid, you also modify the <href> in the <Icon> element to include specifications for which tiles to load. */ ImagePyramid: IMAGE_PYRAMID_TAG, /** * The <Point> element acts as a <Point> inside a <Placemark> element. * It draws an icon to mark the position of the PhotoOverlay. * The icon drawn is specified by the <styleUrl> and <StyleSelector> fields, just as it is for <Placemark>. */ Point: POINT_TAG, /** * The PhotoOverlay is projected onto the <shape>. The <shape> can be one of the following: * * rectangle (default) - for an ordinary photo * * cylinder - for panoramas, which can be either partial or full cylinders * * sphere - for spherical panoramas */ shape: SHAPE_TAG, }; export const VIEW_VOLUME_CHILDREN_TAG = { /** * Angle, in degrees, between the camera's viewing direction and the left side of the view volume. */ leftFov: LEFT_FOV_TAG, /** * Angle, in degrees, between the camera's viewing direction and the right side of the view volume. */ rightFov: RIGHT_FOV_TAG, /** * Angle, in degrees, between the camera's viewing direction and the bottom side of the view volume. */ bottomFov: BOTTOM_FOV_TAG, /** * Angle, in degrees, between the camera's viewing direction and the top side of the view volume. */ topFov: TOP_FOV_TAG, /** * Measurement in meters along the viewing direction from the camera viewpoint to the PhotoOverlay shape. */ near: NEAR_TAG, }; export const IMAGE_PYRAMID_CHILDREN_TAGS = { /** * Size of the tiles, in pixels. Tiles must be square, and <tileSize> must be a power of 2. * A tile size of 256 (the default) or 512 is recommended. * The original image is divided into tiles of this size, at varying resolutions. */ tileSize: TILE_SIZE_TAG, /** * Width in pixels of the original image. */ maxWidth: MAX_WIDTH_TAG, /** * Height in pixels of the original image. */ maxHeight: MAX_HEIGHT_TAG, /** * Specifies where to begin numbering the tiles in each layer of the pyramid. * A value of lowerLeft specifies that row 1, column 1 of each layer is in the bottom left corner of the grid. */ gridOrigin: GRID_ORIGIN_TAG, }; /** * This element draws an image overlay fixed to the screen. * Sample uses for ScreenOverlays are compasses, logos, and heads-up displays. * ScreenOverlay sizing is determined by the <size> element. * Positioning of the overlay is handled by mapping a point in the image specified by <overlayXY> to a point on the screen specified by <screenXY>. * Then the image is rotated by <rotation> degrees about a point relative to the screen specified by <rotationXY>. * * The <href> child of <Icon> specifies the image to be used as the overlay. * This file can be either on a local file system or on a web server. * If this element is omitted or contains no <href>, a rectangle is drawn using the color and size defined by the screen overlay. */ export const SCREEN_OVERLAY_CHILDREN_TAGS = { inheritedOverlayElement: OVERLAY_TAGS_CHILDREN_TAGS, /** * Specifies a point on (or outside of) the overlay image that is mapped to the screen coordinate (<screenXY>). It requires x and y values, and the units for those values. * * The x and y values can be specified in three different ways: as pixels ("pixels"), as fractions of the image ("fraction"), or as inset pixels ("insetPixels"), which is an offset in pixels from the upper right corner of the image. The x and y positions can be specified in different ways—for example, x can be in pixels and y can be a fraction. The origin of the coordinate system is in the lower left corner of the image. * * x - Either the number of pixels, a fractional component of the image, or a pixel inset indicating the x component of a point on the overlay image. * * y - Either the number of pixels, a fractional component of the image, or a pixel inset indicating the y component of a point on the overlay image. * * xunits - Units in which the x value is specified. A value of "fraction" indicates the x value is a fraction of the image. A value of "pixels" indicates the x value in pixels. A value of "insetPixels" indicates the indent from the right edge of the image. * * yunits - Units in which the y value is specified. A value of "fraction" indicates the y value is a fraction of the image. A value of "pixels" indicates the y value in pixels. A value of "insetPixels" indicates the indent from the top edge of the image. */ overlayXY: 'overlayXY', /** * Specifies a point relative to the screen origin that the overlay image is mapped to. The x and y values can be specified in three different ways: as pixels ("pixels"), as fractions of the screen ("fraction"), or as inset pixels ("insetPixels"), which is an offset in pixels from the upper right corner of the screen. The x and y positions can be specified in different ways—for example, x can be in pixels and y can be a fraction. The origin of the coordinate system is in the lower left corner of the screen. * * x - Either the number of pixels, a fractional component of the screen, or a pixel inset indicating the x component of a point on the screen. * * y - Either the number of pixels, a fractional component of the screen, or a pixel inset indicating the y component of a point on the screen. * * xunits - Units in which the x value is specified. A value of "fraction" indicates the x value is a fraction of the screen. A value of "pixels" indicates the x value in pixels. A value of "insetPixels" indicates the indent from the right edge of the screen. * * yunits - Units in which the y value is specified. A value of fraction indicates the y value is a fraction of the screen. A value of "pixels" indicates the y value in pixels. A value of "insetPixels" indicates the indent from the top edge of the screen. */ screenXY: 'screenXY', /** * Point relative to the screen about which the screen overlay is rotated. */ rotationXY: 'rotationXY', /** * Specifies the size of the image for the screen overlay, as follows: * * A value of −1 indicates to use the native dimension * * A value of 0 indicates to maintain the aspect ratio * * A value of n sets the value of the dimension */ size: 'size', /** * Indicates the angle of rotation of the parent object. * A value of 0 means no rotation. * The value is an angle in degrees counterclockwise starting from north. * Use ±180 to indicate the rotation of the parent object from 0. The center of the <rotation>, if not (.5,.5), is specified in <rotationXY>. */ rotation: ROTATION_TAG, }; /** * Within Style tags these defined how different parts of the geometry should look like. */ export const STYLE_TYPE_TAGS = { /** * Not Currently supported */ BALLOON_STYLE: BALLOON_STYLE_TAG, ICON_STYLE: ICON_STYLE_TAG, /** * Not Currently supported */ LABEL_STYLE: LABEL_STYLE_TAG, LINE_STYLE: LINE_STYLE_TAG, /** * Not Currently supported */ LIST_STYLE: LIST_STYLE_TAG, POLY_STYLE: POLY_STYLE_TAG, }; /** * The <gx:x>, <gx:y>, <gx:w>, and <gx:h> elements are used to select one icon from an image that contains multiple icons (often referred to as an icon palette. */ export const ICON_PALLET_SELECTOR = { /** * If the <href> specifies an icon palette, these elements identify the offsets, in pixels, from the lower-left corner of the icon palette.If no values are specified for x and y, the lower left corner of the icon palette is assumed to be the lower-left corner of the icon to use. */ X_POSITION: GX_X_TAG, /** * If the <href> specifies an icon palette, these elements identify the offsets, in pixels, from the lower-left corner of the icon palette.If no values are specified for x and y, the lower left corner of the icon palette is assumed to be the lower-left corner of the icon to use. */ Y_POSITION: GX_Y_TAG, /** * If the <href> specifies an icon palette, these elements specify the width (<gx:w>) and height (<gx:h>), in pixels, of the icon to use. */ WIDTH: GX_W_TAG, /** * If the <href> specifies an icon palette, these elements specify the width (<gx:w>) and height (<gx:h>), in pixels, of the icon to use. */ HEIGHT: GX_H_TAG, }; /** * Define the location of the Icon's anchor */ export const HOTSPOT_TAG_DESCRIPTORS = { /** * xunits - Units in which the x value is specified. A value of fraction indicates the x value is a fraction of the icon. A value of pixels indicates the x value in pixels. A value of insetPixels indicates the indent from the right edge of the icon. */ X_UNITS_DESCRIPTOR: X_UNITS_DESCRIPTOR, /** * yunits - Units in which the y value is specified. A value of fraction indicates the y value is a fraction of the icon. A value of pixels indicates the y value in pixels. A value of insetPixels indicates the indent from the top edge of the icon. */ Y_UNITS_DESCRIPTOR: Y_UNITS_DESCRIPTOR, /** * x - Either the number of pixels, a fractional component of the icon, or a pixel inset indicating the x component of a point on the icon. */ X_COMPONENT_DESCRIPTOR: X_COMPONENT_DESCRIPTOR, /** * y - Either the number of pixels, a fractional component of the icon, or a pixel inset indicating the y component of a point on the icon. */ Y_COMPONENT_DESCRIPTOR: Y_COMPONENT_DESCRIPTOR, }; export const ITEM_TO_SEARCH_WITHIN = [GEOMETRY_TAGS.LINESTRING, GEOMETRY_TAGS.POINT, GEOMETRY_TAGS.POLYGON]; export const INNER_ITEMS_TO_IGNORE = [COORDINATES_TAG, OUTER_BOUNDARY_TAG, INNER_BOUNDARY_TAG];
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace Formmsdyn_iotdevice_Information { interface Header extends DevKit.Controls.IHeader { /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface tab__1BCFF70D_5615_4084_953F_2196583D6E79_Sections { _A9378EBB_2FCC_41B7_8039_B2B2A89490E2: DevKit.Controls.Section; Connected_Device_Readings: DevKit.Controls.Section; Device_Summary_Visualization: DevKit.Controls.Section; DeviceSettingsSection: DevKit.Controls.Section; DeviceStatusSection: DevKit.Controls.Section; } interface tab_AlertsTab_Sections { AlertsSection: DevKit.Controls.Section; } interface tab_CommandsTab_Sections { CommandsSection: DevKit.Controls.Section; } interface tab_Device_Data_Sections { Device_Data: DevKit.Controls.Section; } interface tab_DeviceInsightsTab_Sections { DeviceInsightsSection: DevKit.Controls.Section; } interface tab_RegistrationHistory_Sections { RegistrationHistorySection: DevKit.Controls.Section; } interface tab__1BCFF70D_5615_4084_953F_2196583D6E79 extends DevKit.Controls.ITab { Section: tab__1BCFF70D_5615_4084_953F_2196583D6E79_Sections; } interface tab_AlertsTab extends DevKit.Controls.ITab { Section: tab_AlertsTab_Sections; } interface tab_CommandsTab extends DevKit.Controls.ITab { Section: tab_CommandsTab_Sections; } interface tab_Device_Data extends DevKit.Controls.ITab { Section: tab_Device_Data_Sections; } interface tab_DeviceInsightsTab extends DevKit.Controls.ITab { Section: tab_DeviceInsightsTab_Sections; } interface tab_RegistrationHistory extends DevKit.Controls.ITab { Section: tab_RegistrationHistory_Sections; } interface Tabs { _1BCFF70D_5615_4084_953F_2196583D6E79: tab__1BCFF70D_5615_4084_953F_2196583D6E79; AlertsTab: tab_AlertsTab; CommandsTab: tab_CommandsTab; Device_Data: tab_Device_Data; DeviceInsightsTab: tab_DeviceInsightsTab; RegistrationHistory: tab_RegistrationHistory; } interface Body { Tab: Tabs; /** Parent customer of this device */ msdyn_Account: DevKit.Controls.Lookup; /** The device category that this IoT device belongs to. */ msdyn_Category: DevKit.Controls.Lookup; /** The connection status of the device (Disconnected or Connected) */ msdyn_ConnectionState: DevKit.Controls.Boolean; /** Device ID used to register with the IoT provider. */ msdyn_DeviceId: DevKit.Controls.String; /** Device ID used to register with the IoT provider. */ msdyn_DeviceId_1: DevKit.Controls.String; /** Device ID used to register with the IoT provider. */ msdyn_DeviceId_2: DevKit.Controls.String; /** Reported Properties data for Device */ msdyn_DeviceReportedProperties: DevKit.Controls.String; /** Reported Properties data for Device */ msdyn_DeviceReportedProperties_1: DevKit.Controls.String; /** The editable properties for a device. */ msdyn_DeviceSettings: DevKit.Controls.String; /** The editable properties for a device. */ msdyn_DeviceSettings_1: DevKit.Controls.String; /** The IoT Provider Instance to which this device belongs. */ msdyn_IoTProviderInstance: DevKit.Controls.Lookup; /** Select “Yes” if this device is simulated for testing and development purposes. Select “No” if this is a real device.​ */ msdyn_IsSimulated: DevKit.Controls.OptionSet; /** The last activity time of the device */ msdyn_LastActivityTime: DevKit.Controls.DateTime; /** The name of the custom entity. */ msdyn_name: DevKit.Controls.String; /** A message field that explains the IoT Registration Status. */ msdyn_RegistrationMessage: DevKit.Controls.String; /** A status field that denotes whether the device is registered with the IoT provider. */ msdyn_RegistrationStatus: DevKit.Controls.OptionSet; /** Identifying Tags for the Device */ msdyn_Tags: DevKit.Controls.String; /** Identifying Tags for the Device */ msdyn_Tags_1: DevKit.Controls.String; /** The device's time zone. */ msdyn_Timezone: DevKit.Controls.Integer; WebResource_PowerBIDevice: DevKit.Controls.WebResource; } interface Grid { DeviceDataHistory: DevKit.Controls.Grid; AlertsGrid: DevKit.Controls.Grid; CommandsGrid: DevKit.Controls.Grid; RegistrationHistory: DevKit.Controls.Grid; } } class Formmsdyn_iotdevice_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyn_iotdevice_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 msdyn_iotdevice_Information */ Body: DevKit.Formmsdyn_iotdevice_Information.Body; /** The Header section of form msdyn_iotdevice_Information */ Header: DevKit.Formmsdyn_iotdevice_Information.Header; /** The Grid of form msdyn_iotdevice_Information */ Grid: DevKit.Formmsdyn_iotdevice_Information.Grid; } namespace FormIoT_Device_MFD { interface tab__D56B7A88_6981_4F4B_9AE2_6D1AEC457231_Sections { _column_2_section_1: DevKit.Controls.Section; _column_3_section_1: DevKit.Controls.Section; _804F2D0A_D93D_400B_9A90_B1C0D9992B5F: DevKit.Controls.Section; Device_Data: DevKit.Controls.Section; } interface tab__D56B7A88_6981_4F4B_9AE2_6D1AEC457231 extends DevKit.Controls.ITab { Section: tab__D56B7A88_6981_4F4B_9AE2_6D1AEC457231_Sections; } interface Tabs { _D56B7A88_6981_4F4B_9AE2_6D1AEC457231: tab__D56B7A88_6981_4F4B_9AE2_6D1AEC457231; } interface Body { Tab: Tabs; /** The connection status of the device (Disconnected or Connected) */ msdyn_ConnectionState: DevKit.Controls.Boolean; /** Reported Properties data for Device */ msdyn_DeviceReportedProperties: DevKit.Controls.String; /** The editable properties for a device. */ msdyn_DeviceSettings: DevKit.Controls.String; /** The last activity time of the device */ msdyn_LastActivityTime: DevKit.Controls.DateTime; /** The name of the custom entity. */ msdyn_name: DevKit.Controls.String; /** Identifying Tags for the Device */ msdyn_Tags: DevKit.Controls.String; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface Grid { DeviceDataHistory: DevKit.Controls.Grid; } } class FormIoT_Device_MFD extends DevKit.IForm { /** * DynamicsCrm.DevKit form IoT_Device_MFD * @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 IoT_Device_MFD */ Body: DevKit.FormIoT_Device_MFD.Body; /** The Grid of form IoT_Device_MFD */ Grid: DevKit.FormIoT_Device_MFD.Grid; } class msdyn_iotdeviceApi { /** * DynamicsCrm.DevKit msdyn_iotdeviceApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Parent customer of this device */ msdyn_Account: DevKit.WebApi.LookupValue; /** The device category that this IoT device belongs to. */ msdyn_Category: DevKit.WebApi.LookupValue; /** The connection status of the device (Disconnected or Connected) */ msdyn_ConnectionState: DevKit.WebApi.BooleanValue; /** Device ID used to register with the IoT provider. */ msdyn_DeviceId: DevKit.WebApi.StringValue; /** Reported Properties data for Device */ msdyn_DeviceReportedProperties: DevKit.WebApi.StringValue; /** The editable properties for a device. */ msdyn_DeviceSettings: DevKit.WebApi.StringValue; /** Unique identifier for entity instances */ msdyn_iotdeviceId: DevKit.WebApi.GuidValue; /** The IoT Provider Instance to which this device belongs. */ msdyn_IoTProviderInstance: DevKit.WebApi.LookupValue; /** Select “Yes” if this device is simulated for testing and development purposes. Select “No” if this is a real device.​ */ msdyn_IsSimulated: DevKit.WebApi.OptionSetValue; /** The last activity time of the device */ msdyn_LastActivityTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; msdyn_LastCommandSent: DevKit.WebApi.LookupValue; msdyn_LastCommandSentTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** The name of the custom entity. */ msdyn_name: DevKit.WebApi.StringValue; /** A message field that explains the IoT Registration Status. */ msdyn_RegistrationMessage: DevKit.WebApi.StringValue; /** A status field that denotes whether the device is registered with the IoT provider. */ msdyn_RegistrationStatus: DevKit.WebApi.OptionSetValue; /** Identifying Tags for the Device */ msdyn_Tags: DevKit.WebApi.StringValue; /** The device's time zone. */ msdyn_Timezone: DevKit.WebApi.IntegerValue; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier 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; /** Status of the IoT Device */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the IoT Device */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace msdyn_iotdevice { enum msdyn_IsSimulated { /** 192350001 */ No, /** 192350000 */ Yes } enum msdyn_RegistrationStatus { /** 192350004 */ Error, /** 192350002 */ In_Progress, /** 192350003 */ Registered, /** 192350000 */ Unknown, /** 192350001 */ Unregistered } enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 2 */ Inactive } 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','IoT Device MFD'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import axios, { AxiosRequestConfig } from "axios"; import crypto from "crypto"; import http from "http"; import querystring from "querystring"; import { isNumber } from "util"; import { ICommonResponseBody, ITTSResponseBody } from "./responsemessage"; export class Client { /** * 语音听写服务请求地址 * @type {string} * @memberof Client */ public IATServiceEndPoint: string = "http://api.xfyun.cn/v1/service/v1/iat"; /** * 语音合成服务请求地址 * @type {string} * @memberof Client */ public TTSServiceEndPoint: string = "http://api.xfyun.cn/v1/service/v1/tts"; /** * 语音评测服务请求地址 * @type {string} * @memberof Client */ public ISEServiceEndPoint: string = "http://api.xfyun.cn/v1/service/v1/ise"; /** * 应用ID * * @type {string} * @memberof Client */ public AppID: string; /** * 代理服务器 * * @type {IProxyConfig} * @memberof Client */ public Proxy?: IProxyConfig; /** * 语音听写服务 AppKey * * @type {string} * @memberof Client */ public IATAppKey?: string; /** * 语音合成 AppKey * * @type {string} * @memberof Client */ public TTSAppKey?: string; /** * 语音评测 AppKey * * @type {string} * @memberof Client */ public ISEAppKey?: string; /** * 建立一个讯飞 WebAPI 客户端实例 * @param {string} appid 应用程序 AppID * @param {string} [iatappkey] 语音听写服务的 AppKey * @param {string} [ttsappkey] 语音合成服务的 AppKey * @param {string} [iseappkey] 语音评测服务的 AppKey * @memberof Client */ constructor(appid: string, iatappkey?: string, ttsappkey?: string, iseappkey?: string) { this.AppID = appid; this.IATAppKey = iatappkey; this.TTSAppKey = ttsappkey; this.ISEAppKey = iseappkey; } /** * 语音合成请求 * @param {string} text 要合成的文本 * @param {(TTSAufType | string)} auf 音频采样率 * @param {(TTSAueType | string)} aue 音频编码格式 * @param {(TTSVoiceName | string)} voicename 发音人 * @param {number} [speed] 语速,可选值[0~100],默认50 * @param {number} [volume] 音量,可选值[0~100],默认50 * @param {number} [pitch] 音高,可选值[0~100],默认50 * @param {(TTSEngineType | string)} [enginetype] 引擎类型,默认为 inpt65 * @param {(TTSTextType | string)} [texttype] 文本类型,默认为 text * @returns {Promise<ITTSResponseBody>} * @memberof Client */ public async TTS( text: string, auf: TTSAufType | string, aue: TTSAueType | string, voicename: TTSVoiceName | string = TTSVoiceName.XiaoYan, speed: number = 50, volume: number = 50, pitch: number = 50, enginetype: TTSEngineType | string = TTSEngineType.INTP65CN, texttype: TTSTextType | string = TTSTextType.TEXT) : Promise<ITTSResponseBody> { return new Promise<ITTSResponseBody>((resolve, reject) => { try { if (this.TTSAppKey === undefined) { reject("尚未设定语音合成服务的 AppKey"); } speed = Math.max(Math.min(Math.floor(speed), 100), 0); volume = Math.max(Math.min(Math.floor(volume), 100), 0); pitch = Math.max(Math.min(Math.floor(pitch), 100), 0); const requestParams = { auf, aue, voice_name: voicename, speed: speed ? speed.toFixed(0) : undefined, volume: volume ? volume.toFixed(0) : undefined, pitch: pitch ? pitch.toFixed(0) : undefined, engine_type: enginetype, text_type: texttype, }; const requestParamsJson = JSON.stringify(requestParams); const requestConfig: AxiosRequestConfig = this.SetRequestParams(requestParamsJson, this.TTSAppKey as string); requestConfig.responseType = "arraybuffer"; const requestData = querystring.stringify({ text }); axios.post(this.TTSServiceEndPoint, requestData, requestConfig) .then((response) => { const result: ITTSResponseBody = {}; if (response.headers["content-type"] === "audio/mpeg") { result.sid = response.headers.sid; result.audio = new Buffer(response.data, "binary"); } else if (response.headers["content-type"] === "text/plain") { const x = new Buffer(response.data, "utf8"); const resultString = x.toString("utf8"); const resultObject = JSON.parse(resultString); result.code = resultObject.code; result.desc = resultObject.desc; result.sid = resultObject.sid; } else { reject("请求中发生未知错误"); } resolve(result); }) .catch((reason) => { reject(reason); }); } catch (error) { reject(error); } }); } /** * 语音识别 * @param {(any[] | Buffer | ArrayBuffer)} audio 音频数据。 * @param {(IATEngineType | string)} enginetype 引擎类型,例如:sms16k(16k采样率普通话音频)、sms8k(8k采样率普通话音频)等,其他参见引擎类型说明 * @param {(IATAueType | string)} aue 音频编码,可选值:raw(未压缩的pcm或wav格式)、speex(speex格式)、speex-wb(宽频speex格式) * @param {(string | number)} [speexsize] speex音频帧率,speex音频必传 * @param {string} [scene] 情景模式 * @param {number} vadeos 后端点检测(单位:ms),默认1800 * @returns {Promise<IResponseBody>} 讯飞返回的信息 * @memberof Client */ public async IAT( audio: any[] | Buffer | ArrayBuffer, enginetype: IATEngineType | string, aue: IATAueType | string, speexsize?: string | number, scene?: string, vadeos: number = 1800) : Promise<ICommonResponseBody> { return new Promise<ICommonResponseBody>((resolve, reject) => { try { if (this.IATAppKey === undefined) { reject("尚未设定语音听写服务的 AppKey"); } const requestParams = { engine_type: enginetype, aue, speexsize: speexsize ? speexsize.toString() : undefined, scene: scene ? encodeURIComponent(scene) : undefined, vadeos: vadeos ? vadeos.toString() : undefined, }; const requestParamsJson = JSON.stringify(requestParams); const requestConfig: AxiosRequestConfig = this.SetRequestParams(requestParamsJson, this.IATAppKey as string); const requestData = querystring.stringify({ audio: this.GetEncodedContent(audio) }); axios.post(this.IATServiceEndPoint, requestData, requestConfig) .then((response) => { resolve({ code: response.data.code, data: response.data.data, desc: response.data.desc, sid: response.data.sid, }); }) .catch((reason) => { reject(reason); }); } catch (error) { reject(error); } }); } /** * 语音评测 * * @param {(any[] | Buffer | ArrayBuffer)} audio 音频数据 * @param {string} text 要对比的文本 * @param {(ISEAueType | string)} aue 音频编码,可选值:raw(未压缩的 pcm 格式音频)、speex * @param {(ISELanguageType | string)} language 评测语种,可选值: en(英语)、cn(汉语) * @param {(ISECategoryType | string)} category 评测题型,可选值: read_syllable(单字朗读,汉语专有)、 read_word(词语朗读)、 read_sentence(句子朗读)、read_chapter(段落朗读,需开通权限) * @param {(ISEResultLevelType | string)} [resultlevel=ISEResultLevelType.COMPLETE] 评测结果等级,可选值: plain(精简),complete(完整),默认为 complete * @param {number} [speexsize] 标准speex解码帧的大小(当aue=speex时,若传此参数,表明音频格式为标准speex;若不传,表明音频格式为讯飞定制speex) * @param {ISEExtraAbilityType} [extraability] 拓展能力(内测中,暂不支持),可选值:multi_dimension(全维度)、chapter(段落评测) * @returns {Promise<ICommonResponseBody>} * @memberof Client * @see 有空再补充返回结果的内容吧 http://doc.xfyun.cn/ise_protocol/%E8%AF%84%E6%B5%8B%E7%BB%93%E6%9E%9C%E6%A0%BC%E5%BC%8F.html */ public async ISE( audio: any[] | Buffer | ArrayBuffer, text: string, aue: ISEAueType | string, language: ISELanguageType | string, category: ISECategoryType | string, resultlevel: ISEResultLevelType | string = ISEResultLevelType.COMPLETE, speexsize?: number, extraability?: ISEExtraAbilityType, ): Promise<ICommonResponseBody> { return new Promise<ICommonResponseBody>(async (resolve, reject) => { try { if (this.ISEAppKey === undefined) { reject("尚未设定语音评测服务的 AppKey"); } const requestParams = { aue, speex_size: speexsize ? Math.floor(speexsize).toString() : undefined, result_level: resultlevel, language, category, extra_ability: extraability, }; const requestParamsJson = JSON.stringify(requestParams); const requestConfig: AxiosRequestConfig = this.SetRequestParams(requestParamsJson, this.ISEAppKey as string); const requestData = querystring.stringify({ audio: this.GetEncodedContent(audio), text }); const result = await axios.post<ICommonResponseBody>(this.ISEServiceEndPoint, requestData, requestConfig); resolve(result.data); } catch (error) { reject(error); } }); } private SetRequestParams(requestParamsJson: string, appkey: string) { const xAppid = this.AppID; const xParam = Buffer.from(requestParamsJson).toString("base64"); const xCurTime = Math.floor((new Date()).valueOf() / 1000); const md5 = crypto.createHash("md5"); const xCheckSum = md5.update(appkey + xCurTime + xParam).digest("hex"); const requestConfig: AxiosRequestConfig = { headers: { "X-Appid": xAppid, "X-CurTime": xCurTime, "X-Param": xParam, "X-CheckSum": xCheckSum, "Content-Type": "application/x-www-form-urlencoded; charset=utf-8", }, }; if (this.Proxy) { requestConfig.proxy = this.Proxy; } return requestConfig; } private GetEncodedContent(fileContent: any[] | Buffer | ArrayBuffer | string) { // 理论上这里使用 encodeURIComponent 更加合理,不知道为毛线讯飞服务端使用的 encodeURI,所以只能这样了 const base64ed = encodeURI(Buffer.from(fileContent).toString("base64")); return base64ed; } } /** * 语音评测音频格式 * * @export * @enum {number} */ export enum ISEAueType { /** * 未压缩的pcm或者wav格式 */ RAW = "raw", /** * speex格式 */ SPEEX = "speex", } /** * 语音评测语言类型 * * @export * @enum {number} */ export enum ISELanguageType { /** * 中文 */ CN = "cn", /** * 英文 */ EN = "en", } /** * 评测结果类型 * * @export * @enum {number} */ export enum ISEResultLevelType { /** * 精简 */ PLAIN = "plain", /** * 完整 */ COMPLETE = "complete", } /** * 评测类型 * * @export * @enum {number} */ export enum ISECategoryType { /** * 单字,汉语特有 */ SYLLABLE = "read_syllable", /** * 单词 */ WORD = "read_word", /** * 句子 */ SENTENCE = "read_sentence", /** * 段落 */ CHAPTER = "read_chapter", } /** * 扩展能力 * * @export * @enum {number} */ export enum ISEExtraAbilityType { /** * 全维度 */ MULTI_DIMENSION = "multi_dimension", /** * 段落 */ CHAPTER = "chapter", } /** * 文本类型,目前仅可传入 "text" * * @export * @enum {number} */ export enum TTSTextType { /** * 普通格式文本 */ TEXT = "text", } /** * 引擎类型 * * @export * @enum {string} */ export enum TTSEngineType { /** * 普通效果 */ AISound = "aisound", /** * 中文 */ INTP65CN = "intp65", /** * 英文 */ INTP65EN = "intp65_en", /** * 小语种 */ MTTS = "mtts", /** * 优化效果 */ X = "x", } /** * TTS服务的音频采样率 * * @export * @enum {string} */ export enum TTSAufType { L16_8K = "audio/L16;rate=8000", L16_16K = "audio/L16;rate=16000", } /** * TTS的音频编码类型 * * @export * @enum {string} */ export enum TTSAueType { /** * 未压缩的pcm或者wav格式 */ RAW = "raw", /** * mp3格式 */ LAME = "lame", } /** * TTS发音人 * * @export * @enum {string} */ export enum TTSVoiceName { /** * 晓燕 */ XiaoYan = "xiaoyan", } /** * IAT引擎类型 * @export * @enum {string} */ export enum IATEngineType { /** * 8K采样率普通话 */ SMS8K_Mandarin = "sms8k", /** * 16k采样率普通话 */ SMS16K_Mandarin = "sms16k", /** * 8k采样率英语 */ SMS8K_English = "sms-en8k", /** * 16k采样率英语 */ SMS16K_English = "sms-en16k", } /** * IAT的音频编码 * @export * @enum {string} */ export enum IATAueType { /** * 未压缩的pcm或wav格式 */ RAW = "raw", /** * speex格式 */ SPEEX = "speex", /** * 宽频speex格式 */ SPEEX_WB = "speex-wb", } /** * 代理服务器的身份验证 * * @export * @interface IProxyAuth */ export interface IProxyAuth { /** * 用户名 * * @type {string} */ username: string; /** * 密码 * * @type {string} */ password: string; } /** * 代理服务器 * * @export * @interface IProxyConfig */ export interface IProxyConfig { /** * 代理服务器地址 * * @type {string} * @memberof IProxyConfig */ host: string; /** * 代理服务器端口 * * @type {number} * @memberof IProxyConfig */ port: number; /** * 代理服务器的身份验证 * * @type {IProxyAuth} * @memberof IProxyConfig */ auth?: IProxyAuth; }
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview A jQueryUI plugin that lets the user switch pages in a report. */ namespace VRS { /* * Global options */ export var globalOptions: GlobalOptions = VRS.globalOptions || {}; VRS.globalOptions.reportPagerClass = VRS.globalOptions.reportPagerClass || 'reportPager'; // The class to use for the report pager widget container. VRS.globalOptions.reportPagerSpinnerPageSize = VRS.globalOptions.reportPagerSpinnerPageSize || 5; // The number of pages to skip when paging up and down through the page number spinner. VRS.globalOptions.reportPagerAllowPageSizeChange = VRS.globalOptions.reportPagerAllowPageSizeChange !== undefined ? VRS.globalOptions.reportPagerAllowPageSizeChange : true; // True if the user can change the report page size, false if they cannot. VRS.globalOptions.reportPagerAllowShowAllRows = VRS.globalOptions.reportPagerAllowShowAllRows !== undefined ? VRS.globalOptions.reportPagerAllowShowAllRows : true; // True if the user is allowed to show all rows simultaneously, false if they're not. /** * The options for the ReportPagerPlugin. */ export interface ReportPagerPlugin_Options { /** * The name to save state under. */ name?: string; /** * The report whose flights we're going to page. */ report: Report; /** * True if the user is allowed to change the page size, false if they're not. */ allowPageSizeChange?: boolean; /** * True if the user is allowed to show all rows simultaneously, false if they're not. Ignored if allowPageSizeChange is false. */ allowShowAllRows?: boolean; } /** * The state for the ReportPagerPlugin. */ class ReportPagerPlugin_State { /** * The container for the page selection panel. */ pageSelectionPanelElement: JQuery = null; /** * The element for the first page button. */ firstPageElement: JQuery = null; /** * The element for the previous page button. */ prevPageElement: JQuery = null; /** * The element for the next page button. */ nextPageElement: JQuery = null; /** * The element for the last page button. */ lastPageElement: JQuery = null; /** * The element for the page selector control. */ pageSelectorElement: JQuery = null; /** * The element for the display of the total number of pages in the report. */ countPagesElement: JQuery = null; /** * The element that the user can click to fetch the selected page. */ fetchPageElement: JQuery = null; /** * The element that contains all of the page size modification elements. */ pageSizePanelElement: JQuery = null; /** * The element for the control that the user can enter page sizes into. */ pageSizeSelectElement: JQuery = null; /** * True if we are not to react to changes to the page size control. */ suppressPageSizeChangedByUs: boolean = false; /** * The hook result for the report's rows fetched event. */ rowsFetchedHookResult: IEventHandle = null; /** * The hook result for the report's page size changed event. */ pageSizeChangedHookResult: IEventHandle = null; } /* * jQueryUIHelper methods */ export var jQueryUIHelper: JQueryUIHelper = VRS.jQueryUIHelper || {}; VRS.jQueryUIHelper.getReportPagerPlugin = function(jQueryElement: JQuery) : ReportPagerPlugin { return jQueryElement.data('vrsVrsReportPager'); } VRS.jQueryUIHelper.getReportPagerOptions = function(overrides?: ReportPagerPlugin_Options) : ReportPagerPlugin_Options { return $.extend({ name: 'default', // The name to save state under. report: null, // The report whose flights we're going to page. allowPageSizeChange: VRS.globalOptions.reportPagerAllowPageSizeChange, // True if the user is allowed to change the page size, false if they're not. allowShowAllRows: VRS.globalOptions.reportPagerAllowShowAllRows, // True if the user is allowed to show all rows simultaneously, false if they're not. Ignored if allowPageSizeChange is false. }, overrides); } /** * A jQuery widget that can display a pager strip for the reports. */ export class ReportPagerPlugin extends JQueryUICustomWidget { options: ReportPagerPlugin_Options; constructor() { super(); this.options = VRS.jQueryUIHelper.getReportPagerOptions(); } private _getState() : ReportPagerPlugin_State { var result = this.element.data('reportPagerState'); if(result === undefined) { result = new ReportPagerPlugin_State(); this.element.data('reportPagerState', result); } return result; } _create() { var state = this._getState(); var options = this.options; this.element.addClass(VRS.globalOptions.reportPagerClass); var controls = $('<div/>') .addClass('controls') .appendTo(this.element); this._createPageSelectionPanel(state, controls); this._createPageSizePanel(state, controls); state.rowsFetchedHookResult = options.report.hookRowsFetched(this._rowsFetched, this); state.pageSizeChangedHookResult = options.report.hookPageSizeChanged(this._pageSizeChanged, this); } _destroy() { var state = this._getState(); var options = this.options; if(state.rowsFetchedHookResult && options.report) { options.report.unhook(state.rowsFetchedHookResult); } state.rowsFetchedHookResult = null; if(state.pageSizeChangedHookResult && options.report) { options.report.unhook(state.pageSizeChangedHookResult); } state.pageSizeChangedHookResult = null; this._destroyPageSelectionPanel(state); this._destroyPageSizePanel(state); } /** * Creates the page selection panel. */ private _createPageSelectionPanel(state: ReportPagerPlugin_State, container: JQuery) { this._destroyPageSelectionPanel(state); state.pageSelectionPanelElement = $('<ul/>') .addClass('pageSelection') .appendTo(container); var self = this; var addJumpElement = function(icon: string, clickHandler: () => void, tooltip: string, container?: JQuery) { if(!container) { container = $('<li/>').appendTo(state.pageSelectionPanelElement); } return $('<p/>') .appendTo(container) .text(tooltip) .prepend($('<span/>').addClass('vrsIcon vrsIcon-' + icon)) .on('click', $.proxy(clickHandler, self)); }; state.firstPageElement = addJumpElement('first', this._firstPageClicked, VRS.$$.PageFirst); state.prevPageElement = addJumpElement('backward', this._prevPageClicked, VRS.$$.PagePrevious); var pageSelectorContainer = $('<li/>').appendTo(state.pageSelectionPanelElement); state.pageSelectorElement = $('<input/>') .attr('type', 'text') .appendTo(pageSelectorContainer) .spinner({ page: VRS.globalOptions.reportPagerSpinnerPageSize }); state.countPagesElement = $('<span/>') .addClass('countPages') .appendTo(pageSelectorContainer); var fetchPageContainer = $('<li/>').appendTo(state.pageSelectionPanelElement); state.fetchPageElement = addJumpElement('loop', this._fetchPageClicked, VRS.$$.FetchPage, fetchPageContainer); state.nextPageElement = addJumpElement('forward', this._nextPageClicked, VRS.$$.PageNext); state.lastPageElement = addJumpElement('last', this._lastPageClicked, VRS.$$.PageLast); this._setPageSelectionPanelState(state); } /** * Tears down the page selection panel. */ private _destroyPageSelectionPanel(state: ReportPagerPlugin_State) { if(state.pageSelectionPanelElement) { var destroyJumpElement = function(buttonElement: JQuery) { if(buttonElement) { buttonElement.off(); } return null; }; state.firstPageElement = destroyJumpElement(state.firstPageElement); state.prevPageElement = destroyJumpElement(state.prevPageElement); state.nextPageElement = destroyJumpElement(state.nextPageElement); state.lastPageElement = destroyJumpElement(state.lastPageElement); state.fetchPageElement = destroyJumpElement(state.fetchPageElement); if(state.pageSelectorElement) { state.pageSelectorElement.spinner('destroy'); state.pageSelectorElement = null; } state.pageSelectionPanelElement.remove(); state.pageSelectionPanelElement = null; } } /** * Builds up the UI for the page size panel. */ private _createPageSizePanel(state: ReportPagerPlugin_State, container: JQuery) { var options = this.options; this._destroyPageSizePanel(state); if(VRS.globalOptions.reportDefaultStepSize > 0 && options.allowPageSizeChange) { state.pageSizePanelElement = $('<ul/>') .addClass('pageSize') .appendTo(container); var selectContainer = $('<li/>').appendTo(state.pageSizePanelElement); state.pageSizeSelectElement = $('<select/>') .appendTo(selectContainer) .uniqueId(); for(var i = 1;i <= 10;++i) { var rows = i * VRS.globalOptions.reportDefaultStepSize; $('<option/>') .attr('value', rows) .text(rows.toString()) .appendTo(state.pageSizeSelectElement); } if(options.allowShowAllRows) { $('<option/>') .attr('value', -1) .text(VRS.$$.AllRows) .appendTo(state.pageSizeSelectElement); } state.pageSizeSelectElement.val(options.report.getPageSize()); state.pageSizeSelectElement.change($.proxy(this._pageSizeChangedByUs, this)); $('<label/>') .attr('for', state.pageSizeSelectElement.attr('id')) .insertBefore(state.pageSizeSelectElement) .text(VRS.$$.Rows + ':') } } /** * Destroys the UI added for the page size panel. */ private _destroyPageSizePanel(state: ReportPagerPlugin_State) { if(state.pageSizePanelElement) { if(state.pageSizeSelectElement) state.pageSizeSelectElement.off(); state.pageSelectionPanelElement = null; state.pageSizePanelElement.remove(); state.pageSizePanelElement = null; } } /** * Sets the state of the page selection controls. */ private _setPageSelectionPanelState(state: ReportPagerPlugin_State) { var metrics = this._getPageMetrics(); var setJumpElementDisabled = function(jumpElement, disabled) { if(disabled) jumpElement.addClass('disabled'); else jumpElement.removeClass('disabled'); }; setJumpElementDisabled(state.firstPageElement, !metrics.isPaged || metrics.onFirstPage); setJumpElementDisabled(state.prevPageElement, !metrics.isPaged || metrics.onFirstPage); setJumpElementDisabled(state.nextPageElement, !metrics.isPaged || metrics.onLastPage); setJumpElementDisabled(state.lastPageElement, !metrics.isPaged || metrics.onLastPage); state.pageSelectorElement.val(1); state.pageSelectorElement.spinner('option', { min: 1, max: metrics.totalPages }); state.pageSelectorElement.val(metrics.currentPage + 1); state.countPagesElement.text(VRS.stringUtility.format(VRS.$$.OfPages, metrics.totalPages)); } /** * Returns an anonymous object that describes the page size */ private _getPageMetrics() { var report = this.options.report; var flights = report.getFlights(); var rowCount = report.getCountRowsAvailable(); var pageSize = report.getPageSize(); var firstRow = flights.length > 0 ? flights[0].row : 0; var lastRow = flights.length > 0 ? flights[flights.length - 1].row : 0; var isPaged = report.isReportPaged(); var currentPage = isPaged ? Math.max(0, Math.floor(firstRow / pageSize)) : 0; var totalPages = isPaged ? Math.max(1, Math.ceil(rowCount / pageSize)) : 1; return { isPaged: isPaged, pageSize: pageSize, currentPage: currentPage, totalPages: totalPages, onFirstPage: !isPaged || currentPage === 0, onLastPage: !isPaged || currentPage + 1 >= totalPages, pageFirstRow: firstRow, pageLastRow: lastRow }; } /** * Called after the report has fetched a new batch of rows. */ private _rowsFetched() { this._setPageSelectionPanelState(this._getState()); } /** * Called when the user clicks the first page button. */ private _firstPageClicked() { var metrics = this._getPageMetrics(); if(!metrics.onFirstPage) { this.options.report.fetchPage(0); } } /** * Called when the user clicks the previous page button. */ private _prevPageClicked() { var metrics = this._getPageMetrics(); if(!metrics.onFirstPage) { this.options.report.fetchPage(metrics.currentPage - 1); } } /** * Called when the user clicks the next page button. */ private _nextPageClicked() { var metrics = this._getPageMetrics(); if(!metrics.onLastPage) { this.options.report.fetchPage(metrics.currentPage + 1); } } /** * Called when the user clicks the last page button. */ private _lastPageClicked() { var metrics = this._getPageMetrics(); if(!metrics.onLastPage) { this.options.report.fetchPage(metrics.totalPages - 1); } } /** * Called when the user clicks the fetch page button. */ private _fetchPageClicked() { var state = this._getState(); var metrics = this._getPageMetrics(); var pageNumber = state.pageSelectorElement ? state.pageSelectorElement.val() : 0; if(pageNumber > 0 && pageNumber <= metrics.totalPages) { this.options.report.fetchPage(pageNumber - 1); } } /** * Called when something (including, but not limited to, this object) changes the page size held by the report. */ private _pageSizeChanged() { var state = this._getState(); if(state.pageSizeSelectElement && !state.suppressPageSizeChangedByUs) { state.suppressPageSizeChangedByUs = true; state.pageSizeSelectElement.val(this.options.report.getPageSize()); state.suppressPageSizeChangedByUs = false; } } /** * Called when the value in the page size control is changed, either by the user or by us. */ private _pageSizeChangedByUs() { var state = this._getState(); if(!state.suppressPageSizeChangedByUs) { state.suppressPageSizeChangedByUs = true; var report = this.options.report; var currentPageSize = report.getPageSize(); var newPageSize = parseInt(state.pageSizeSelectElement.val()); if(!isNaN(newPageSize) && newPageSize !== currentPageSize) { report.setPageSize(newPageSize); var metrics = this._getPageMetrics(); report.fetchPage(metrics.currentPage); } state.suppressPageSizeChangedByUs = false; } } } $.widget('vrs.vrsReportPager', new ReportPagerPlugin()); } declare interface JQuery { vrsReportPager(); vrsReportPager(options: VRS.ReportPagerPlugin_Options); vrsReportPager(methodName: string, param1?: any, param2?: any, param3?: any, param4?: any); }
the_stack
import React from 'react'; import {RootState} from '../../data/reducers'; import { BasicConfig, ContainerContextType, ExecTaskOptions, FormContextType, IteratorContextType, RCREContextType, TriggerContextType } from '../../types'; import {containerActionCreators} from '../Container/action'; import {RunTimeContextCollection, TriggerContext} from '../context'; import {componentLoader} from '../util/componentLoader'; import {getRuntimeContext, isPromise} from '../util/util'; import {formActions, TRIGGER_SET_DATA_OPTIONS, TRIGGER_SET_DATA_PAYLOAD} from './actions'; import {DataCustomer} from '../DataCustomer/index'; import {compileExpressionString, isExpression, parseExpressionString} from '../util/vm'; import {isObject} from 'lodash'; export class TriggerEventItem { /** * 事件名称 */ event: string; /** * 指定的目标DataCustomer */ targetCustomer?: string | string[]; targetTask: string | string[]; /** * 传递给目标的参数 */ params?: any; /** * 阻止冒泡 */ stopPropagation?: boolean; /** * 阻止默认事件 */ preventDefault?: boolean; /** * 延迟触发 */ debounce?: number; /** * 等待之后触发 */ wait?: number; /** * 调试模式 */ debug?: boolean; /** * 事件触发的条件 */ condition?: string; } export interface TriggerProps { model: string; dataCustomer: DataCustomer; /** * 当前trigger的数据模型 */ trigger: TriggerEventItem[]; /** * 来自RCRE的context对象 */ rcreContext: RCREContextType; /** * 来自Foreach组件的context对象 */ iteratorContext?: IteratorContextType; /** * 来自父级Container的context对象 */ containerContext: ContainerContextType; formContext?: FormContextType; } type UnCookedTriggerEventItem = { customers: string[], data: any; }; export class RCRETrigger<Config extends BasicConfig> extends React.Component<TriggerProps, {}> { private contextValue: TriggerContextType; private debounceCache: { isRunning: boolean; data: any }[]; constructor(props: TriggerProps) { super(props); this.debounceCache = []; this.eventHandle = this.eventHandle.bind(this); this.contextValue = { $trigger: null, eventHandle: this.eventHandle, execTask: this.execTask }; } private async runTaskQueue(taskQueue: TRIGGER_SET_DATA_PAYLOAD[]) { let runTime = getRuntimeContext(this.props.containerContext, this.props.rcreContext, { iteratorContext: this.props.iteratorContext }); let context: RunTimeContextCollection = { rcre: this.props.rcreContext, container: this.props.containerContext, iterator: this.props.iteratorContext, form: this.props.formContext }; let state: RootState = this.props.rcreContext.store.getState(); runTime.$trigger = state.$rcre.trigger[this.props.model]; let prev = null; while (taskQueue.length > 0) { let item = taskQueue.shift(); if (!item) { break; } runTime.$prev = prev; prev = await this.props.dataCustomer.execCustomer({ customer: item.customer, runTime, prev: prev, params: runTime.$trigger![item.customer], model: this.props.model, actions: { taskPass: (payload) => this.props.rcreContext.store.dispatch( containerActionCreators.dataCustomerPass(payload, context) ) }, options: item.options, rcreContext: this.props.rcreContext, containerContext: this.props.containerContext, iteratorContext: this.props.iteratorContext }); if (!prev && !(item.options && item.options.keepWhenError)) { break; } } return runTime.$trigger; } render() { return ( <TriggerContext.Provider value={this.contextValue}> {this.props.children} </TriggerContext.Provider> ); } private async postProcessEvent(itemP: Promise<UnCookedTriggerEventItem | undefined>, customerMap: object, options: TRIGGER_SET_DATA_OPTIONS = {}) { return itemP.then(item => { if (!item) { return; } let triggerItems: TRIGGER_SET_DATA_PAYLOAD[] = []; let group = this.props.dataCustomer.getGroups(); let taskQueue: TRIGGER_SET_DATA_PAYLOAD[] = []; for (let customer of item.customers) { let isGroup = group[customer]; if (isGroup) { group[customer].steps.forEach(groupItem => { let data = item.data; if (isObject(item.data)) { if (!customerMap[groupItem]) { customerMap[groupItem] = {}; } Object.assign(customerMap[groupItem], item.data); data = customerMap[groupItem]; } let conf = { model: this.props.model, customer: groupItem, data: data, options: { ...options, keepWhenError: group[customer].keepWhenError } }; taskQueue.push(conf); triggerItems.push(conf); }); } else { let data = item.data; if (isObject(item.data)) { if (!customerMap[customer]) { customerMap[customer] = {}; } Object.assign(customerMap[customer], item.data); data = customerMap[customer]; } let conf = { model: this.props.model, customer: customer, data: data, options: { ...options } }; taskQueue.push(conf); triggerItems.push(conf); } } this.props.rcreContext.store.dispatch(formActions.triggerSetData(triggerItems)); return this.runTaskQueue(taskQueue); }); } private execTask = async (targetTask: string, params: any, options?: ExecTaskOptions) => { console.log('execTask'); let event: TriggerEventItem = { event: '__INTENAL__', targetTask: targetTask, params: params, ...options }; let customerMap = {}; let execItem = this.execEvent(event, params, 0); return this.postProcessEvent(execItem, customerMap); } private async eventHandle(eventName: string, args: Object, options: { index?: number, preventSubmit?: boolean } = {}) { let eventList = this.props.trigger; let validEventList = eventList.filter(event => event.event === eventName); if (validEventList.length === 0) { return; } let customerMap = {}; if (options.index) { let execItem = this.execEvent(validEventList[options.index], args, options.index); await this.postProcessEvent(execItem, customerMap, { preventSubmit: options.preventSubmit }); return; } let pEvent: Promise<any>[] = validEventList.map((event, index) => { let execItem = this.execEvent(event, args, index); return this.postProcessEvent(execItem, customerMap, { preventSubmit: options.preventSubmit }); }); return await Promise.all(pEvent); } private async execEvent(event: TriggerEventItem, args: Object, index: number): Promise<UnCookedTriggerEventItem | undefined> { if (!event.targetCustomer && !event.targetTask) { console.warn('触发事件必须指定targetTask'); return; } let params = event.params || {}; let debug = event.debug; let targetCustomer = event.targetTask || event.targetCustomer || ''; if (event.wait) { await new Promise((resolve) => { setTimeout(() => { resolve(); }, event.wait); }); } if (typeof event.debounce === 'number') { if (!this.debounceCache[index]) { this.debounceCache[index] = { isRunning: true, data: args }; args = await new Promise((resolve) => { setTimeout(() => { let data = this.debounceCache[index].data; delete this.debounceCache[index]; resolve(data); }, event.debounce); }); } else { this.debounceCache[index].data = args; return; } } let runTime = getRuntimeContext(this.props.containerContext, this.props.rcreContext, { iteratorContext: this.props.iteratorContext }); let context = { ...runTime, $args: args }; if (event.stopPropagation && args['stopPropagation']) { args['stopPropagation'](); } if (event.preventDefault && args['preventDefault']) { args['preventDefault'](); } let output: any; if (isExpression(params)) { output = parseExpressionString(params, context); if (isPromise(output)) { output = await output; } } else { output = compileExpressionString(params, context, [], true); for (let key in output) { if (output.hasOwnProperty(key) && isPromise(output[key])) { output[key] = await output[key]; } } } let condition: boolean = true; if (isExpression(event.condition)) { condition = !!parseExpressionString(event.condition, context); } if (debug) { console.group(`RCRE trigger event`); console.log('event: ' + event.event); console.log('targetCustomer: ' + event.targetCustomer); console.log('params: ', event.params); console.log('params parsed output: ', output); console.log('condition: ', event.condition, 'result: ', condition); console.log('$args: ', args); console.groupEnd(); } if (!condition) { return; } if (typeof targetCustomer === 'string') { targetCustomer = [targetCustomer]; } targetCustomer = targetCustomer.map(customer => { if (isExpression(customer)) { customer = parseExpressionString(customer, runTime); } if (customer === '$this') { return '$SELF_PASS_CUSTOMER'; } if (customer === '$parent') { return '$PARENT_PASS_CUSTOMER'; } return customer; }); return { customers: targetCustomer, data: output }; } } componentLoader.addComponent('__TRIGGER__', RCRETrigger);
the_stack
import { expect } from "chai"; import { Subject } from "rxjs"; import { mapTo } from "rxjs/operators"; import * as sinon from "sinon"; import { tag } from "./operators"; import { Plugin } from "./plugin"; import { create } from "./spy-factory"; import { Spy } from "./spy-interface"; const options = { keptDuration: -1, keptValues: 4, warning: false }; describe("spy", () => { let spy: Spy; describe("flush", () => { let plugin: Plugin; beforeEach(() => { plugin = stubPlugin(); spy = create({ defaultPlugins: false, ...options }); spy.plug(plugin); }); it("should call the plugin's flush method", () => { spy.flush(); expect(plugin.flush).to.have.property("called", true); }); }); describe("let", () => { it("should apply the selector to the tagged observable", () => { spy = create({ defaultPlugins: false, ...options }); spy.let("people", (source) => source.pipe(mapTo("bob"))); const values: any[] = []; const subject = new Subject<string>(); const subscription = subject.pipe(tag("people")).subscribe((value) => values.push(value)); subject.next("alice"); expect(values).to.deep.equal(["bob"]); }); }); describe("log", () => { it("should log the tagged observable", () => { spy = create({ defaultPlugins: false, ...options }); const subject = new Subject<string>(); let calls: any[][] = []; spy.log("people", { log(...args: any[]): void { calls.push(args); } }); const subscription = subject.pipe(tag("people")).subscribe(); expect(calls).to.not.be.empty; expect(calls[0]).to.deep.equal(["Tag = people; notification = subscribe"]); calls = []; subject.next("alice"); expect(calls).to.not.be.empty; expect(calls[0]).to.deep.equal(["Tag = people; notification = next; value =", "alice"]); calls = []; subscription.unsubscribe(); expect(calls).to.not.be.empty; expect(calls[0]).to.deep.equal(["Tag = people; notification = unsubscribe"]); }); it("should log all/any tagged observables", () => { spy = create({ defaultPlugins: false, ...options }); const subject = new Subject<string>(); const calls: any[][] = []; spy.log({ log(...args: any[]): void { calls.push(args); } }); const subscription = subject.pipe(tag("people")).subscribe(); expect(calls).to.not.be.empty; expect(calls[0]).to.deep.equal(["Tag = people; notification = subscribe; matching /.+/"]); }); it("should support a notification match", () => { spy = create({ defaultPlugins: false, ...options }); const subject = new Subject<string>(); const calls: any[][] = []; spy.log(/people/, /next/, { log(...args: any[]): void { calls.push(args); } }); const subscription = subject.pipe(tag("people")).subscribe(); subject.next("alice"); subscription.unsubscribe(); expect(calls).to.not.be.empty; expect(calls[0]).to.deep.equal(["Tag = people; notification = next; matching /people/; value =", "alice"]); }); }); describe("pause", () => { it("should pause the tagged observable's subscriptions", () => { spy = create({ defaultPlugins: false, ...options }); const deck = spy.pause("people"); const values: any[] = []; const subject = new Subject<string>(); const subscription = subject.pipe(tag("people")).subscribe((value) => values.push(value)); subject.next("alice"); subject.next("bob"); expect(values).to.deep.equal([]); deck.resume(); expect(values).to.deep.equal(["alice", "bob"]); }); it("should resume upon teardown", () => { spy = create({ defaultPlugins: false, ...options }); const deck = spy.pause("people"); const values: any[] = []; const subject = new Subject<string>(); const subscription = subject.pipe(tag("people")).subscribe((value) => values.push(value)); subject.next("alice"); subject.next("bob"); expect(values).to.deep.equal([]); spy.teardown(); expect(values).to.deep.equal(["alice", "bob"]); }); }); describe("plugin", () => { let plugin: Plugin; beforeEach(() => { plugin = stubPlugin(); spy = create({ defaultPlugins: false, ...options }); spy.plug(plugin); }); it("should call the plugin subscribe/next/unsubscribe methods", () => { const subject = new Subject<string>(); const subscription = subject.subscribe(); expect(plugin.beforeSubscribe).to.have.property("calledOnce", true); expect(plugin.afterSubscribe).to.have.property("calledOnce", true); subject.next("alice"); expect(plugin.beforeNext).to.have.property("calledOnce", true); expect(plugin.afterNext).to.have.property("calledOnce", true); subscription.unsubscribe(); expect(plugin.beforeUnsubscribe).to.have.property("calledOnce", true); expect(plugin.afterUnsubscribe).to.have.property("calledOnce", true); }); it("should call the plugin subscribe/next/unsubscribe methods for each observable", () => { const subject = new Subject<string>(); const subscription = subject.pipe(mapTo("mallory")).subscribe(); expect(plugin.beforeSubscribe).to.have.property("calledTwice", true); expect(plugin.afterSubscribe).to.have.property("calledTwice", true); subject.next("alice"); expect(plugin.beforeNext).to.have.property("calledTwice", true); expect(plugin.afterNext).to.have.property("calledTwice", true); subscription.unsubscribe(); expect(plugin.beforeUnsubscribe).to.have.property("calledTwice", true); expect(plugin.afterUnsubscribe).to.have.property("calledTwice", true); }); it("should call the plugin unsubscribe methods only once", () => { const subject = new Subject<string>(); const subscription = subject.subscribe(); expect(plugin.beforeSubscribe).to.have.property("calledOnce", true); expect(plugin.afterSubscribe).to.have.property("calledOnce", true); subscription.unsubscribe(); expect(plugin.beforeUnsubscribe).to.have.property("calledOnce", true); expect(plugin.afterUnsubscribe).to.have.property("calledOnce", true); subscription.unsubscribe(); expect(plugin.beforeUnsubscribe).to.have.property("calledOnce", true); expect(plugin.afterUnsubscribe).to.have.property("calledOnce", true); }); it("should call the plugin unsubscribe methods on completion", () => { const subject = new Subject<string>(); const subscription = subject.subscribe(); expect(plugin.beforeSubscribe).to.have.property("calledOnce", true); expect(plugin.afterSubscribe).to.have.property("calledOnce", true); subject.complete(); expect(plugin.beforeUnsubscribe).to.have.property("calledOnce", true); expect(plugin.afterUnsubscribe).to.have.property("calledOnce", true); }); it("should call the plugin unsubscribe methods on error", () => { const subject = new Subject<string>(); const subscription = subject.subscribe(() => {}, () => {}); expect(plugin.beforeSubscribe).to.have.property("calledOnce", true); expect(plugin.afterSubscribe).to.have.property("calledOnce", true); subject.error(new Error("Boom!")); expect(plugin.beforeUnsubscribe).to.have.property("calledOnce", true); expect(plugin.afterUnsubscribe).to.have.property("calledOnce", true); }); it("should call the plugin unsubscribe methods when paused for explicit unsubscribes", () => { const subject = new Subject<string>(); const subscription = subject.pipe(tag("people")).subscribe(); expect(plugin.beforeSubscribe).to.have.property("calledTwice", true); expect(plugin.afterSubscribe).to.have.property("calledTwice", true); const deck = spy.pause("people"); subscription.unsubscribe(); expect(plugin.beforeUnsubscribe).to.have.property("calledTwice", true); expect(plugin.afterUnsubscribe).to.have.property("calledTwice", true); }); it("should call the plugin unsubscribe methods on resumed completion", () => { const subject = new Subject<string>(); const subscription = subject.pipe(tag("people")).subscribe(); expect(plugin.beforeSubscribe).to.have.property("calledTwice", true); expect(plugin.afterSubscribe).to.have.property("calledTwice", true); const deck = spy.pause("people"); subject.complete(); expect(plugin.beforeUnsubscribe).to.have.property("calledOnce", true); expect(plugin.afterUnsubscribe).to.have.property("calledOnce", true); deck.resume(); expect(plugin.beforeUnsubscribe).to.have.property("calledTwice", true); expect(plugin.afterUnsubscribe).to.have.property("calledTwice", true); }); it("should call the plugin unsubscribe methods on resumed error", () => { const subject = new Subject<string>(); const subscription = subject.pipe(tag("people")).subscribe(() => {}, () => {}); expect(plugin.beforeSubscribe).to.have.property("calledTwice", true); expect(plugin.afterSubscribe).to.have.property("calledTwice", true); const deck = spy.pause("people"); subject.error(new Error("Boom!")); expect(plugin.beforeUnsubscribe).to.have.property("calledOnce", true); expect(plugin.afterUnsubscribe).to.have.property("calledOnce", true); deck.resume(); expect(plugin.beforeUnsubscribe).to.have.property("calledTwice", true); expect(plugin.afterUnsubscribe).to.have.property("calledTwice", true); }); it("should call the plugin complete methods", () => { const subject = new Subject<string>(); const subscription = subject.subscribe(); expect(plugin.beforeSubscribe).to.have.property("calledOnce", true); expect(plugin.afterSubscribe).to.have.property("calledOnce", true); subject.complete(); expect(plugin.beforeComplete).to.have.property("calledOnce", true); expect(plugin.afterComplete).to.have.property("calledOnce", true); }); it("should call the plugin error methods", () => { const subject = new Subject<string>(); const subscription = subject.subscribe((value) => {}, (error) => {}); expect(plugin.beforeSubscribe).to.have.property("calledOnce", true); expect(plugin.afterSubscribe).to.have.property("calledOnce", true); subject.error(new Error("Boom!")); expect(plugin.beforeError).to.have.property("calledOnce", true); expect(plugin.afterError).to.have.property("calledOnce", true); }); }); describe("show", () => { it("should show snapshotted information for the tagged observable", () => { spy = create({ ...options }); const calls: any[][] = []; const subject = new Subject<number>(); const subscription = subject.pipe(tag("people")).subscribe(); spy.show("people", { log(...args: any[]): void { calls.push(args); } }); expect(calls).to.not.be.empty; expect(calls[0]).to.deep.equal(["1 snapshot(s) matching people"]); expect(calls[1]).to.deep.equal([" Tag = people"]); }); it("should show snapshotted information all/any tagged observables", () => { spy = create({ ...options }); const calls: any[][] = []; const subject = new Subject<number>(); const subscription = subject.pipe(tag("people")).subscribe(); spy.show({ log(...args: any[]): void { calls.push(args); } }); expect(calls).to.not.be.empty; expect(calls[0]).to.deep.equal(["1 snapshot(s) matching /.+/"]); expect(calls[1]).to.deep.equal([" Tag = people"]); }); }); describe("stats", () => { it("should show the stats", () => { spy = create({ ...options }); const calls: any[][] = []; const subject = new Subject<number>(); const subscription = subject.subscribe(); spy.stats({ log(...args: any[]): void { calls.push(args); } }); expect(calls).to.not.be.empty; expect(calls[0]).to.deep.equal(["Stats"]); expect(calls[1]).to.deep.equal([" Subscribes =", 1]); expect(calls[2]).to.deep.equal([" Root subscribes =", 1]); expect(calls[3]).to.deep.equal([" Leaf subscribes =", 1]); expect(calls[4]).to.deep.equal([" Unsubscribes =", 0]); }); }); describe("tick", () => { it("should increment with each subscription and value, etc.", () => { spy = create({ defaultPlugins: false, ...options }); const subject = new Subject<string>(); let last = spy.tick; const subscription = subject.subscribe(); expect(spy.tick).to.be.above(last); last = spy.tick; subject.next("alice"); expect(spy.tick).to.be.above(last); last = spy.tick; subscription.unsubscribe(); expect(spy.tick).to.be.above(last); }); }); describe("version", () => { it("should return the package version", () => { spy = create({ defaultPlugins: false, ...options }); expect(spy).to.have.property("version", require("../package.json").version); }); }); describe("warnOnce", () => { it("should warn only once per message", () => { const logger = { log: sinon.stub(), warn: sinon.stub() }; spy = create({ defaultPlugins: false, ...options }); spy.warnOnce(logger, "there's a problem"); expect(logger.warn.callCount).to.equal(1); spy.warnOnce(logger, "there's a problem"); expect(logger.warn.callCount).to.equal(1); spy.warnOnce(logger, "there's another problem"); expect(logger.warn.callCount).to.equal(2); }); }); if (typeof window !== "undefined") { describe("window", () => { it("should create a global named 'spy' by default", () => { spy = create({ ...options }); expect(window).to.have.property("spy"); }); it("should create a global with the specified name", () => { spy = create({ global: "_spy", ...options }); expect(window).to.not.have.property("spy"); expect(window).to.have.property("_spy"); }); }); } afterEach(() => { if (spy) { spy.teardown(); } }); }); function stubPlugin(): Plugin { return { afterComplete: sinon.stub(), afterError: sinon.stub(), afterNext: sinon.stub(), afterSubscribe: sinon.stub(), afterUnsubscribe: sinon.stub(), beforeComplete: sinon.stub(), beforeError: sinon.stub(), beforeNext: sinon.stub(), beforeSubscribe: sinon.stub(), beforeUnsubscribe: sinon.stub(), flush: sinon.stub(), select: sinon.stub().returns(undefined), teardown: sinon.stub() } as any; }
the_stack
import ms from 'ms'; import SocketIOClient from 'socket.io-client'; import { isString, isInteger, debugLogger, toString } from '@terascope/utils'; import * as i from './interfaces'; import { Core } from './core'; import { newMsgId } from '../utils'; const _logger = debugLogger('teraslice-messaging:client'); export class Client extends Core { readonly socket: SocketIOClient.Socket; readonly clientId: string; readonly clientType: string; readonly serverName: string; readonly connectTimeout: number; readonly hostUrl: string; available: boolean; protected ready: boolean; protected serverShutdown: boolean; constructor(opts: i.ClientOptions, _connectTimeout?: number) { const { hostUrl, clientId, clientType, serverName, socketOptions = {}, connectTimeout, clientDisconnectTimeout, logger, ...coreOpts } = opts; super({ logger: logger ? logger.child({ module: 'messaging:client', }) : _logger, ...coreOpts, }); if (!isString(hostUrl)) { throw new Error('Messenger.Client requires a valid hostUrl'); } if (!isString(clientId)) { throw new Error('Messenger.Client requires a valid clientId'); } if (!isString(clientType)) { throw new Error('Messenger.Client requires a valid clientType'); } if (!isString(serverName)) { throw new Error('Messenger.Client requires a valid serverName'); } if (!isInteger(connectTimeout)) { throw new Error('Messenger.Client requires a valid connectTimeout'); } // The pingTimeout should be the client disconnect timeout // (which is greater than the pingTimeout on the server which uses actionTimeout) // to avoid disconnecting from the server before the connection // is considered const pingTimeout = clientDisconnectTimeout; const pingInterval = clientDisconnectTimeout + this.networkLatencyBuffer; const options: SocketIOClient.ConnectOpts = Object.assign({}, socketOptions, { autoConnect: false, forceNew: true, pingTimeout, pingInterval, perMessageDeflate: false, query: { clientId, clientType }, timeout: _connectTimeout }); this.socket = SocketIOClient(hostUrl, options); this.socket.on('error', (err: any) => { this.logger.error(err, 'unhandled socket.io-client error'); }); this.hostUrl = hostUrl; this.connectTimeout = connectTimeout; this.clientId = clientId; this.clientType = clientType; this.serverName = serverName; this.available = false; this.ready = false; this.serverShutdown = false; } onServerShutdown(fn: () => void): void { this.on('server:shutdown', () => { this.serverShutdown = true; try { fn(); } catch (err) { this.logger.error(err); } process.nextTick(() => { this.socket.close(); }); }); } async connect(): Promise<void> { if (this.socket.connected) { return; } await this._connect(this.connectTimeout); this.socket.on('reconnecting', () => { this.logger.debug(`client ${this.clientId} is reconnecting...`); this.ready = false; }); this.socket.on('reconnect', () => { this.logger.info(`client ${this.clientId} reconnected`); this.ready = true; this.emit('ready'); if (!this.available) return; process.nextTick(async () => { try { await this.sendAvailable(); } catch (err) { this.logger.warn(err, 'update availability on reconnect error'); } }); }); this.socket.on('disconnect', (reason: string) => { this.logger.info(`client ${this.clientId} disconnected`, reason ? { reason } : undefined); this.ready = false; }); this.socket.on('shutdown', () => { this.logger.debug(`server ${this.serverName} shutdown`); this.ready = false; this.serverShutdown = true; this.emit('server:shutdown'); }); this.socket.on('message:response', (msg: i.Message) => { this.emit(msg.id, { scope: msg.from, payload: msg, }); }); this.socket.on('connect', () => { this.logger.info(`client ${this.clientId} connected`); this.ready = true; this.emit('ready'); }); this.ready = true; this.emit('ready'); this.logger.debug(`client ${this.clientId} connect`); } private async _connect(remainingTimeout: number, attempt = 1): Promise<void> { const connectToStr = `${this.serverName} at ${this.hostUrl}`; if (this.socket.connected) { return; } if (attempt > 1) { this.logger.debug(`attempt #${attempt} connecting to ${connectToStr}`, { remainingTimeout }); } else { this.logger.debug(`attempting to connect to ${connectToStr}`); } const startTime = Date.now(); await new Promise<void>((resolve, reject) => { let timer: any; let cleanup: () => void; const onError = (err: any) => { const errStr = toString(err).replace('Error: ', ''); if (errStr.includes('xhr poll error')) { // it still connecting so this is probably okay this.logger.debug(`${errStr} when connecting to ${connectToStr}`); } else { this.logger.warn(`${errStr} when connecting to ${connectToStr}`); } }; const onTimeoutError = (timeout: number) => { this.logger.debug(`timeout of ${ms(timeout)} when connecting to ${connectToStr}, reconnecting...`); cleanup(); resolve(); }; cleanup = () => { clearTimeout(timer); this.socket.removeListener('connect_error', onError); this.socket.removeListener('connect_timeout', onTimeoutError); this.socket.removeListener('connect', onConnect); }; function onConnect() { cleanup(); resolve(); } this.socket.on('connect_error', onError); this.socket.once('connect_timeout', onTimeoutError); this.socket.once('connect', onConnect); this.socket.connect(); timer = setTimeout(() => { if (this.socket.connected) return; cleanup(); reject(new Error(`Unable to connect to ${connectToStr} after ${ms(this.connectTimeout)}`)); }, remainingTimeout); }); const elapsed = Date.now() - startTime; return this._connect(elapsed, attempt + 1); } async sendAvailable(payload?: i.Payload): Promise<i.Message|null|undefined> { if (this.available) return; this.available = true; return this.send(`client:${i.ClientState.Available}`, payload, { volatile: true, }); } async sendUnavailable(payload?: i.Payload): Promise<i.Message|null|undefined> { if (!this.available) return; this.available = false; return this.send(`client:${i.ClientState.Unavailable}`, payload, { volatile: true, }); } protected async send( eventName: string, payload: i.Payload = {}, options: i.SendOptions = { response: true } ): Promise<i.Message | null> { if (this.serverShutdown || this.closed) return null; if (!this.ready && !options.volatile) { const connected = this.socket.connected ? 'connected' : 'not-connected'; this.logger.debug(`server is not ready and ${connected}, waiting for the ready event`); await this.onceWithTimeout(`ready:${this.serverName}`); } const response = options.response != null ? options.response : true; const respondBy = Date.now() + this.getTimeout(options.timeout); const message: i.Message = { id: await newMsgId(), eventName, from: this.clientId, to: this.serverName, payload, volatile: options.volatile, response, respondBy, }; const responseMsg = this.handleSendResponse(message); this.socket.emit(eventName, message); return responseMsg; } emit(eventName: string, msg: i.ClientEventMessage = { payload: {} }): void { msg.scope = this.serverName; super.emit(`${eventName}`, msg as i.EventMessage); } isClientReady(): boolean { return !this.serverShutdown && this.ready; } async shutdown(): Promise<void> { if (this.isClientReady()) { try { await this.send( `client:${i.ClientState.Shutdown}`, {}, { volatile: true, response: false, timeout: 100, } ); } catch (err) { this.logger.error(err, 'client send shutdown error'); } } this.ready = false; if (this.socket.connected) { this.socket.close(); } this.close(); } // For testing purposes forceReconnect(): Promise<void> { return new Promise<void>((resolve) => { this.socket.io.once('reconnect', () => { resolve(); }); // @ts-expect-error this.socket.io.engine.close(); }); } }
the_stack
import * as _ from 'lodash'; import * as utils from 'strapi-utils'; import { NormalCollection } from './db/normal-collection'; import { FlatCollection } from './db/flat-collection'; import { ComponentCollection } from './db/component-collection'; import type { AttributeKey, ConnectorOptions, FlattenFn, ModelOptions, ModelTestFn, Strapi, StrapiAttribute, StrapiAttributeType, StrapiModel, StrapiModelRecord } from './types'; import { PickReferenceKeys, PopulatedByKeys, populateDoc, populateSnapshots } from './populate'; import { buildPrefixQuery } from './utils/prefix-query'; import type{ Collection } from './db/collection'; import { DocumentReference, FieldPath, Firestore } from '@google-cloud/firestore'; import type { Transaction, TransactionOpts } from './db/transaction'; import type { RelationHandler } from './utils/relation-handler'; import { buildRelations } from './relations'; import { getComponentModel } from './utils/components'; import { AttributeIndexInfo, buildIndexers, doesComponentRequireMetadata } from './utils/components-indexing'; import type { Snapshot } from './db/reference'; import { StatusError } from './utils/status-error'; import { makeTransactionRunner } from './utils/transaction-runner'; import { VirtualCollection } from './db/virtual-collection'; export const DEFAULT_CREATE_TIME_KEY = 'createdAt'; export const DEFAULT_UPDATE_TIME_KEY = 'updatedAt'; const { PUBLISHED_AT_ATTRIBUTE, CREATED_BY_ATTRIBUTE, UPDATED_BY_ATTRIBUTE, } = utils.contentTypes.constants; /** * Iterates each model in a the given of models. */ export function* eachModel<M extends StrapiModel<any> = FirestoreConnectorModel<any>>(models: StrapiModelRecord): Generator<{ model: M, target: object, key: string }> { for (const key of Object.keys(models)) { const model: M = models[key]; yield { model, target: models, key }; } } /** * Iterates all models in the Strapi instance. * @param strapiInstance Defaults to global Strapi */ export function* allModels<M extends StrapiModel<any> = FirestoreConnectorModel<any>>(strapiInstance = strapi): Generator<{ model: M, target: object, key: string }> { // Iterate components first because subsequent models // need to access the indexers yield* eachModel(strapiInstance.components); yield* eachModel(strapiInstance.models); yield* eachModel(strapiInstance.admin.models); for (const plugin of Object.keys(strapi.plugins)) { yield* eachModel(strapiInstance.plugins[plugin].models); } } /** * Firestore connector implementation of the Strapi model interface. */ export interface FirestoreConnectorModel<T extends object = object> extends StrapiModel<T> { options: Required<ModelOptions<T>>; defaultPopulate: PickReferenceKeys<T>[]; assocKeys: AttributeKey<T>[]; componentKeys: AttributeKey<T>[]; /** * If this model is a component, then this is a list of indexer * information for all of the indexed fields. */ indexers: AttributeIndexInfo[] | undefined; isComponent: boolean; relations: RelationHandler<T, any>[]; firestore: Firestore; db: Collection<T>; timestamps: [string, string] | false; /** * Gets the path of the field to store the metadata/index * map for the given repeatable component attribute. */ getMetadataMapKey(attrKey: AttributeKey<T>): string hasPK(obj: any): boolean; getPK(obj: any): string; getAttributePath(fieldOrPath: string | FieldPath): string getAttribute(path: string | FieldPath): StrapiAttribute | undefined getAttributeValue(path: string | FieldPath, snapshot: Pick<Snapshot<T>, 'id' | 'data'>): unknown runTransaction<TResult>(fn: (transaction: Transaction) => TResult | PromiseLike<TResult>, opts?: TransactionOpts): Promise<TResult>; populate<K extends PickReferenceKeys<T>>(data: Snapshot<T>, transaction: Transaction, populate?: K[]): Promise<PopulatedByKeys<T, K>>; populateAll<K extends PickReferenceKeys<T>>(datas: Snapshot<T>[], transaction: Transaction, populate?: K[]): Promise<PopulatedByKeys<T, K>[]>; } export interface FirestoreConnectorModelArgs { firestore: Firestore connectorOptions: Required<ConnectorOptions> strapi: Strapi } /** * Mounts the Firestore model implementation onto the existing instance of all Strapi models. * They are mounted onto the existing instance because that instance is already * propagated through many parts of Strapi's core. */ export async function mountModels(args: FirestoreConnectorModelArgs) { // Call the before mount hook for each model // then mount initialise all models onto the existing model instances const modelPromises: Promise<FirestoreConnectorModel>[] = []; for (const { model, target, key } of allModels<StrapiModel>(args.strapi)) { modelPromises.push( Promise.resolve() .then(() => args.connectorOptions.beforeMountModel(model)) .then(() => mountModel(target, key, model, args)) ); } const models = await Promise.all(modelPromises); // Build relations for (const model of models) { buildRelations(model, args.strapi); } // Call the after mount hook for each model await Promise.all(models.map(model => args.connectorOptions.afterMountModel(model))); } function mountModel<T extends object>(target: object, modelKey: string, mdl: StrapiModel<T>, { strapi, firestore, connectorOptions }: FirestoreConnectorModelArgs): FirestoreConnectorModel<T> { mdl.orm = 'firestore'; mdl.primaryKey = mdl.primaryKey || 'id'; mdl.primaryKeyType = mdl.primaryKeyType || 'string'; mdl.attributes = mdl.attributes || {}; mdl.collectionName = mdl.collectionName || mdl.globalId; const isComponent = mdl.modelType === 'component'; const opts: ModelOptions<T> = mdl.options || {}; const flattening = defaultFlattenOpts(mdl, opts, connectorOptions); mdl.collectionName = flattening?.collectionName || mdl.collectionName; const options: Required<ModelOptions<T>> = { ...opts, populateCreatorFields: opts.populateCreatorFields || false, timestamps: opts.timestamps || false, logQueries: opts.logQueries ?? connectorOptions.logQueries, singleId: flattening?.singleId || opts.singleId || connectorOptions.singleId, flatten: flattening != null, searchAttribute: defaultSearchAttrOpts(mdl, opts), maxQuerySize: flattening ? 0 : opts.maxQuerySize ?? connectorOptions.maxQuerySize, ensureComponentIds: opts.ensureComponentIds ?? connectorOptions.ensureComponentIds, allowNonNativeQueries: defaultAllowNonNativeQueries(mdl, opts, connectorOptions), metadataField: opts.metadataField || connectorOptions.metadataField, creatorUserModel: opts.creatorUserModel || connectorOptions.creatorUserModel, converter: opts.converter || {}, virtualDataSource: opts.virtualDataSource || null, onChange: opts.onChange || (() => {}), }; const timestamps: [string, string] | false = (options.timestamps && (typeof options.timestamps === 'boolean')) ? [DEFAULT_CREATE_TIME_KEY, DEFAULT_UPDATE_TIME_KEY] : options.timestamps; options.timestamps = timestamps; // Make sure any primary key attribute has the correct type // Normally this doesn't exist, but it may exist if the user has // used it to customise indexing of components if (mdl.attributes[mdl.primaryKey]) { const attr = mdl.attributes[mdl.primaryKey]; attr.type = mdl.primaryKeyType; } if (!mdl.uid.startsWith('strapi::') && mdl.modelType !== 'component') { if (utils.contentTypes.hasDraftAndPublish(mdl)) { mdl.attributes[PUBLISHED_AT_ATTRIBUTE] = { type: 'datetime', configurable: false, writable: true, visible: false, }; } const isPrivate = options.populateCreatorFields; const creatorModelAttr = typeof options.creatorUserModel === 'string' ? { model: options.creatorUserModel } : options.creatorUserModel; mdl.attributes[CREATED_BY_ATTRIBUTE] = { configurable: false, writable: false, visible: false, private: isPrivate, ...creatorModelAttr, }; mdl.attributes[UPDATED_BY_ATTRIBUTE] = { configurable: false, writable: false, visible: false, private: isPrivate, ...creatorModelAttr, }; } const componentKeys = (Object.keys(mdl.attributes) as AttributeKey<T>[]) .filter(key => { const { type } = mdl.attributes[key]; return type && ['component', 'dynamiczone'].includes(type); }); // Build indexers if this is a component model const indexers = buildIndexers(mdl); // Add all component's metadata keys as attributes on this model const getMetadataMapKey = typeof options.metadataField === 'string' ? (attrKey: AttributeKey<T>) => attrKey + options.metadataField : options.metadataField; Object.assign( mdl.attributes, buildMetadataAttributes(mdl, { componentKeys, getMetadataMapKey }), ); // Metadata attributes are configured as private and will // automatically be populated in the private attributes list const privateAttributes: AttributeKey<T>[] = utils.contentTypes.getPrivateAttributes(mdl); const assocKeys: AttributeKey<T>[] = (Object.keys(mdl.attributes) as AttributeKey<T>[]) .filter(alias => { const { model, collection } = mdl.attributes[alias]; return model || collection; }); const defaultPopulate: PickReferenceKeys<T>[] = (assocKeys as PickReferenceKeys<T>[]) .filter(alias => { const attr = mdl.attributes[alias]; return attr.autoPopulate ?? true; }); for (const attrKey of Object.keys(mdl.attributes)) { // Required for other parts of Strapi to work utils.models.defineAssociations(mdl.uid.toLowerCase(), mdl, mdl.attributes[attrKey], attrKey); } const hasPK = (obj: any) => { return _.has(obj, mdl.primaryKey) || _.has(obj, 'id'); } const getPK = (obj: any) => { return ((_.has(obj, mdl.primaryKey) ? obj[mdl.primaryKey] : obj.id)); } const populate: FirestoreConnectorModel<T>['populate'] = async (snap: Snapshot<T>, transaction: Transaction, populate = (defaultPopulate as any)) => { const data = snap.data(); if (!data) { throw new StatusError('entry.notFound', 404); } return await populateDoc(model, snap.ref, data, populate || model.defaultPopulate, transaction); }; const populateAll: FirestoreConnectorModel<T>['populateAll'] = async (snaps: Snapshot<T>[], transaction: Transaction, populate = (defaultPopulate as any)) => { return await populateSnapshots(snaps, populate, transaction); }; const query = (init: (qb: any) => void) => { let field!: string; let value!: string; let operator!: string; const qb = { where: (f: string, op: string, v: string) => { operator = op; field = f; value = v; } }; init(qb); if ((operator !== 'like') || !/^\w+%$/.test(value)) { throw new Error('An update to Strapi has broken `strapi-connector-firestore`. ' + 'Please create an issue at https://github.com/arrowheadapps/strapi-connector-firestore/issues, ' + 'or in the meantime, revert Strapi your version to the last working version.'); } // Remove '%' character from the end value = value.slice(0, -1); return { fetchAll: async () => { const { gte, lt } = buildPrefixQuery(value); const results = await strapi.query(modelKey).find({ [`${field}_gte`]: gte, [`${field}_lt`]: lt, }); return { toJSON: () => results } } }; }; const getAttributePath = (fieldOrPath: string | FieldPath): string => { let path: string; if (fieldOrPath instanceof FieldPath) { if (FieldPath.documentId().isEqual(fieldOrPath)) { return model.primaryKey; } path = fieldOrPath.toString(); } else { path = fieldOrPath; } if (path.endsWith('.id')) { // Special case: // We could encounter field path that refers to the "id" field of a reference // In this case we return the path to the reference itself, and the query value // should be coerced to a reference also for comparison const refPath = path.slice(0, -3); const attr = model.attributes[refPath]; if (attr && (attr.model || attr.collection)) { path = refPath; } } return path; }; const getAttribute = (fieldOrPath: string | FieldPath): StrapiAttribute | undefined => { const path = getAttributePath(fieldOrPath); if (path === model.primaryKey) { return { type: 'string' }; } else { return model.attributes[path]; } }; const getAttributeValue = (fieldOrPath: string | FieldPath, snapshot: Pick<Snapshot<T>, 'id' | 'data'>): unknown | undefined => { const path = getAttributePath(fieldOrPath); if (path === model.primaryKey) { return snapshot.id; } return _.get(snapshot.data(), path, undefined); }; const model: FirestoreConnectorModel<T> = Object.assign({}, mdl, { firestore, options, timestamps, relations: [], isComponent, privateAttributes, assocKeys, componentKeys, defaultPopulate, indexers, getMetadataMapKey, getAttributePath, getAttribute, getAttributeValue, // We assign this next // The constructors need these other values to be populated onto the model first db: null!, hasPK, getPK, runTransaction: makeTransactionRunner(firestore, options, connectorOptions), populate, populateAll, /** * HACK: * For `strapi-plugin-content-manager` which accesses the raw * ORM layer and only knows about mongoose and bookshelf connectors. * See: https://github.com/strapi/strapi/blob/535fa25311a2caa469a13d173d710a7eba6d5ecc/packages/strapi-plugin-content-manager/services/utils/store.js#L52-L68 * * It seems that the aim here is to emulate searching for * a prefix in the `key` field. * * ``` * return model * .query(qb => { * qb.where('key', 'like', `${key}%`); * }) * .fetchAll() * .then(config => config && config.toJSON()) * .then(results => results.map(({ value }) => JSON.parse(value))); * ``` */ query, }); model.db = isComponent ? new ComponentCollection<T>(model) : opts.virtualDataSource ? new VirtualCollection<T>(model) : flattening ? new FlatCollection<T>(model) : new NormalCollection<T>(model) // Mimic built-in connectors // They re-assign an (almost) identical copy of the model object // Without this, there is an infinite recursion loop in the `privateAttributes` // property getter target[modelKey] = model; Object.assign(mdl, _.omit(model, ['privateAttributes'])) return model; } function defaultAllowNonNativeQueries<T extends object>(model: StrapiModel<T>, options: ModelOptions<T>, connectorOptions: Required<ConnectorOptions>) { if (options.allowNonNativeQueries === undefined) { const rootAllow = connectorOptions.allowNonNativeQueries; if (typeof rootAllow === 'boolean') { return rootAllow; } const tests = _.castArray(rootAllow) .map(test => { if (typeof test === 'function') { return test; } const regex = test instanceof RegExp ? test : new RegExp(test); const tester: ModelTestFn = (model) => regex.test(model.uid); return tester; }) .map(tester => { return tester(model); }); return tests.some(t => t); } else { return options.allowNonNativeQueries; } } interface FlattenResult { collectionName: string | null singleId: string } function defaultFlattenOpts<T extends object>(model: StrapiModel<T>, options: ModelOptions<T>, connectorOptions: Required<ConnectorOptions>): FlattenResult | null { const singleId = options.singleId || connectorOptions.singleId; const result: FlattenResult = { collectionName: null, singleId, }; if (options.flatten === undefined) { const { flattenModels } = connectorOptions; if (typeof flattenModels === 'boolean') { return flattenModels ? result : null; } const tests = _.castArray(flattenModels) .map(test => { let testFn: FlattenFn if (typeof test === 'function') { testFn = test; } else { const regex = test instanceof RegExp ? test : new RegExp(test); testFn = (model) => regex.test(model.uid) ? singleId : null; } const flatten = testFn(model); if (!flatten) { return null; } if (flatten instanceof DocumentReference) { return flatten.path; } return (typeof flatten === 'string') ? flatten : singleId; }); const path = tests.find(test => test != null); if (path) { const i = path.lastIndexOf('/'); return { collectionName: (i === -1) ? null : path.slice(0, i), singleId: (i === -1) ? path : path.slice(i + 1), }; } return null; } else { return options.flatten ? result : null; } } function defaultSearchAttrOpts<T extends object>(model: StrapiModel<any>, options: ModelOptions<T>) { const searchAttr = options.searchAttribute || ''; if (searchAttr) { const type: StrapiAttributeType | undefined = (searchAttr === model.primaryKey) ? 'uid' : model.attributes[searchAttr]?.type; const notAllowed: StrapiAttributeType[] = [ 'password', 'dynamiczone', 'component', ]; if (!type || notAllowed.includes(type)) { throw new Error(`The search attribute "${searchAttr}" does not exist on the model ${model.uid} or is of an unsupported type.`); } } return searchAttr; } /** * Build attributes for the metadata map fields. */ function buildMetadataAttributes<T extends object>(model: StrapiModel<T>, { componentKeys, getMetadataMapKey }: Pick<FirestoreConnectorModel<T>, 'componentKeys'> & Pick<FirestoreConnectorModel<T>, 'getMetadataMapKey'>): { [key: string]: StrapiAttribute } { const attributes: { [key: string]: StrapiAttribute } = {}; if (model.modelType !== 'component') { for (const alias of componentKeys) { const attr = model.attributes[alias]; if (!doesComponentRequireMetadata(attr)) { continue; } const mapKey = getMetadataMapKey(alias); if (mapKey in model.attributes) { throw new Error(`The metadata field "${mapKey}" in model "${model.uid}" conflicts with an existing attribute.`); } const models = attr.component ? [attr.component] : (attr.components || []); for (const modelName of models) { // We rely on component models being mounted first const { indexers } = getComponentModel(modelName); for (const info of indexers!) { for (const key of Object.keys(info.indexers)) { const attrPath = `${mapKey}.${key}`; // Other Strapi internals would get confused by the presence of fields if the value is undefined const attrValue: StrapiAttribute = _.omitBy({ collection: info.attr.model || info.attr.collection, via: info.attr.via, type: info.attr.type, plugin: info.attr.plugin, isMeta: true, repeatable: true, private: true, configurable: false, writable: false, visible: false, }, value => value === undefined); const existingAttrValue = attributes[attrPath]; if (existingAttrValue) { if (existingAttrValue.collection && attrValue.collection && (existingAttrValue.collection !== attrValue.collection)) { // Consider different collections as polymorphic existingAttrValue.collection = attrValue.collection = '*'; } // Make sure all overlapping indexed attribute in dynamic-zone components are compatible // Required so that we know how to coerce the metadata map back and forth from Firestore if (!_.isEqual(attributes[attrPath], attrValue)) { throw new Error( `The indexed attribute "${info.alias}" of component "${modelName}" is not compatible with an indexed attribute of another component. ` + `The parent attribute is "${alias}" in model "${model.uid}"` ); } } attributes[attrPath] = attrValue; // Add the empty indicator meta attribute // This is so that we can query for "empty" without relying on inequality operators, which imposes more restrictions on sorting etc attributes[`${attrPath}$empty`] = { type: 'boolean', isMeta: true, repeatable: true, private: true, configurable: false, writable: false, visible: false, }; // Set layout config on the model so that the attribute is hidden _.set(model, ['config', 'attributes', attrPath], { hidden: true }); } } } } } return attributes; }
the_stack
import { ProxyConfigWithDefaults } from './applyConfigDefaults'; import { addHostEntry, removeHostEntry, portProxy, getPortProxies, stopPortProxy } from './adminRequests'; import { registerCleanup } from './cleanupQueue'; import { preloadCertForHost } from './getCertForHost'; import getPort from 'get-port'; import { getProxyResponse } from './getProxyResponse'; import { Server, Request, ResponseToolkit } from '@hapi/hapi'; import * as http from 'http'; import { createTLSListener } from './listener'; import { log } from './logger'; import { ProxyConfig, ProxyResponse, WrappedRequest } from './ProxyConfig'; import * as url from 'url'; import { getCertPath } from './getCertPath'; import { IncomingRequest } from './IncomingRequest'; import { HttpResponse } from './httpRequest'; function ProxyCallError(originalError: Error) { this.error = originalError; } ProxyCallError.prototype = new Error(); const CATCHALL_ROUTE = /\/\{[a-zA-Z0-9$_]+\*\}/; export async function createProxy( proxyConfig: ProxyConfigWithDefaults ): Promise<Server> { let listener; let hostname = proxyConfig.localParsedUrl.hostname; let tls = proxyConfig.localParsedUrl.protocol === 'https:'; let port: number = proxyConfig.localParsedUrl.port ? parseInt(proxyConfig.localParsedUrl.port, 10) : tls ? 443 : 80; if (hostname && proxyConfig.writeEtcHosts) { log.info(`Writing /etc/hosts entry for ${hostname}`); const hostsEntryHostname = hostname; const result = await addHostEntry(hostsEntryHostname); if (result.success && result.added) { registerCleanup(() => removeHostEntry(hostsEntryHostname)); } } const certificatePath = await getCertPath(); // Preload/precreate the certificate // This helps speed up the first request to the host, and improves the success rate of the // first request. We ignore that it might not be needed, as we need to pass it to the portProxy anyway, // so it needs to be set to something if (tls && hostname) { await preloadCertForHost(certificatePath, hostname, {}); } if (proxyConfig.createPrivilegedPortProxy && port < 1024) { // Check if there's already a privileged port proxy on the right port const proxiedPrivilegedPorts = await getPortProxies(); if ( proxiedPrivilegedPorts[port] && proxiedPrivilegedPorts[port].tls === tls ) { port = proxiedPrivilegedPorts[port].localPort; } else { if ( proxiedPrivilegedPorts[port] && proxiedPrivilegedPorts[port].tls !== tls ) { // There is a proxied privileged port, but it's either TLS and we don't want TLS or vice versa // So just stop it and create a new one await stopPortProxy(port); } const localPort = await getPort(); log.info( `Proxying privileged port for ${url.format( proxyConfig.localParsedUrl )} to local port ${localPort}` ); const portProxyResult = await portProxy( url.format(proxyConfig.localParsedUrl), localPort, certificatePath, proxyConfig.cors ); if (!portProxyResult.data.success) { switch (portProxyResult.data.code) { case 'EADDRINUSE': log.error( "Error starting privileged port listener, the port is in use. Check if there's another admin server still running from a previous process" ); break; case 'EACCESS': log.error( "Error starting privileged port listener - the admin server doesn't have rights to listen on the low numbered port. This is strange, and is probably a bug somewhere." ); break; default: log.error( 'Error starting privileged port listener: ' + portProxyResult.data.message ); break; } throw new Error('Error starting admin server'); } port = localPort; } // Disable tls for the local (non-admin) server tls = false; } if (tls) { listener = createTLSListener({ certPath: certificatePath }); } else { listener = http.createServer(); } const server = new Server({ port, listener, tls }); addRoutes(server, proxyConfig); server.events.on('log', (event, tags) => { if (tags.error) { let message = event.error ? (event.error as any).message : 'unknown'; if (message.includes('alert bad certificate')) { message = `${message} intervene attempts to trust the certificate with the operating system when supported. This works for some browsers but not all (e.g. Firefox). For Firefox, open the requested URL in your browser and add a security exception for the certificate. For Chrome on Linux, make sure you have certutil available - package libnss3-tools under Debian based distributions (e.g. Ubuntu) and restart intervene. For other browsers or operating systems, refer to your browser or tool documentation about accessing URLs with untrusted certificates. `; } log.error(`Server error: ${message}`); } else { log.error((event.error as any).message); } }); if (proxyConfig.onShutdown) { registerCleanup(proxyConfig.onShutdown); } return server; } function addRoutes(server: Server, proxyConfig: ProxyConfigWithDefaults) { const targetUrl = url.parse(proxyConfig.target); let catchAllRouteDefined = false; const routes = proxyConfig.routes || {}; for (const routePath in routes) { const { method, path } = parseRoutePath(routePath); if (method === '*' && CATCHALL_ROUTE.test(path)) { catchAllRouteDefined = true; } const response: any = routes[routePath]; if (typeof response === 'string' || typeof response === 'object') { server.route({ method, path, options: { cors: proxyConfig.cors, handler(request, h) { return h.response(response); } } }); } if (typeof response === 'function') { server.route({ method, path, options: { cors: proxyConfig.cors, async handler(request, h) { const wrappedRequest = createWrappedRequest( proxyConfig, request, targetUrl ); try { const result = await response(wrappedRequest, h, async () => { return getProxyResponse(proxyConfig, wrappedRequest).catch( (e) => { throw new ProxyCallError(e); } ); }); if (result && result instanceof HttpResponse) { return handleProxyResponse(result as ProxyResponse, h); } return result; } catch (e) { let message; if (e instanceof ProxyCallError) { e = (e as any).error; message = `Proxy call to target failed for route ${method} ${path}`; log.error( `Proxy call to target failed for route ${method} ${path}: ${e}`, e ); } else { message = `Error in intervene handler function for route ${method} ${path}`; log.error( `Error in handler for route ${method} ${path}: ${e}`, e ); } return h .response({ statusCode: 500, message, error: e.toString() }) .code(500); } } } }); } } if (!catchAllRouteDefined) { server.route({ method: '*', path: '/{path*}', options: { cors: proxyConfig.cors, async handler(request, h) { try { let proxyResponse; try { proxyResponse = await getProxyResponse( proxyConfig, createWrappedRequest(proxyConfig, request, targetUrl) ); } catch (e) { throw new ProxyCallError(e); } return handleProxyResponse(proxyResponse, h); } catch (e) { let message; if (e instanceof ProxyCallError) { message = 'Proxy call to target failed in catch-all route'; e = (e as any).error; } else { message = 'Error in catch-all route'; } log.error(`${message}: ${e}`, e); return h .response({ statusCode: 500, message, error: e.toString() }) .code(500); } } } }); } } function handleProxyResponse(proxyResponse: ProxyResponse, h: ResponseToolkit) { const res = h.response(proxyResponse.getCalculatedRawResponse()); res.type(proxyResponse.contentType); res.code(proxyResponse.statusCode); for (const name in proxyResponse.headers) { switch (name) { // We don't want to copy these headers, they don't make sense with // the proxied response case 'transfer-encoding': // Transfer encoding doesn't make sense - it's always just straight, no chunked etc case 'content-length': // Content-length could have changed, so we'll skip that // TODO: We could & should actually update it to the new length now case 'content-encoding': // Content-encoding is now plain, as it has been gunzipped, inflated or brotli-decompressed continue; default: const header = proxyResponse.headers[name]; if (typeof header === 'string') { res.header(name, header); } else if (Array.isArray(header)) { header.forEach((headerValue) => res.header(name.toLowerCase(), headerValue, { append: true }) ); } } } return res; } function createWrappedRequest( proxyConfig: ProxyConfig, request: Request, targetUrl: url.UrlWithStringQuery ): WrappedRequest { const parsedRequestUrl = url.parse(url.format(request.url), true); const requestUrl = { ...targetUrl, path: undefined, pathname: request.url.pathname, query: parsedRequestUrl.query }; return new IncomingRequest({ method: request.method.toUpperCase() as any, url: requestUrl, params: request.params, headers: request.headers, overrideHeaders: { ...proxyConfig.targetHeaders }, payload: request.payload, state: request.state }); } function parseRoutePath(routePath: string): { method: string; path: string } { let [method, path] = routePath.split(' '); if (!path) { path = method; method = 'GET'; } return { method, path }; }
the_stack
import * as THREE from 'three'; import type { PerspectiveCamera } from 'three'; import { EphemPresets } from './EphemPresets'; import { Orbit } from './Orbit'; import { getFullTextureUrl } from './util'; import { rescaleArray, rescaleNumber } from './Scale'; import type { Coordinate3d } from './Coordinates'; import type { Ephem } from './Ephem'; import type { EphemerisTable } from './EphemerisTable'; import type { Simulation, SimulationContext, SimulationObject, } from './Simulation'; export interface SpaceObjectOptions { position?: Coordinate3d; scale?: [number, number, number]; particleSize?: number; labelText?: string; labelUrl?: string; hideOrbit?: boolean; axialTilt?: number; color?: number; radius?: number; levelsOfDetail?: { radii: number; segments: number }[]; atmosphere?: { color?: number; innerSizeRatio?: number; outerSizeRatio?: number; enable?: boolean; }; orbitPathSettings?: { leadDurationYears?: number; trailDurationYears?: number; numberSamplePoints?: number; }; ephem?: Ephem; ephemTable?: EphemerisTable; textureUrl?: string; basePath?: string; rotation?: { enable: boolean; period: number; speed?: number; lambdaDeg?: number; betaDeg?: number; yorp?: number; phi0?: number; jd0?: number; }; shape?: { shapeUrl?: string; color?: number; }; ecliptic?: { lineColor?: number; displayLines?: boolean; }; theme?: { color?: number; orbitColor?: number; }; debug?: { showAxes: boolean; showGrid: boolean; }; } /** * @private * Minimum number of degrees per day an object must move in order for its * position to be updated in the visualization. */ // const MIN_DEG_MOVE_PER_DAY: number = 0.05; /** * @private * Number of milliseconds between label position updates. */ const LABEL_UPDATE_MS: number = 30; /** * @private * Converts [X, Y, Z] position in visualization to pixel coordinates. */ function toScreenXY( position: Coordinate3d, camera: PerspectiveCamera, canvas: HTMLCanvasElement, ): { x: number; y: number } { const pos = new THREE.Vector3(position[0], position[1], position[2]); pos.project(camera); return { x: ((pos.x + 1) * canvas.clientWidth) / 2, y: ((-pos.y + 1) * canvas.clientHeight) / 2, }; } /** * An object that can be added to a visualization. * @example * ``` * const myObject = viz.addObject('planet1', { * position: [0, 0, 0], * scale: [1, 1, 1], * particleSize: 5, * labelText: 'My object', * labelUrl: 'http://...', * hideOrbit: false, * ephem: new Spacekit.Ephem({...}), * textureUrl: '/path/to/spriteTexture.png', * basePath: '/base', * ecliptic: { * lineColor: 0xCCCCCC, * displayLines: false, * }, * theme: { * color: 0xFFFFFF, * orbitColor: 0x888888, * }, * }); * ``` */ export class SpaceObject implements SimulationObject { protected _id: string; protected _options: SpaceObjectOptions; protected _simulation: Simulation; protected _context: SimulationContext; protected _renderMethod?: | 'SPRITE' | 'PARTICLESYSTEM' | 'ROTATING_OBJECT' | 'SPHERE'; protected _initialized: boolean; private _object3js?: THREE.Object3D; private _useEphemTable: boolean; private _isStaticObject: boolean; private _label?: HTMLElement; private _showLabel: boolean; private _lastLabelUpdate: number; // private _lastPositionUpdate: number; private _position: Coordinate3d; private _orbitAround?: SpaceObject; private _scale: [number, number, number]; private _particleIndex?: number; // private _degreesPerDay?: number; private _orbitPath?: THREE.Object3D; private _eclipticLines?: THREE.Object3D; private _orbit?: Orbit; /** * @param {String} id Unique id of this object * @param {Object} options Options container * @param {Array.<Number>} options.position [X, Y, Z] heliocentric coordinates of object. Defaults to [0, 0, 0] * @param {Array.<Number>} options.scale Scale of object on each [X, Y, Z] axis. Defaults to [1, 1, 1] * @param {Number} options.particleSize Size of particle if this object is a Kepler object being represented as a particle. * @param {String} options.labelText Text label to display above object (set undefined for no label) * @param {String} options.labelUrl Label becomes a link that goes to this url. * @param {boolean} options.hideOrbit If true, don't show an orbital ellipse. Defaults false. * @param {Object} options.orbitPathSettings Contains settings for defining the orbit path * @param {Object} options.orbitPathSettings.leadDurationYears orbit path lead time in years * @param {Object} options.orbitPathSettings.trailDurationYears orbit path trail time in years * @param {Object} options.orbitPathSettings.numberSamplePoints number of * points to use when drawing the orbit line. Only applicable for * non-elliptical and ephemeris table orbits. * @param {Ephem} options.ephem Ephemerides for this orbit * @param {EphemerisTable} options.ephemTable ephemeris table object which represents look up ephemeris * @param {String} options.textureUrl Texture for sprite * @param {String} options.basePath Base path for simulation assets and data * @param {Object} options.ecliptic Contains settings related to ecliptic * @param {Number} options.ecliptic.lineColor Hex color of lines that run perpendicular to ecliptic. @see Orbit * @param {boolean} options.ecliptic.displayLines Whether to show ecliptic lines. Defaults false. * @param {Object} options.theme Contains settings related to appearance of orbit * @param {Number} options.theme.color Hex color of the object, if applicable * @param {Number} options.theme.orbitColor Hex color of the orbit * @param {Simulation} contextOrSimulation Simulation context or simulation object * @param {boolean} autoInit Automatically initialize this object. If false * you must call init() manually. */ constructor( id: string, options: SpaceObjectOptions, simulation: Simulation, autoInit: boolean = true, ) { this._id = id; this._options = options || {}; this._object3js = undefined; this._useEphemTable = this._options.ephemTable !== undefined; this._isStaticObject = !this._options.ephem && !this._useEphemTable; this._simulation = simulation; this._context = simulation.getContext(); this._label = undefined; this._showLabel = false; this._lastLabelUpdate = 0; // this._lastPositionUpdate = 0; this._position = rescaleArray(this._options.position || [0, 0, 0]); this._orbitAround = undefined; this._scale = this._options.scale || [1, 1, 1]; // The method of rendering used for this object (e.g. SPRITE, PARTICLESYSTEM). this._renderMethod = undefined; // The index of this particle in the KeplerParticles system, if applicable. this._particleIndex = undefined; // Number of degrees moved per day. Used to limit the number of orbit // updates for very slow moving objects. /* this._degreesPerDay = this._options.ephem ? this._options.ephem.get('n', 'deg') : undefined; */ this._initialized = false; if (autoInit && !this.init()) { console.warn(`SpaceObject ${id}: failed to initialize`); } } /** * Initializes label and three.js objects. Called automatically unless you've * set autoInit to false in constructor (this init is suppressed by some * child classes). */ init(): boolean { this.renderObject(); if (this._options.labelText) { const labelElt = this.createLabel(); this._simulation.getSimulationElement().appendChild(labelElt); this._label = labelElt; this._showLabel = true; } /** * Caching of THREE.js objects for orbitPath */ this._orbitPath = undefined; this._eclipticLines = undefined; this.update(this._simulation.getJd(), true /* force */); this._initialized = true; return true; } /** * @protected * Used by child classes to set the object that gets its position updated. * @param {THREE.Object3D} obj Any THREE.js object */ protected setPositionedObject(obj: THREE.Object3D) { this._object3js = obj; } /** * @private * Build the THREE.js object for this SpaceObject. */ private renderObject() { if (this.isStaticObject()) { if (!this._renderMethod) { // TODO(ian): It kinda sucks to have SpaceObject care about // renderMethod, which is set by children. // Create a stationary sprite. this._object3js = this.createSprite(); if (this._simulation) { // Add it all to visualization. this._simulation.addObject(this, false /* noUpdate */); } this._renderMethod = 'SPRITE'; } } else { // Create the orbit no matter what - it's used to get current position // for CPU-positioned objects (e.g. child RotatingObjects, SphereObjects, // ShapeObjects). // TODO(ian): Only do this if we need to compute orbit position on the // CPU or display an orbit path. this._orbit = this.createOrbit(); if (!this._options.hideOrbit && this._simulation) { // Add it all to visualization. this._simulation.addObject(this, false /* noUpdate */); } if (this._useEphemTable) { if (!this._renderMethod) { this._object3js = this.createSprite(); if (this._simulation) { this._simulation.addObject(this, true); } this._renderMethod = 'SPRITE'; } } if (!this._renderMethod) { if (!this._options.ephem) { throw new Error( 'Attempting to create a particle system, but ephemeris are not available.', ); } // Create a particle representing this object on the GPU. this._particleIndex = this._context.objects.particles.addParticle( this._options.ephem, { particleSize: this._options.particleSize, color: this.getColor(), }, ); this._renderMethod = 'PARTICLESYSTEM'; } } } /** * @private * Builds the label div and adds it to the visualization * @return {HTMLElement} A div that contains the label for this object */ private createLabel(): HTMLElement { const text = document.createElement('div'); text.className = 'spacekit__object-label'; const { labelText, labelUrl } = this._options; if (this._options.labelUrl) { text.innerHTML = `<div><a target="_blank" href="${labelUrl}">${labelText}</a></div>`; } else { text.innerHTML = `<div>${labelText}</div>`; } text.style.fontFamily = 'Arial'; text.style.fontSize = '12px'; text.style.color = '#fff'; text.style.position = 'absolute'; text.style.backgroundColor = '#0009'; text.style.outline = '1px solid #5f5f5f'; return text; } /** * @private * Updates the label's position * @param {Array.Number} newpos Position of the label in the visualization's * coordinate system */ private updateLabelPosition(newpos: Coordinate3d) { if (!this._label) { throw new Error('Attempted to update label position without a label'); } const label = this._label; const simulationElt = this._simulation.getSimulationElement(); const pos = toScreenXY( newpos, this._simulation.getViewer().get3jsCamera(), simulationElt, ); const loc = { left: pos.x, top: pos.y, right: pos.x + label.clientWidth, bottom: pos.y + label.clientHeight, }; if ( loc.left - 30 > 0 && loc.right + 20 < simulationElt.clientWidth && loc.top - 25 > 0 && loc.bottom < simulationElt.clientHeight ) { label.style.left = `${loc.left - label.clientWidth / 2}px`; label.style.top = `${loc.top - label.clientHeight - 8}px`; label.style.visibility = 'visible'; } else { label.style.visibility = 'hidden'; } } /** * @private * Builds the sprite for this object * @return {THREE.Sprite} A sprite object */ private createSprite(): THREE.Sprite { if (!this._options.textureUrl) { throw new Error('Cannot create sprite without a textureUrl'); } const fullTextureUrl = getFullTextureUrl( this._options.textureUrl, this._context.options.basePath, ); const texture = new THREE.TextureLoader().load(fullTextureUrl); texture.encoding = THREE.LinearEncoding; const sprite = new THREE.Sprite( new THREE.SpriteMaterial({ map: texture, blending: THREE.AdditiveBlending, depthWrite: false, color: this._options.theme ? this._options.theme.color : 0xffffff, }), ); const scale = rescaleArray(this._scale); sprite.scale.set(scale[0], scale[1], scale[2]); const position = this.getPosition(this._simulation.getJd()); sprite.position.set(position[0], position[1], position[2]); if (this.isStaticObject()) { sprite.updateMatrix(); sprite.matrixAutoUpdate = false; } return sprite; } /** * @private * Builds the {Orbit} for this object * @return {Orbit} An orbit object */ private createOrbit(): Orbit { if (this._orbit) { return this._orbit; } const ephem = this._useEphemTable ? this._options.ephemTable : this._options.ephem; if (!ephem) { throw new Error('Cannot create orbit without Ephem or EphemerisTable'); } return new Orbit(ephem, { orbitPathSettings: this._options.orbitPathSettings, color: this._options.theme ? this._options.theme.orbitColor : undefined, eclipticLineColor: this._options.ecliptic ? this._options.ecliptic.lineColor : undefined, }); } /** * @private * Determines whether to update the position of an update. Don't update if JD * threshold is less than a certain amount. * @param {Number} afterJd Next JD * @return {boolean} Whether to update */ private shouldUpdateObjectPosition(afterJd: number): boolean { // TODO(ian): Reenable this as a function of zoom level, because as you get // closer the chopiness gets more noticeable. return true; /* if (!this._degreesPerDay || !this._lastPositionUpdate) { return true; } const degMove = this._degreesPerDay * (afterJd - this._lastPositionUpdate); if (degMove < MIN_DEG_MOVE_PER_DAY) { return false; } return true; */ } /** * Make this object orbit another orbit. * @param {Object} spaceObj The SpaceObject that will serve as the origin of this object's orbit. */ orbitAround(spaceObj: SpaceObject) { this._orbitAround = spaceObj; } /** * Updates the position of this object. Applicable only if this object is a * sprite and not a particle type. * @param {Number} x X position * @param {Number} y Y position * @param {Number} z Z position */ setPosition(x: number, y: number, z: number) { this._position[0] = rescaleNumber(x); this._position[1] = rescaleNumber(y); this._position[2] = rescaleNumber(z); } /** * Gets the visualization coordinates of this object at a given time. * @param {Number} jd JD date * @return {Array.<Number>} [X, Y,Z] coordinates */ getPosition(jd: number): Coordinate3d { const pos = this._position; if (!this._orbit) { // Default implementation, a static object. return pos; } const posModified = this._orbit.getPositionAtTime(jd); if (this._orbitAround) { const parentPos = this._orbitAround.getPosition(jd); return [ pos[0] + posModified[0] + parentPos[0], pos[1] + posModified[1] + parentPos[1], pos[2] + posModified[2] + parentPos[2], ]; } return [ pos[0] + posModified[0], pos[1] + posModified[1], pos[2] + posModified[2], ]; } /** * Updates the object and its label positions for a given time. * @param {Number} jd JD date * @param {boolean} force Whether to force an update regardless of checks for * movement. */ update(jd: number, force: boolean = false) { let newpos; if (this._label) { // Labels must update, even for static objects. // TODO(ian): Determine this based on orbit and camera position change. const meetsLabelUpdateThreshold = +new Date() - this._lastLabelUpdate > LABEL_UPDATE_MS; const shouldUpdateLabelPos = force || (this._showLabel && meetsLabelUpdateThreshold); if (shouldUpdateLabelPos) { if (!newpos) { newpos = this.getPosition(jd); } this.updateLabelPosition(newpos); this._lastLabelUpdate = +new Date(); } } if (this.isStaticObject() && !force) { return; } let shouldUpdateObjectPosition = false; if (this._object3js || this._label) { shouldUpdateObjectPosition = force || this.shouldUpdateObjectPosition(jd); } if (this._object3js && shouldUpdateObjectPosition) { newpos = this.getPosition(jd); this._object3js.position.set(newpos[0], newpos[1], newpos[2]); // this._lastPositionUpdate = jd; } const orbitNeedsRefreshing = !this._orbitPath || this._orbit?.needsUpdateForTime(jd); if (this._orbit && !this._options.hideOrbit && orbitNeedsRefreshing) { if (this._orbitPath) { this._simulation.getScene().remove(this._orbitPath); } this._orbitPath = this._orbit.getOrbitShape(jd, true); this._simulation.getScene().add(this._orbitPath); } const eclipticNeedsRefreshing = !this._eclipticLines || orbitNeedsRefreshing; if ( this._orbit && this._options.ecliptic && this._options.ecliptic.displayLines && eclipticNeedsRefreshing ) { if (this._eclipticLines) { this._simulation.getScene().remove(this._eclipticLines); } this._eclipticLines = this._orbit.getLinesToEcliptic(); this._simulation.getScene().add(this._eclipticLines); } if (this._orbitAround) { const parentPos = this._orbitAround.getPosition(jd); if (this._renderMethod === 'PARTICLESYSTEM') { // TODO(ian): Only do this when the origin changes this._context.objects.particles?.setParticleOrigin( this._particleIndex!, parentPos, ); } if (!this._options.hideOrbit) { this._orbitPath?.position.set(parentPos[0], parentPos[1], parentPos[2]); } if (!newpos) { newpos = this.getPosition(jd); } } } /** * Gets the THREE.js objects that represent this SpaceObject. The first * object returned is the primary object. Other objects may be returned, * such as rings, ellipses, etc. * @return {Array.<THREE.Object3D>} A list of THREE.js objects */ get3jsObjects(): THREE.Object3D[] { const ret = []; if (this._object3js) { ret.push(this._object3js); } if (this._orbit) { if (this._orbitPath) { ret.push(this._orbitPath); } if (this._eclipticLines) { ret.push(this._eclipticLines); } } return ret; } /** * Specifies the object that is used to compute the bounding box. By default, * this will be the first THREE.js object in this class's list of objects. * @return {THREE.Object3D} THREE.js object */ async getBoundingObject(): Promise<THREE.Object3D> { return Promise.resolve(this.get3jsObjects()[0]); } /** * Gets the color of this object. Usually this corresponds to the color of * the dot representing the object as well as its orbit. * @return {Number} A hexidecimal color value, e.g. 0xFFFFFF */ getColor(): number { if (this._options.theme) { return this._options.theme.color || 0xffffff; } return 0xffffff; } /** * Gets the {Orbit} object for this SpaceObject. * @return {Orbit} Orbit object */ getOrbit(): Orbit | undefined { return this._orbit; } /** * Gets label visilibity status. * @return {boolean} Whether label is visible. */ getLabelVisibility(): boolean { return this._showLabel; } /** * Toggle the visilibity of the label. * @param {boolean} val Whether to show or hide. */ setLabelVisibility(val: boolean) { if (!this._label) { throw new Error('Attempted to set label visibility without a label'); } if (val) { this._showLabel = true; this._label.style.display = 'block'; } else { this._showLabel = false; this._label.style.display = 'none'; } } /** * Gets the unique ID of this object. * @return {String} Unique ID */ getId(): string { return this._id; } /** * Determines whether object is static (can't change its position) or whether * its position can be updated (ie, it has ephemeris) * @return {boolean} Whether this object can change its position. */ isStaticObject(): boolean { return this._isStaticObject; } /** * Determines whether object is ready to be measured or added to scene. * @return {boolean} True if ready */ isReady(): boolean { return this._initialized; } removalCleanup() { if (this._label) { this._simulation.getSimulationElement().removeChild(this._label); this._label = undefined; } if (this._particleIndex !== undefined) { this._context?.objects.particles.hideParticle(this._particleIndex); } } } const DEFAULT_PLANET_TEXTURE_URL = '{{assets}}/sprites/smallparticle.png'; /** * Useful presets for creating SpaceObjects. * @example * ``` * const myobject = viz.addObject('planet1', Spacekit.SpaceObjectPresets.MERCURY); * ``` */ export const SpaceObjectPresets = { SUN: { textureUrl: '{{assets}}/sprites/lensflare0.png', position: [0, 0, 0], }, MERCURY: { textureUrl: DEFAULT_PLANET_TEXTURE_URL, theme: { color: 0x913cee, }, ephem: EphemPresets.MERCURY, }, VENUS: { textureUrl: DEFAULT_PLANET_TEXTURE_URL, theme: { color: 0xff7733, }, ephem: EphemPresets.VENUS, }, EARTH: { textureUrl: DEFAULT_PLANET_TEXTURE_URL, theme: { color: 0x009acd, }, ephem: EphemPresets.EARTH, }, MOON: { textureUrl: DEFAULT_PLANET_TEXTURE_URL, theme: { color: 0xffd700, }, ephem: EphemPresets.MOON, // Special params particleSize: 6, }, MARS: { textureUrl: DEFAULT_PLANET_TEXTURE_URL, theme: { color: 0xa63a3a, }, ephem: EphemPresets.MARS, }, JUPITER: { textureUrl: DEFAULT_PLANET_TEXTURE_URL, theme: { color: 0xffb90f, }, ephem: EphemPresets.JUPITER, }, SATURN: { textureUrl: DEFAULT_PLANET_TEXTURE_URL, theme: { color: 0x336633, }, ephem: EphemPresets.SATURN, }, URANUS: { textureUrl: DEFAULT_PLANET_TEXTURE_URL, theme: { color: 0x0099ff, }, ephem: EphemPresets.URANUS, }, NEPTUNE: { textureUrl: DEFAULT_PLANET_TEXTURE_URL, theme: { color: 0x3333ff, }, ephem: EphemPresets.NEPTUNE, }, PLUTO: { textureUrl: DEFAULT_PLANET_TEXTURE_URL, theme: { color: 0xccc0b0, }, ephem: EphemPresets.PLUTO, }, };
the_stack
const oneArray: string[] = [ "foreground", "errorForeground", "descriptionForeground", "focusBorder", "contrastBorder", "contrastActiveBorder", "selection.background", "textSeparator.foreground", "textLink.foreground", "textLink.activeForeground", "textPreformat.foreground", "textBlockQuote.background", "textBlockQuote.border", "textCodeBlock.background", "widget.shadow", "input.background", "input.foreground", "input.border", "inputOption.activeBorder", "input.placeholderForeground", "inputValidation.infoBackground", "inputValidation.infoForeground", "inputValidation.infoBorder", "inputValidation.warningBackground", "inputValidation.warningForeground", "inputValidation.warningBorder", "inputValidation.errorBackground", "inputValidation.errorForeground", "inputValidation.errorBorder", "dropdown.background", "dropdown.listBackground", "dropdown.foreground", "dropdown.border", "list.focusBackground", "list.focusForeground", "list.activeSelectionBackground", "list.activeSelectionForeground", "list.inactiveSelectionBackground", "list.inactiveSelectionForeground", "list.inactiveFocusBackground", "list.hoverBackground", "list.hoverForeground", "list.dropBackground", "list.highlightForeground", "list.invalidItemForeground", "list.errorForeground", "list.warningForeground", "listFilterWidget.background", "listFilterWidget.outline", "listFilterWidget.noMatchesOutline", "pickerGroup.foreground", "pickerGroup.border", "button.foreground", "button.background", "button.hoverBackground", "badge.background", "badge.foreground", "scrollbar.shadow", "scrollbarSlider.background", "scrollbarSlider.hoverBackground", "scrollbarSlider.activeBackground", "progressBar.background", "menu.border", "menu.foreground", "menu.background", "menu.selectionForeground", "menu.selectionBackground", "menu.selectionBorder", "menu.separatorBackground", "editor.background", "editor.foreground", "editorWidget.background", "editorWidget.border", "editorWidget.resizeBorder", "editor.selectionBackground", "editor.selectionForeground", "editor.inactiveSelectionBackground", "editor.selectionHighlightBackground", "editor.selectionHighlightBorder", "editor.findMatchBackground", "editor.findMatchHighlightBackground", "editor.findRangeHighlightBackground", "editor.findMatchBorder", "editor.findMatchHighlightBorder", "editor.findRangeHighlightBorder", "editor.hoverHighlightBackground", "editorHoverWidget.background", "editorHoverWidget.border", "editorHoverWidget.statusBarBackground", "editorLink.activeForeground", "diffEditor.insertedTextBackground", "diffEditor.removedTextBackground", "diffEditor.insertedTextBorder", "diffEditor.removedTextBorder", "diffEditor.border", "editor.snippetTabstopHighlightBackground", "editor.snippetTabstopHighlightBorder", "editor.snippetFinalTabstopHighlightBackround'", "editor.snippetFinalTabstopHighlightBorder", "breadcrumb.foreground", "breadcrumb.background", "breadcrumb.focusForeground", "breadcrumb.activeSelectionForeground", "breadcrumbPicker.background", "merge.currentHeaderBackground", "merge.currentContentBackground", "merge.incomingHeaderBackground", "merge.incomingContentBackground", "merge.commonHeaderBackground", "merge.commonContentBackground", "merge.border", "editorOverviewRuler.currentContentForeground", "editorOverviewRuler.incomingContentForeground", "editorOverviewRuler.commonContentForeground", "editorOverviewRuler.findMatchForeground", "editorOverviewRuler.selectionHighlightForeground", "foreground", "errorForeground", "descriptionForeground", "focusBorder", "contrastBorder", "contrastActiveBorder", "selection.background", "textSeparator.foreground", "textLink.foreground", "textLink.activeForeground", "textPreformat.foreground", "textBlockQuote.background", "textBlockQuote.border", "textCodeBlock.background", "widget.shadow", "input.background", "input.foreground", "input.border", "inputOption.activeBorder", "input.placeholderForeground", "inputValidation.infoBackground", "inputValidation.infoForeground", "inputValidation.infoBorder", "inputValidation.warningBackground", "inputValidation.warningForeground", "inputValidation.warningBorder", "inputValidation.errorBackground", "inputValidation.errorForeground", "inputValidation.errorBorder", "dropdown.background", "dropdown.listBackground", "dropdown.foreground", "dropdown.border", "list.focusBackground", "list.focusForeground", "list.activeSelectionBackground", "list.activeSelectionForeground", "list.inactiveSelectionBackground", "list.inactiveSelectionForeground", "list.inactiveFocusBackground", "list.hoverBackground", "list.hoverForeground", "list.dropBackground", "list.highlightForeground", "list.invalidItemForeground", "list.errorForeground", "list.warningForeground", "listFilterWidget.background", "listFilterWidget.outline", "listFilterWidget.noMatchesOutline", "pickerGroup.foreground", "pickerGroup.border", "button.foreground", "button.background", "button.hoverBackground", "badge.background", "badge.foreground", "scrollbar.shadow", "scrollbarSlider.background", "scrollbarSlider.hoverBackground", "scrollbarSlider.activeBackground", "progressBar.background", "menu.border", "menu.foreground", "menu.background", "menu.selectionForeground", "menu.selectionBackground", "menu.selectionBorder", "menu.separatorBackground", "editor.background", "editor.foreground", "editorWidget.background", "editorWidget.border", "editorWidget.resizeBorder", "editor.selectionBackground", "editor.selectionForeground", "editor.inactiveSelectionBackground", "editor.selectionHighlightBackground", "editor.selectionHighlightBorder", "editor.findMatchBackground", "editor.findMatchHighlightBackground", "editor.findRangeHighlightBackground", "editor.findMatchBorder", "editor.findMatchHighlightBorder", "editor.findRangeHighlightBorder", "editor.hoverHighlightBackground", "editorHoverWidget.background", "editorHoverWidget.border", "editorHoverWidget.statusBarBackground", "editorLink.activeForeground", "diffEditor.insertedTextBackground", "diffEditor.removedTextBackground", "diffEditor.insertedTextBorder", "diffEditor.removedTextBorder", "diffEditor.border", "editor.snippetTabstopHighlightBackground", "editor.snippetTabstopHighlightBorder", "editor.snippetFinalTabstopHighlightBackround'", "editor.snippetFinalTabstopHighlightBorder", "breadcrumb.foreground", "breadcrumb.background", "breadcrumb.focusForeground", "breadcrumb.activeSelectionForeground", "breadcrumbPicker.background", "merge.currentHeaderBackground", "merge.currentContentBackground", "merge.incomingHeaderBackground", "merge.incomingContentBackground", "merge.commonHeaderBackground", "merge.commonContentBackground", "merge.border", "editorOverviewRuler.currentContentForeground", "editorOverviewRuler.incomingContentForeground", "editorOverviewRuler.commonContentForeground", "editorOverviewRuler.findMatchForeground", "editorOverviewRuler.selectionHighlightForeground" ]; const array = [...new Set(oneArray)].forEach(element => { console.log(`"${element.toString()}": "",`); }); /* "foreground": "", "errorForeground": "", "descriptionForeground": "", "focusBorder": "", "contrastBorder": "", "contrastActiveBorder": "", "selection.background": "", "textSeparator.foreground": "", "textLink.foreground": "", "textLink.activeForeground": "", "textPreformat.foreground": "", "textBlockQuote.background": "", "textBlockQuote.border": "", "textCodeBlock.background": "", "widget.shadow": "", "input.background": "", "input.foreground": "", "input.border": "", "inputOption.activeBorder": "", "input.placeholderForeground": "", "inputValidation.infoBackground": "", "inputValidation.infoForeground": "", "inputValidation.infoBorder": "", "inputValidation.warningBackground": "", "inputValidation.warningForeground": "", "inputValidation.warningBorder": "", "inputValidation.errorBackground": "", "inputValidation.errorForeground": "", "inputValidation.errorBorder": "", "dropdown.background": "", "dropdown.listBackground": "", "dropdown.foreground": "", "dropdown.border": "", "list.focusBackground": "", "list.focusForeground": "", "list.activeSelectionBackground": "", "list.activeSelectionForeground": "", "list.inactiveSelectionBackground": "", "list.inactiveSelectionForeground": "", "list.inactiveFocusBackground": "", "list.hoverBackground": "", "list.hoverForeground": "", "list.dropBackground": "", "list.highlightForeground": "", "list.invalidItemForeground": "", "list.errorForeground": "", "list.warningForeground": "", "listFilterWidget.background": "", "listFilterWidget.outline": "", "listFilterWidget.noMatchesOutline": "", "pickerGroup.foreground": "", "pickerGroup.border": "", "button.foreground": "", "button.background": "", "button.hoverBackground": "", "badge.background": "", "badge.foreground": "", "scrollbar.shadow": "", "scrollbarSlider.background": "", "scrollbarSlider.hoverBackground": "", "scrollbarSlider.activeBackground": "", "progressBar.background": "", "menu.border": "", "menu.foreground": "", "menu.background": "", "menu.selectionForeground": "", "menu.selectionBackground": "", "menu.selectionBorder": "", "menu.separatorBackground": "", "editor.background": "", "editor.foreground": "", "editorWidget.background": "", "editorWidget.border": "", "editorWidget.resizeBorder": "", "editor.selectionBackground": "", "editor.selectionForeground": "", "editor.inactiveSelectionBackground": "", "editor.selectionHighlightBackground": "", "editor.selectionHighlightBorder": "", "editor.findMatchBackground": "", "editor.findMatchHighlightBackground": "", "editor.findRangeHighlightBackground": "", "editor.findMatchBorder": "", "editor.findMatchHighlightBorder": "", "editor.findRangeHighlightBorder": "", "editor.hoverHighlightBackground": "", "editorHoverWidget.background": "", "editorHoverWidget.border": "", "editorHoverWidget.statusBarBackground": "", "editorLink.activeForeground": "", "diffEditor.insertedTextBackground": "", "diffEditor.removedTextBackground": "", "diffEditor.insertedTextBorder": "", "diffEditor.removedTextBorder": "", "diffEditor.border": "", "editor.snippetTabstopHighlightBackground": "", "editor.snippetTabstopHighlightBorder": "", "editor.snippetFinalTabstopHighlightBackround'": "", "editor.snippetFinalTabstopHighlightBorder": "", "breadcrumb.foreground": "", "breadcrumb.background": "", "breadcrumb.focusForeground": "", "breadcrumb.activeSelectionForeground": "", "breadcrumbPicker.background": "", "merge.currentHeaderBackground": "", "merge.currentContentBackground": "", "merge.incomingHeaderBackground": "", "merge.incomingContentBackground": "", "merge.commonHeaderBackground": "", "merge.commonContentBackground": "", "merge.border": "", "editorOverviewRuler.currentContentForeground": "", "editorOverviewRuler.incomingContentForeground": "", "editorOverviewRuler.commonContentForeground": "", "editorOverviewRuler.findMatchForeground": "", "editorOverviewRuler.selectionHighlightForeground": "", */
the_stack